blob: 4622d8c1dd26ce5fe020cfdd8451e8abfe34b737 [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 Zulaufd14743a2020-07-03 09:42:39 -0600329// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
330// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
331// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700332static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700333static const SyncStageAccessFlags kColorAttachmentAccessScope =
334 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
335 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
336 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
337 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700338static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
339 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 -0700340static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
341 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
342 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
343 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700344static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700345static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600346
John Zulauf8e3c3e92021-01-06 11:19:36 -0700347ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700348 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700349 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
350 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
351 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
352
John Zulaufee984022022-04-13 16:39:50 -0600353// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
354static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600355
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600356static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600357
John Zulaufcb7e1672022-05-04 13:46:08 -0600358VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600359 if (size == VK_WHOLE_SIZE) {
360 return (whole_size - offset);
361 }
362 return size;
363}
364
John Zulauf3e86bf02020-09-12 10:47:57 -0600365static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
366 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
367}
368
John Zulauf16adfc92020-04-08 10:28:33 -0600369template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600370static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600371 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
372}
373
John Zulauf355e49b2020-04-24 15:11:15 -0600374static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600375
John Zulauf3e86bf02020-09-12 10:47:57 -0600376static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
377 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
378}
379
380static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
381 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
382}
383
John Zulauf4a6105a2020-11-17 15:11:05 -0700384// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
385//
John Zulauf10f1f522020-12-18 12:00:35 -0700386// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
387//
John Zulauf4a6105a2020-11-17 15:11:05 -0700388// Usage:
389// Constructor() -- initializes the generator to point to the begin of the space declared.
390// * -- the current range of the generator empty signfies end
391// ++ -- advance to the next non-empty range (or end)
392
393// A wrapper for a single range with the same semantics as the actual generators below
394template <typename KeyType>
395class SingleRangeGenerator {
396 public:
397 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700398 const KeyType &operator*() const { return current_; }
399 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700400 SingleRangeGenerator &operator++() {
401 current_ = KeyType(); // just one real range
402 return *this;
403 }
404
405 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
406
407 private:
408 SingleRangeGenerator() = default;
409 const KeyType range_;
410 KeyType current_;
411};
412
John Zulaufae842002021-04-15 18:20:55 -0600413// Generate the ranges that are the intersection of range and the entries in the RangeMap
414template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
415class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700416 public:
John Zulaufd5115702021-01-18 12:34:33 -0700417 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600418 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700419 // Default construction for KeyType *must* be empty range
420 assert(current_.empty());
421 }
John Zulaufae842002021-04-15 18:20:55 -0600422 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700423 SeekBegin();
424 }
John Zulaufae842002021-04-15 18:20:55 -0600425 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700426
John Zulauf4a6105a2020-11-17 15:11:05 -0700427 const KeyType &operator*() const { return current_; }
428 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600429 MapRangesRangeGenerator &operator++() {
430 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700431 UpdateCurrent();
432 return *this;
433 }
434
John Zulaufae842002021-04-15 18:20:55 -0600435 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700436
John Zulaufae842002021-04-15 18:20:55 -0600437 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700438 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600439 if (map_pos_ != map_->cend()) {
440 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700441 } else {
442 current_ = KeyType();
443 }
444 }
445 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600446 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700447 UpdateCurrent();
448 }
John Zulaufae842002021-04-15 18:20:55 -0600449
450 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
451 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
452 template <typename Pred>
453 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
454 do {
455 ++map_pos_;
456 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
457 UpdateCurrent();
458 return *this;
459 }
460
John Zulauf4a6105a2020-11-17 15:11:05 -0700461 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600462 const RangeMap *map_;
463 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700464 KeyType current_;
465};
John Zulaufd5115702021-01-18 12:34:33 -0700466using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600467using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700468
John Zulaufae842002021-04-15 18:20:55 -0600469// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
470template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
471class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
472 public:
473 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
474 // Default constructed is safe to dereference for "empty" test, but for no other operation.
475 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
476 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
477 : Base(filter, range), pred_(pred) {}
478 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
479
480 PredicatedMapRangesRangeGenerator &operator++() {
481 Base::PredicatedIncrement(pred_);
482 return *this;
483 }
484
485 protected:
486 Predicate pred_;
487};
John Zulauf4a6105a2020-11-17 15:11:05 -0700488
489// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600490// Templated to allow for different Range generators or map sources...
491template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700492class FilteredGeneratorGenerator {
493 public:
John Zulaufd5115702021-01-18 12:34:33 -0700494 // Default constructed is safe to dereference for "empty" test, but for no other operation.
495 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
496 // Default construction for KeyType *must* be empty range
497 assert(current_.empty());
498 }
John Zulaufae842002021-04-15 18:20:55 -0600499 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700500 SeekBegin();
501 }
John Zulaufd5115702021-01-18 12:34:33 -0700502 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700503 const KeyType &operator*() const { return current_; }
504 const KeyType *operator->() const { return &current_; }
505 FilteredGeneratorGenerator &operator++() {
506 KeyType gen_range = GenRange();
507 KeyType filter_range = FilterRange();
508 current_ = KeyType();
509 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
510 if (gen_range.end > filter_range.end) {
511 // if the generated range is beyond the filter_range, advance the filter range
512 filter_range = AdvanceFilter();
513 } else {
514 gen_range = AdvanceGen();
515 }
516 current_ = gen_range & filter_range;
517 }
518 return *this;
519 }
520
521 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
522
523 private:
524 KeyType AdvanceFilter() {
525 ++filter_pos_;
526 auto filter_range = FilterRange();
527 if (filter_range.valid()) {
528 FastForwardGen(filter_range);
529 }
530 return filter_range;
531 }
532 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700533 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700534 auto gen_range = GenRange();
535 if (gen_range.valid()) {
536 FastForwardFilter(gen_range);
537 }
538 return gen_range;
539 }
540
541 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700542 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700543
544 KeyType FastForwardFilter(const KeyType &range) {
545 auto filter_range = FilterRange();
546 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700547 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700548 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
549 if (retry_count < kRetryLimit) {
550 ++filter_pos_;
551 filter_range = FilterRange();
552 retry_count++;
553 } else {
554 // Okay we've tried walking, do a seek.
555 filter_pos_ = filter_->lower_bound(range);
556 break;
557 }
558 }
559 return FilterRange();
560 }
561
562 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
563 // faster.
564 KeyType FastForwardGen(const KeyType &range) {
565 auto gen_range = GenRange();
566 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700567 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700568 gen_range = GenRange();
569 }
570 return gen_range;
571 }
572
573 void SeekBegin() {
574 auto gen_range = GenRange();
575 if (gen_range.empty()) {
576 current_ = KeyType();
577 filter_pos_ = filter_->cend();
578 } else {
579 filter_pos_ = filter_->lower_bound(gen_range);
580 current_ = gen_range & FilterRange();
581 }
582 }
583
John Zulaufae842002021-04-15 18:20:55 -0600584 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700585 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600586 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700587 KeyType current_;
588};
589
590using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
591
John Zulauf5c5e88d2019-12-26 11:22:02 -0700592
John Zulauf3e86bf02020-09-12 10:47:57 -0600593ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
594 VkDeviceSize stride) {
595 VkDeviceSize range_start = offset + first_index * stride;
596 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600597 if (count == UINT32_MAX) {
598 range_size = buf_whole_size - range_start;
599 } else {
600 range_size = count * stride;
601 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600602 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600603}
604
locke-lunarg654e3692020-06-04 17:19:15 -0600605SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
606 VkShaderStageFlagBits stage_flag) {
607 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
608 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
609 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
610 }
611 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
612 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
613 assert(0);
614 }
615 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
616 return stage_access->second.uniform_read;
617 }
618
619 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
620 // Because if write hazard happens, read hazard might or might not happen.
621 // But if write hazard doesn't happen, read hazard is impossible to happen.
622 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700623 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600624 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700625 // TODO: sampled_read
626 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600627}
628
locke-lunarg37047832020-06-12 13:44:45 -0600629bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
630 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
631 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
632 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
633 ? true
634 : false;
635}
636
637bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
638 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
639 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
640 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
641 ? true
642 : false;
643}
644
John Zulauf355e49b2020-04-24 15:11:15 -0600645// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600646template <typename Action>
647static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
648 Action &action) {
649 // At this point the "apply over range" logic only supports a single memory binding
650 if (!SimpleBinding(image_state)) return;
651 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600652 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700653 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
Aitor Camachoe67f2c72022-06-08 14:41:58 +0200654 image_state.createInfo.extent, base_address, false);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600655 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700656 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600657 }
658}
659
John Zulauf7635de32020-05-29 17:14:15 -0600660// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
661// Used by both validation and record operations
662//
663// The signature for Action() reflect the needs of both uses.
664template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700665void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
666 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600667 const auto &rp_ci = rp_state.createInfo;
668 const auto *attachment_ci = rp_ci.pAttachments;
669 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
670
671 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
672 const auto *color_attachments = subpass_ci.pColorAttachments;
673 const auto *color_resolve = subpass_ci.pResolveAttachments;
674 if (color_resolve && color_attachments) {
675 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
676 const auto &color_attach = color_attachments[i].attachment;
677 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
678 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
679 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700680 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
681 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600682 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700683 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
684 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600685 }
686 }
687 }
688
689 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700690 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600691 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
692 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
693 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
694 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
695 const auto src_ci = attachment_ci[src_at];
696 // The formats are required to match so we can pick either
697 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
698 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
699 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600700
701 // Figure out which aspects are actually touched during resolve operations
702 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700703 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600704 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600705 aspect_string = "depth/stencil";
706 } else if (resolve_depth) {
707 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700708 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600709 aspect_string = "depth";
710 } else if (resolve_stencil) {
711 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700712 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600713 aspect_string = "stencil";
714 }
715
John Zulaufd0ec59f2021-03-13 14:25:08 -0700716 if (aspect_string) {
717 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
718 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
719 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
720 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600721 }
722 }
723}
724
725// Action for validating resolve operations
726class ValidateResolveAction {
727 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700728 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
sjfricke0bea06e2022-06-05 09:22:26 +0900729 const CommandExecutionContext &exec_context, CMD_TYPE cmd_type)
John Zulauf7635de32020-05-29 17:14:15 -0600730 : render_pass_(render_pass),
731 subpass_(subpass),
732 context_(context),
John Zulaufbb890452021-12-14 11:30:18 -0700733 exec_context_(exec_context),
sjfricke0bea06e2022-06-05 09:22:26 +0900734 cmd_type_(cmd_type),
John Zulauf7635de32020-05-29 17:14:15 -0600735 skip_(false) {}
736 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 -0700737 const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
738 SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600739 HazardResult hazard;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700740 hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
John Zulauf7635de32020-05-29 17:14:15 -0600741 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +0900742 skip_ |= exec_context_.GetSyncState().LogError(
743 render_pass_, string_SyncHazardVUID(hazard.hazard),
744 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32 " to resolve attachment %" PRIu32
745 ". Access info %s.",
746 CommandTypeString(cmd_type_), string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name, src_at,
747 dst_at, exec_context_.FormatHazard(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600748 }
749 }
750 // Providing a mechanism for the constructing caller to get the result of the validation
751 bool GetSkip() const { return skip_; }
752
753 private:
754 VkRenderPass render_pass_;
755 const uint32_t subpass_;
756 const AccessContext &context_;
John Zulaufbb890452021-12-14 11:30:18 -0700757 const CommandExecutionContext &exec_context_;
sjfricke0bea06e2022-06-05 09:22:26 +0900758 CMD_TYPE cmd_type_;
John Zulauf7635de32020-05-29 17:14:15 -0600759 bool skip_;
760};
761
762// Update action for resolve operations
763class UpdateStateResolveAction {
764 public:
John Zulauf14940722021-04-12 15:19:02 -0600765 UpdateStateResolveAction(AccessContext &context, ResourceUsageTag tag) : context_(context), tag_(tag) {}
John Zulaufd0ec59f2021-03-13 14:25:08 -0700766 void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
767 AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600768 // Ignores validation only arguments...
John Zulaufd0ec59f2021-03-13 14:25:08 -0700769 context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600770 }
771
772 private:
773 AccessContext &context_;
John Zulauf14940722021-04-12 15:19:02 -0600774 const ResourceUsageTag tag_;
John Zulauf7635de32020-05-29 17:14:15 -0600775};
776
John Zulauf59e25072020-07-17 10:55:21 -0600777void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
John Zulauf14940722021-04-12 15:19:02 -0600778 const SyncStageAccessFlags &prior_, const ResourceUsageTag tag_) {
John Zulauf4fa68462021-04-26 21:04:22 -0600779 access_state = layer_data::make_unique<const ResourceAccessState>(*access_state_);
John Zulauf59e25072020-07-17 10:55:21 -0600780 usage_index = usage_index_;
781 hazard = hazard_;
782 prior_access = prior_;
783 tag = tag_;
784}
785
John Zulauf4fa68462021-04-26 21:04:22 -0600786void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
787 recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
788}
789
John Zulauf1d5f9c12022-05-13 14:51:08 -0600790void AccessContext::DeleteAccess(const AddressRange &address) { GetAccessStateMap(address.type).erase_range(address.range); }
791
John Zulauf540266b2020-04-06 18:54:53 -0600792AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
793 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600794 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600795 Reset();
796 const auto &subpass_dep = dependencies[subpass];
John Zulauf22aefed2021-03-11 18:14:35 -0700797 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
798 prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
John Zulauf355e49b2020-04-24 15:11:15 -0600799 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600800 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600801 const auto prev_pass = prev_dep.first->pass;
802 const auto &prev_barriers = prev_dep.second;
803 assert(prev_dep.second.size());
804 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
805 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700806 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600807
808 async_.reserve(subpass_dep.async.size());
809 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700810 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600811 }
John Zulauf22aefed2021-03-11 18:14:35 -0700812 if (has_barrier_from_external) {
813 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
814 prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
815 src_external_ = &prev_.back();
John Zulaufe5da6e52020-03-18 15:32:18 -0600816 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600817 if (subpass_dep.barrier_to_external.size()) {
818 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600819 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700820}
821
John Zulauf5f13a792020-03-10 07:31:21 -0600822template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700823HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, const Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600824 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600825 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600826 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600827
828 HazardResult hazard;
829 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
830 hazard = detector.Detect(prev);
831 }
832 return hazard;
833}
834
John Zulauf4a6105a2020-11-17 15:11:05 -0700835template <typename Action>
836void AccessContext::ForAll(Action &&action) {
837 for (const auto address_type : kAddressTypes) {
838 auto &accesses = GetAccessStateMap(address_type);
John Zulauf1d5f9c12022-05-13 14:51:08 -0600839 for (auto &access : accesses) {
John Zulauf4a6105a2020-11-17 15:11:05 -0700840 action(address_type, access);
841 }
842 }
843}
844
John Zulauf3d84f1b2020-03-09 13:33:25 -0600845// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
846// the DAG of the contexts (for example subpasses)
847template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700848HazardResult AccessContext::DetectHazard(AccessAddressType type, const Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600849 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600850 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600851
John Zulauf1a224292020-06-30 14:52:13 -0600852 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600853 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
854 // so we'll check these first
855 for (const auto &async_context : async_) {
856 hazard = async_context->DetectAsyncHazard(type, detector, range);
857 if (hazard.hazard) return hazard;
858 }
John Zulauf5f13a792020-03-10 07:31:21 -0600859 }
860
John Zulauf1a224292020-06-30 14:52:13 -0600861 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600862
John Zulauf69133422020-05-20 14:55:53 -0600863 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600864 const auto the_end = accesses.cend(); // End is not invalidated
865 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600866 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600867
John Zulauf3cafbf72021-03-26 16:55:19 -0600868 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600869 // Cover any leading gap, or gap between entries
870 if (detect_prev) {
871 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
872 // Cover any leading gap, or gap between entries
873 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600874 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600875 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600876 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600877 if (hazard.hazard) return hazard;
878 }
John Zulauf69133422020-05-20 14:55:53 -0600879 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
880 gap.begin = pos->first.end;
881 }
882
883 hazard = detector.Detect(pos);
884 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600885 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600886 }
887
888 if (detect_prev) {
889 // Detect in the trailing empty as needed
890 gap.end = range.end;
891 if (gap.non_empty()) {
892 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600893 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600894 }
895
896 return hazard;
897}
898
899// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
900template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700901HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
902 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600903 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600904 auto pos = accesses.lower_bound(range);
905 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600906
John Zulauf3d84f1b2020-03-09 13:33:25 -0600907 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600908 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700909 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600910 if (hazard.hazard) break;
911 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600912 }
John Zulauf16adfc92020-04-08 10:28:33 -0600913
John Zulauf3d84f1b2020-03-09 13:33:25 -0600914 return hazard;
915}
916
John Zulaufb02c1eb2020-10-06 16:33:36 -0600917struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700918 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600919 void operator()(ResourceAccessState *access) const {
920 assert(access);
921 access->ApplyBarriers(barriers, true);
922 }
923 const std::vector<SyncBarrier> &barriers;
924};
925
John Zulauf22aefed2021-03-11 18:14:35 -0700926struct ApplyTrackbackStackAction {
927 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
928 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
929 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600930 void operator()(ResourceAccessState *access) const {
931 assert(access);
932 assert(!access->HasPendingState());
933 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600934 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
935 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700936 if (previous_barrier) {
937 assert(bool(*previous_barrier));
938 (*previous_barrier)(access);
939 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600940 }
941 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700942 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600943};
944
945// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
946// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
947// *different* map from dest.
948// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
949// range [first, last)
950template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600951static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
952 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600953 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600954 auto at = entry;
955 for (auto pos = first; pos != last; ++pos) {
956 // Every member of the input iterator range must fit within the remaining portion of entry
957 assert(at->first.includes(pos->first));
958 assert(at != dest->end());
959 // Trim up at to the same size as the entry to resolve
960 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600961 auto access = pos->second; // intentional copy
962 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600963 at->second.Resolve(access);
964 ++at; // Go to the remaining unused section of entry
965 }
966}
967
John Zulaufa0a98292020-09-18 09:30:10 -0600968static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
969 SyncBarrier merged = {};
970 for (const auto &barrier : barriers) {
971 merged.Merge(barrier);
972 }
973 return merged;
974}
975
John Zulaufb02c1eb2020-10-06 16:33:36 -0600976template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700977void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600978 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
979 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600980 if (!range.non_empty()) return;
981
John Zulauf355e49b2020-04-24 15:11:15 -0600982 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
983 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600984 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -0600985 if (current->pos_B->valid) {
986 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600987 auto access = src_pos->second; // intentional copy
988 barrier_action(&access);
989
John Zulauf16adfc92020-04-08 10:28:33 -0600990 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600991 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
992 trimmed->second.Resolve(access);
993 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -0600994 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600995 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -0600996 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -0600997 }
John Zulauf16adfc92020-04-08 10:28:33 -0600998 } else {
999 // we have to descend to fill this gap
1000 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001001 ResourceAccessRange recurrence_range = current_range;
1002 // The current context is empty for the current range, so recur to fill the gap.
1003 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1004 // is not valid, to minimize that recurrence
1005 if (current->pos_B.at_end()) {
1006 // Do the remainder here....
1007 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001008 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001009 // Recur only over the range until B becomes valid (within the limits of range).
1010 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001011 }
John Zulauf22aefed2021-03-11 18:14:35 -07001012 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1013
John Zulauf355e49b2020-04-24 15:11:15 -06001014 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1015 // iterator of the outer while.
1016
1017 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1018 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1019 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001020 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 -06001021 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001022 current.seek(seek_to);
1023 } else if (!current->pos_A->valid && infill_state) {
1024 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1025 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1026 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001027 }
John Zulauf5f13a792020-03-10 07:31:21 -06001028 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001029 if (current->range.non_empty()) {
1030 ++current;
1031 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001032 }
John Zulauf1a224292020-06-30 14:52:13 -06001033
1034 // Infill if range goes passed both the current and resolve map prior contents
1035 if (recur_to_infill && (current->range.end < range.end)) {
1036 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001037 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001038 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001039}
1040
John Zulauf22aefed2021-03-11 18:14:35 -07001041template <typename BarrierAction>
1042void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1043 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1044 const BarrierAction &previous_barrier) const {
1045 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1046 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1047}
1048
John Zulauf43cc7462020-12-03 12:33:12 -07001049void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001050 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1051 const ResourceAccessStateFunction *previous_barrier) const {
1052 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001053 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001054 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1055 ResourceAccessState state_copy;
1056 if (previous_barrier) {
1057 assert(bool(*previous_barrier));
1058 state_copy = *infill_state;
1059 (*previous_barrier)(&state_copy);
1060 infill_state = &state_copy;
1061 }
1062 sparse_container::update_range_value(*descent_map, range, *infill_state,
1063 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001064 }
1065 } else {
1066 // Look for something to fill the gap further along.
1067 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001068 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001069 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001070 }
John Zulauf5f13a792020-03-10 07:31:21 -06001071 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001072}
1073
John Zulauf4a6105a2020-11-17 15:11:05 -07001074// Non-lazy import of all accesses, WaitEvents needs this.
1075void AccessContext::ResolvePreviousAccesses() {
1076 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001077 if (!prev_.size()) return; // If no previous contexts, nothing to do
1078
John Zulauf4a6105a2020-11-17 15:11:05 -07001079 for (const auto address_type : kAddressTypes) {
1080 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1081 }
1082}
1083
John Zulauf43cc7462020-12-03 12:33:12 -07001084AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1085 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001086}
1087
John Zulauf1507ee42020-05-18 11:33:09 -06001088static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001089 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1090 ? SYNC_ACCESS_INDEX_NONE
1091 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1092 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001093 return stage_access;
1094}
1095static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001096 const auto stage_access =
1097 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1098 ? SYNC_ACCESS_INDEX_NONE
1099 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1100 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001101 return stage_access;
1102}
1103
John Zulauf7635de32020-05-29 17:14:15 -06001104// Caller must manage returned pointer
1105static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001106 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001107 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001108 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1109 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001110 return proxy;
1111}
1112
John Zulaufb02c1eb2020-10-06 16:33:36 -06001113template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001114void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1115 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1116 const ResourceAccessState *infill_state) const {
1117 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1118 if (!attachment_gen) return;
1119
1120 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1121 const AccessAddressType address_type = view_gen.GetAddressType();
1122 for (; range_gen->non_empty(); ++range_gen) {
1123 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001124 }
John Zulauf62f10592020-04-03 12:20:02 -06001125}
1126
John Zulauf1d5f9c12022-05-13 14:51:08 -06001127template <typename ResolveOp>
1128void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1129 const ResourceAccessState *infill_state, bool recur_to_infill) {
1130 for (auto address_type : kAddressTypes) {
1131 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1132 recur_to_infill);
1133 }
1134}
1135
John Zulauf7635de32020-05-29 17:14:15 -06001136// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001137bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001138 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001139 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001140 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001141 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1142 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1143 // those affects have not been recorded yet.
1144 //
1145 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1146 // to apply and only copy then, if this proves a hot spot.
1147 std::unique_ptr<AccessContext> proxy_for_prev;
1148 TrackBack proxy_track_back;
1149
John Zulauf355e49b2020-04-24 15:11:15 -06001150 const auto &transitions = rp_state.subpass_transitions[subpass];
1151 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001152 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1153
1154 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001155 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001156 if (prev_needs_proxy) {
1157 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001158 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001159 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001160 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001161 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001162 }
1163 track_back = &proxy_track_back;
1164 }
1165 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001166 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001167 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001168 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001169 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001170 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1171 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1172 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1173 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1174 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1175 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001176 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001177 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1178 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1179 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1180 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1181 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001182 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001183 }
John Zulauf355e49b2020-04-24 15:11:15 -06001184 }
1185 }
1186 return skip;
1187}
1188
John Zulaufbb890452021-12-14 11:30:18 -07001189bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001190 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001191 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001192 bool skip = false;
1193 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001194
John Zulauf1507ee42020-05-18 11:33:09 -06001195 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1196 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001197 const auto &view_gen = attachment_views[i];
1198 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001199 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001200
1201 // Need check in the following way
1202 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1203 // vs. transition
1204 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1205 // for each aspect loaded.
1206
1207 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001208 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001209 const bool is_color = !(has_depth || has_stencil);
1210
1211 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001212 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001213
John Zulaufaff20662020-06-01 14:07:58 -06001214 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001215 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001216
John Zulaufb02c1eb2020-10-06 16:33:36 -06001217 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001218 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001219 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001220 aspect = "color";
1221 } else {
John Zulauf57261402021-08-13 11:32:06 -06001222 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001223 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1224 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001225 aspect = "depth";
1226 }
John Zulauf57261402021-08-13 11:32:06 -06001227 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001228 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1229 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001230 aspect = "stencil";
1231 checked_stencil = true;
1232 }
1233 }
1234
1235 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001236 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001237 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001238 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001239 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001240 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001241 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001242 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1243 " aspect %s during load with loadOp %s.",
1244 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1245 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001246 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001247 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001248 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001249 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001250 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001251 }
1252 }
1253 }
1254 }
1255 return skip;
1256}
1257
John Zulaufaff20662020-06-01 14:07:58 -06001258// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1259// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1260// store is part of the same Next/End operation.
1261// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001262bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001263 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001264 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001265 bool skip = false;
1266 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001267
1268 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1269 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001270 const AttachmentViewGen &view_gen = attachment_views[i];
1271 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001272 const auto &ci = attachment_ci[i];
1273
1274 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1275 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1276 // sake, we treat DONT_CARE as writing.
1277 const bool has_depth = FormatHasDepth(ci.format);
1278 const bool has_stencil = FormatHasStencil(ci.format);
1279 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001280 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001281 if (!has_stencil && !store_op_stores) continue;
1282
1283 HazardResult hazard;
1284 const char *aspect = nullptr;
1285 bool checked_stencil = false;
1286 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001287 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1288 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001289 aspect = "color";
1290 } else {
John Zulauf57261402021-08-13 11:32:06 -06001291 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001292 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001293 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1294 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001295 aspect = "depth";
1296 }
1297 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001298 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1299 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001300 aspect = "stencil";
1301 checked_stencil = true;
1302 }
1303 }
1304
1305 if (hazard.hazard) {
1306 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1307 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001308 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1309 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1310 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001311 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1312 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001313 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001314 }
1315 }
1316 }
1317 return skip;
1318}
1319
John Zulaufbb890452021-12-14 11:30:18 -07001320bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001321 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001322 CMD_TYPE cmd_type, uint32_t subpass) const {
1323 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001324 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001325 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001326}
1327
John Zulauf06f6f1e2022-04-19 15:28:11 -06001328AccessContext::TrackBack *AccessContext::AddTrackBack(const AccessContext *context, const SyncBarrier &barrier) {
1329 prev_.emplace_back(context, barrier);
1330 return &prev_.back();
1331}
1332
1333void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1334
John Zulauf3d84f1b2020-03-09 13:33:25 -06001335class HazardDetector {
1336 SyncStageAccessIndex usage_index_;
1337
1338 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001339 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001340 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001341 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001342 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001343 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001344};
1345
John Zulauf69133422020-05-20 14:55:53 -06001346class HazardDetectorWithOrdering {
1347 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001348 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001349
1350 public:
1351 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001352 return pos->second.DetectHazard(usage_index_, ordering_rule_);
John Zulauf69133422020-05-20 14:55:53 -06001353 }
John Zulauf14940722021-04-12 15:19:02 -06001354 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001355 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001356 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001357 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001358};
1359
John Zulauf16adfc92020-04-08 10:28:33 -06001360HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001361 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001362 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001363 const auto base_address = ResourceBaseAddress(buffer);
1364 HazardDetector detector(usage_index);
1365 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001366}
1367
John Zulauf69133422020-05-20 14:55:53 -06001368template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001369HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1370 DetectOptions options) const {
1371 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1372 if (!attachment_gen) return HazardResult();
1373
1374 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1375 const auto address_type = view_gen.GetAddressType();
1376 for (; range_gen->non_empty(); ++range_gen) {
1377 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1378 if (hazard.hazard) return hazard;
1379 }
1380
1381 return HazardResult();
1382}
1383
1384template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001385HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1386 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001387 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001388 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001389 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001390 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001391 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001392 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001393 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001394 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001395 if (hazard.hazard) return hazard;
1396 }
1397 return HazardResult();
1398}
John Zulauf110413c2021-03-20 05:38:38 -06001399template <typename Detector>
1400HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001401 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1402 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001403 if (!SimpleBinding(image)) return HazardResult();
1404 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001405 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1406 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001407 const auto address_type = ImageAddressType(image);
1408 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001409 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1410 if (hazard.hazard) return hazard;
1411 }
1412 return HazardResult();
1413}
John Zulauf69133422020-05-20 14:55:53 -06001414
John Zulauf540266b2020-04-06 18:54:53 -06001415HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1416 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001417 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001418 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1419 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001420 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001421 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001422}
1423
1424HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001425 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001426 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001427 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001428}
1429
John Zulaufd0ec59f2021-03-13 14:25:08 -07001430HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1431 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1432 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1433 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1434}
1435
John Zulauf69133422020-05-20 14:55:53 -06001436HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001437 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001438 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001439 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001440 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001441}
1442
John Zulauf3d84f1b2020-03-09 13:33:25 -06001443class BarrierHazardDetector {
1444 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001445 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001446 SyncStageAccessFlags src_access_scope)
1447 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1448
John Zulauf5f13a792020-03-10 07:31:21 -06001449 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1450 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001451 }
John Zulauf14940722021-04-12 15:19:02 -06001452 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001453 // 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 -07001454 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001455 }
1456
1457 private:
1458 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001459 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001460 SyncStageAccessFlags src_access_scope_;
1461};
1462
John Zulauf4a6105a2020-11-17 15:11:05 -07001463class EventBarrierHazardDetector {
1464 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001465 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001466 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
John Zulauf14940722021-04-12 15:19:02 -06001467 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001468 : usage_index_(usage_index),
1469 src_exec_scope_(src_exec_scope),
1470 src_access_scope_(src_access_scope),
1471 event_scope_(event_scope),
1472 scope_pos_(event_scope.cbegin()),
1473 scope_end_(event_scope.cend()),
1474 scope_tag_(scope_tag) {}
1475
1476 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1477 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1478 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1479 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1480 if (scope_pos_ == scope_end_) return HazardResult();
1481 if (!scope_pos_->first.intersects(pos->first)) {
1482 event_scope_.lower_bound(pos->first);
1483 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1484 }
1485
1486 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1487 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1488 }
John Zulauf14940722021-04-12 15:19:02 -06001489 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001490 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1491 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1492 }
1493
1494 private:
1495 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001496 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001497 SyncStageAccessFlags src_access_scope_;
1498 const SyncEventState::ScopeMap &event_scope_;
1499 SyncEventState::ScopeMap::const_iterator scope_pos_;
1500 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf14940722021-04-12 15:19:02 -06001501 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001502};
1503
Jeremy Gebben40a22942020-12-22 14:22:06 -07001504HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001505 const SyncStageAccessFlags &src_access_scope,
1506 const VkImageSubresourceRange &subresource_range,
1507 const SyncEventState &sync_event, DetectOptions options) const {
1508 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1509 // first access scope map to use, and there's no easy way to plumb it in below.
1510 const auto address_type = ImageAddressType(image);
1511 const auto &event_scope = sync_event.FirstScope(address_type);
1512
1513 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1514 event_scope, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001515 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001516}
1517
John Zulaufd0ec59f2021-03-13 14:25:08 -07001518HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1519 DetectOptions options) const {
1520 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1521 barrier.src_access_scope);
1522 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1523}
1524
Jeremy Gebben40a22942020-12-22 14:22:06 -07001525HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001526 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001527 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001528 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001529 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001530 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001531}
1532
Jeremy Gebben40a22942020-12-22 14:22:06 -07001533HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001534 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001535 const VkImageMemoryBarrier &barrier) const {
1536 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1537 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1538 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1539}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001540HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001541 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001542 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001543}
John Zulauf355e49b2020-04-24 15:11:15 -06001544
John Zulauf9cb530d2019-09-30 14:14:10 -06001545template <typename Flags, typename Map>
1546SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1547 SyncStageAccessFlags scope = 0;
1548 for (const auto &bit_scope : map) {
1549 if (flag_mask < bit_scope.first) break;
1550
1551 if (flag_mask & bit_scope.first) {
1552 scope |= bit_scope.second;
1553 }
1554 }
1555 return scope;
1556}
1557
Jeremy Gebben40a22942020-12-22 14:22:06 -07001558SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001559 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1560}
1561
Jeremy Gebben40a22942020-12-22 14:22:06 -07001562SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1563 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001564}
1565
Jeremy Gebben40a22942020-12-22 14:22:06 -07001566// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1567SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001568 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1569 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1570 // 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 -06001571 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1572}
1573
1574template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001575void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001576 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1577 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001578 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001579 auto pos = accesses->lower_bound(range);
1580 if (pos == accesses->end() || !pos->first.intersects(range)) {
1581 // The range is empty, fill it with a default value.
1582 pos = action.Infill(accesses, pos, range);
1583 } else if (range.begin < pos->first.begin) {
1584 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001585 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001586 } else if (pos->first.begin < range.begin) {
1587 // Trim the beginning if needed
1588 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1589 ++pos;
1590 }
1591
1592 const auto the_end = accesses->end();
1593 while ((pos != the_end) && pos->first.intersects(range)) {
1594 if (pos->first.end > range.end) {
1595 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1596 }
1597
1598 pos = action(accesses, pos);
1599 if (pos == the_end) break;
1600
1601 auto next = pos;
1602 ++next;
1603 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1604 // Need to infill if next is disjoint
1605 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001606 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001607 next = action.Infill(accesses, next, new_range);
1608 }
1609 pos = next;
1610 }
1611}
John Zulaufd5115702021-01-18 12:34:33 -07001612
1613// Give a comparable interface for range generators and ranges
1614template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001615void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001616 assert(range);
1617 UpdateMemoryAccessState(accesses, *range, action);
1618}
1619
John Zulauf4a6105a2020-11-17 15:11:05 -07001620template <typename Action, typename RangeGen>
1621void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1622 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001623 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 -07001624 for (; range_gen->non_empty(); ++range_gen) {
1625 UpdateMemoryAccessState(accesses, *range_gen, action);
1626 }
1627}
John Zulauf9cb530d2019-09-30 14:14:10 -06001628
John Zulaufd0ec59f2021-03-13 14:25:08 -07001629template <typename Action, typename RangeGen>
1630void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1631 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1632 for (; range_gen->non_empty(); ++range_gen) {
1633 UpdateMemoryAccessState(accesses, *range_gen, action);
1634 }
1635}
John Zulauf9cb530d2019-09-30 14:14:10 -06001636struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001637 using Iterator = ResourceAccessRangeMap::iterator;
1638 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001639 // this is only called on gaps, and never returns a gap.
1640 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001641 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001642 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001643 }
John Zulauf5f13a792020-03-10 07:31:21 -06001644
John Zulauf5c5e88d2019-12-26 11:22:02 -07001645 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001646 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001647 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001648 return pos;
1649 }
1650
John Zulauf43cc7462020-12-03 12:33:12 -07001651 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001652 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001653 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001654 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001655 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001656 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001657 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001658 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001659};
1660
John Zulauf4a6105a2020-11-17 15:11:05 -07001661// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001662struct PipelineBarrierOp {
1663 SyncBarrier barrier;
1664 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001665 ResourceAccessState::QueueScopeOps scope;
1666 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1667 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001668 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001669 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001670};
John Zulauf00119522022-05-23 19:07:42 -06001671
John Zulauf4a6105a2020-11-17 15:11:05 -07001672// The barrier operation for wait events
1673struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001674 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001675 SyncBarrier barrier;
1676 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001677 // WIP Integrate Queue scoping into event scope operations
1678 WaitEventBarrierOp(const QueueId scope_queue, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
1679 bool layout_transition_)
John Zulaufb7578302022-05-19 13:50:18 -06001680 : scope_ops(scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1681 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001682};
John Zulauf1e331ec2020-12-04 18:29:38 -07001683
John Zulauf4a6105a2020-11-17 15:11:05 -07001684// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1685// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1686// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001687template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001688class ApplyBarrierOpsFunctor {
1689 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001690 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001691 // Only called with a gap, and pos at the lower_bound(range)
1692 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1693 if (!infill_default_) {
1694 return pos;
1695 }
1696 ResourceAccessState default_state;
1697 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1698 return inserted;
1699 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001700
John Zulauf5c628d02021-05-04 15:46:36 -06001701 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001702 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001703 for (const auto &op : barrier_ops_) {
1704 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001705 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001706
John Zulauf89311b42020-09-29 16:28:47 -06001707 if (resolve_) {
1708 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1709 // another walk
1710 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001711 }
1712 return pos;
1713 }
1714
John Zulauf89311b42020-09-29 16:28:47 -06001715 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001716 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1717 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001718 barrier_ops_.reserve(size_hint);
1719 }
John Zulauf5c628d02021-05-04 15:46:36 -06001720 void EmplaceBack(const BarrierOp &op) {
1721 barrier_ops_.emplace_back(op);
1722 infill_default_ |= op.layout_transition;
1723 }
John Zulauf89311b42020-09-29 16:28:47 -06001724
1725 private:
1726 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001727 bool infill_default_;
1728 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001729 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001730};
1731
John Zulauf4a6105a2020-11-17 15:11:05 -07001732// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1733// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1734template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001735class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1736 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1737
John Zulauf4a6105a2020-11-17 15:11:05 -07001738 public:
John Zulaufee984022022-04-13 16:39:50 -06001739 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001740};
1741
John Zulauf1e331ec2020-12-04 18:29:38 -07001742// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001743class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1744 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1745
John Zulauf1e331ec2020-12-04 18:29:38 -07001746 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001747 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001748};
1749
John Zulauf8e3c3e92021-01-06 11:19:36 -07001750void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001751 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001752 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001753 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001754}
1755
John Zulauf8e3c3e92021-01-06 11:19:36 -07001756void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001757 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001758 if (!SimpleBinding(buffer)) return;
1759 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001760 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001761}
John Zulauf355e49b2020-04-24 15:11:15 -06001762
John Zulauf8e3c3e92021-01-06 11:19:36 -07001763void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001764 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1765 if (!SimpleBinding(image)) return;
1766 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001767 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001768 const auto address_type = ImageAddressType(image);
1769 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1770 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1771}
1772void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001773 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001774 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001775 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001776 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001777 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001778 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001779 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001780 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001781 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001782}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001783
1784void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001785 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001786 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1787 if (!gen) return;
1788 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1789 const auto address_type = view_gen.GetAddressType();
1790 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1791 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001792}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001793
John Zulauf8e3c3e92021-01-06 11:19:36 -07001794void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001795 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001796 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001797 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1798 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001799 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001800}
1801
John Zulaufd0ec59f2021-03-13 14:25:08 -07001802template <typename Action, typename RangeGen>
1803void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1804 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1805 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001806}
1807
1808template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001809void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1810 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1811 if (!gen) return;
1812 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001813}
1814
John Zulaufd0ec59f2021-03-13 14:25:08 -07001815void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1816 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001817 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001818 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001819 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001820}
1821
John Zulaufd0ec59f2021-03-13 14:25:08 -07001822void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001823 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001824 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001825
1826 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1827 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001828 const auto &view_gen = attachment_views[i];
1829 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001830
1831 const auto &ci = attachment_ci[i];
1832 const bool has_depth = FormatHasDepth(ci.format);
1833 const bool has_stencil = FormatHasStencil(ci.format);
1834 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001835 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001836
1837 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001838 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1839 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001840 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001841 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001842 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1843 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001844 }
John Zulauf57261402021-08-13 11:32:06 -06001845 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001846 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001847 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1848 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001849 }
1850 }
1851 }
1852 }
1853}
1854
John Zulauf540266b2020-04-06 18:54:53 -06001855template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001856void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001857 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001858 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001859 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001860 }
1861}
1862
1863void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001864 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1865 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001866 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001867 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001868 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001869 }
1870 }
1871}
1872
John Zulauf4fa68462021-04-26 21:04:22 -06001873// Caller must ensure that lifespan of this is less than from
1874void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1875
John Zulauf355e49b2020-04-24 15:11:15 -06001876// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001877HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1878 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001879
John Zulauf355e49b2020-04-24 15:11:15 -06001880 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001881 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001882
1883 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001884 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1885 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001886 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001887 if (!hazard.hazard) {
1888 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001889 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001890 }
John Zulaufa0a98292020-09-18 09:30:10 -06001891
John Zulauf355e49b2020-04-24 15:11:15 -06001892 return hazard;
1893}
1894
John Zulaufb02c1eb2020-10-06 16:33:36 -06001895void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001896 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001897 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001898 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001899 for (const auto &transition : transitions) {
1900 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001901 const auto &view_gen = attachment_views[transition.attachment];
1902 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001903
1904 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1905 assert(trackback);
1906
1907 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001908 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001909 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001910 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001911 auto &target_map = GetAccessStateMap(address_type);
1912 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001913 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1914 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001915 }
1916
John Zulauf86356ca2020-10-19 11:46:41 -06001917 // If there were no transitions skip this global map walk
1918 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001919 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001920 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001921 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001922}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001923
sjfricke0bea06e2022-06-05 09:22:26 +09001924bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06001925 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001926 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001927 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001928 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001929 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001930 return skip;
1931 }
sjfricke0bea06e2022-06-05 09:22:26 +09001932 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06001933
1934 using DescriptorClass = cvdescriptorset::DescriptorClass;
1935 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1936 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06001937 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1938
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001939 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001940 const auto raster_state = pipe->RasterizationState();
1941 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001942 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001943 }
locke-lunarg61870c22020-06-09 14:51:50 -06001944 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001945 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06001946 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001947 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06001948 const auto descriptor_type = binding_it.GetType();
1949 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1950 auto array_idx = 0;
1951
1952 if (binding_it.IsVariableDescriptorCount()) {
1953 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1954 }
1955 SyncStageAccessIndex sync_index =
1956 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1957
1958 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1959 uint32_t index = i - index_range.start;
1960 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1961 switch (descriptor->GetClass()) {
1962 case DescriptorClass::ImageSampler:
1963 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07001964 if (descriptor->Invalid()) {
1965 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06001966 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07001967
1968 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
1969 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1970 const auto *img_view_state = image_descriptor->GetImageViewState();
1971 VkImageLayout image_layout = image_descriptor->GetImageLayout();
1972
John Zulauf361fb532020-07-22 10:45:39 -06001973 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06001974 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
1975 // Descriptors, so we do not have to worry about depth slicing here.
1976 // See: VUID 00343
1977 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06001978 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06001979 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06001980
1981 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1982 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1983 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06001984 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001985 hazard =
1986 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
1987 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06001988 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001989 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
1990 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06001991 }
John Zulauf110413c2021-03-20 05:38:38 -06001992
John Zulauf33fc1d52020-07-17 11:01:10 -06001993 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001994 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001995 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001996 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1997 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09001998 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001999 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2000 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2001 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002002 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2003 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002004 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002005 }
2006 break;
2007 }
2008 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002009 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2010 if (texel_descriptor->Invalid()) {
2011 continue;
2012 }
2013 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2014 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002015 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002016 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002017 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002018 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002019 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002020 "%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 +09002021 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002022 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2023 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2024 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002025 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002026 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002027 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002028 }
2029 break;
2030 }
2031 case DescriptorClass::GeneralBuffer: {
2032 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002033 if (buffer_descriptor->Invalid()) {
2034 continue;
2035 }
2036 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002037 const ResourceAccessRange range =
2038 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002039 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002040 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002041 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002042 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002043 "%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 +09002044 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002045 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2046 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2047 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002048 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002049 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002050 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002051 }
2052 break;
2053 }
2054 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2055 default:
2056 break;
2057 }
2058 }
2059 }
2060 }
2061 return skip;
2062}
2063
2064void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002065 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002066 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002067 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002068 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002069 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002070 return;
2071 }
2072
2073 using DescriptorClass = cvdescriptorset::DescriptorClass;
2074 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2075 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002076 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2077
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002078 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002079 const auto raster_state = pipe->RasterizationState();
2080 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002081 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002082 }
locke-lunarg61870c22020-06-09 14:51:50 -06002083 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002084 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002085 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002086 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06002087 const auto descriptor_type = binding_it.GetType();
2088 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
2089 auto array_idx = 0;
2090
2091 if (binding_it.IsVariableDescriptorCount()) {
2092 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2093 }
2094 SyncStageAccessIndex sync_index =
2095 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2096
2097 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2098 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2099 switch (descriptor->GetClass()) {
2100 case DescriptorClass::ImageSampler:
2101 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002102 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2103 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2104 if (image_descriptor->Invalid()) {
2105 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002106 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002107 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002108 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2109 // Descriptors, so we do not have to worry about depth slicing here.
2110 // See: VUID 00343
2111 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002112 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002113 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002114 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2115 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2116 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2117 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002118 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002119 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2120 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002121 }
locke-lunarg61870c22020-06-09 14:51:50 -06002122 break;
2123 }
2124 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002125 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2126 if (texel_descriptor->Invalid()) {
2127 continue;
2128 }
2129 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2130 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002131 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002132 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002133 break;
2134 }
2135 case DescriptorClass::GeneralBuffer: {
2136 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002137 if (buffer_descriptor->Invalid()) {
2138 continue;
2139 }
2140 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002141 const ResourceAccessRange range =
2142 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002143 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002144 break;
2145 }
2146 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2147 default:
2148 break;
2149 }
2150 }
2151 }
2152 }
2153}
2154
sjfricke0bea06e2022-06-05 09:22:26 +09002155bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002156 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002157 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002158 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002159 return skip;
2160 }
2161
2162 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2163 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002164 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002165
2166 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002167 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002168 if (binding_description.binding < binding_buffers_size) {
2169 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002170 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002171
locke-lunarg1ae57d62020-11-18 10:49:19 -07002172 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002173 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2174 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002175 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002176 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002177 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002178 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002179 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002180 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2181 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002182 }
2183 }
2184 }
2185 return skip;
2186}
2187
John Zulauf14940722021-04-12 15:19:02 -06002188void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002189 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002190 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002191 return;
2192 }
2193 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2194 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002195 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002196
2197 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002198 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002199 if (binding_description.binding < binding_buffers_size) {
2200 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002201 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002202
locke-lunarg1ae57d62020-11-18 10:49:19 -07002203 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002204 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2205 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002206 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2207 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002208 }
2209 }
2210}
2211
sjfricke0bea06e2022-06-05 09:22:26 +09002212bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002213 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002214 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002215 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002216 }
locke-lunarg61870c22020-06-09 14:51:50 -06002217
locke-lunarg1ae57d62020-11-18 10:49:19 -07002218 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002219 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002220 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2221 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002222 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002223 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002224 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002225 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 +09002226 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2227 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002228 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002229 }
2230
2231 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2232 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002233 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002234 return skip;
2235}
2236
John Zulauf14940722021-04-12 15:19:02 -06002237void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002238 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 -06002239
locke-lunarg1ae57d62020-11-18 10:49:19 -07002240 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002241 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002242 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2243 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002244 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002245
2246 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2247 // We will detect more accurate range in the future.
2248 RecordDrawVertex(UINT32_MAX, 0, tag);
2249}
2250
sjfricke0bea06e2022-06-05 09:22:26 +09002251bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002252 bool skip = false;
2253 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002254 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002255 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002256}
2257
John Zulauf14940722021-04-12 15:19:02 -06002258void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002259 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002260 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002261 }
locke-lunarg61870c22020-06-09 14:51:50 -06002262}
2263
John Zulauf00119522022-05-23 19:07:42 -06002264QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2265
sjfricke0bea06e2022-06-05 09:22:26 +09002266ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002267 const VkRect2D &render_area,
2268 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002269 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002270 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2271 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002272 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002273 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002274 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002275 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002276 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002277}
2278
sjfricke0bea06e2022-06-05 09:22:26 +09002279ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002280 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002281 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002282
sjfricke0bea06e2022-06-05 09:22:26 +09002283 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2284 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2285 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002286
2287 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002288 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002289 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002290}
2291
sjfricke0bea06e2022-06-05 09:22:26 +09002292ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002293 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002294 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002295
sjfricke0bea06e2022-06-05 09:22:26 +09002296 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2297 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002298
2299 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002300 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002301 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002302 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002303}
2304
John Zulauf4a6105a2020-11-17 15:11:05 -07002305void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2306 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002307 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002308 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002309 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002310 }
2311}
2312
John Zulaufae842002021-04-15 18:20:55 -06002313// The is the recorded cb context
John Zulaufbb890452021-12-14 11:30:18 -07002314bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext *proxy_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002315 uint32_t index) const {
2316 assert(proxy_context);
John Zulauf00119522022-05-23 19:07:42 -06002317 SyncEventsContext *const events_context = proxy_context->GetCurrentEventsContext();
2318 AccessContext *const access_context = proxy_context->GetCurrentAccessContext();
2319 const QueueId queue_id = proxy_context->GetQueueId();
John Zulauf4fa68462021-04-26 21:04:22 -06002320 const ResourceUsageTag base_tag = proxy_context->GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002321 bool skip = false;
2322 ResourceUsageRange tag_range = {0, 0};
2323 const AccessContext *recorded_context = GetCurrentAccessContext();
2324 assert(recorded_context);
2325 HazardResult hazard;
John Zulaufbb890452021-12-14 11:30:18 -07002326 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002327 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002328 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002329 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002330 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002331 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002332 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2333 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002334 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002335 };
John Zulaufbb890452021-12-14 11:30:18 -07002336 const ReplayTrackbackBarriersAction *replay_context = nullptr;
John Zulaufae842002021-04-15 18:20:55 -06002337 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002338 // we update the range to any include layout transition first use writes,
2339 // as they are stored along with the source scope (as effective barrier) when recorded
2340 tag_range.end = sync_op.tag + 1;
John Zulauf610e28c2021-08-03 17:46:23 -06002341 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, proxy_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002342
John Zulaufbb890452021-12-14 11:30:18 -07002343 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002344 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002345 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002346 }
2347 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002348 // Record the barrier into the proxy context.
John Zulauf00119522022-05-23 19:07:42 -06002349 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulaufbb890452021-12-14 11:30:18 -07002350 replay_context = sync_op.sync_op->GetReplayTrackback();
John Zulauf4fa68462021-04-26 21:04:22 -06002351 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002352 }
2353
John Zulaufbb890452021-12-14 11:30:18 -07002354 // Renderpasses may not cross command buffer boundaries
2355 assert(replay_context == nullptr);
2356
John Zulaufae842002021-04-15 18:20:55 -06002357 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002358 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulaufbb890452021-12-14 11:30:18 -07002359 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002360 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002361 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002362 }
2363
2364 return skip;
2365}
2366
sjfricke0bea06e2022-06-05 09:22:26 +09002367void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf00119522022-05-23 19:07:42 -06002368 SyncEventsContext *const events_context = GetCurrentEventsContext();
2369 AccessContext *const access_context = GetCurrentAccessContext();
2370 const QueueId queue_id = GetQueueId();
2371
John Zulauf4fa68462021-04-26 21:04:22 -06002372 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2373 assert(recorded_context);
2374
2375 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2376 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002377 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
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
John Zulauf00119522022-05-23 19:07:42 -06002380 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002381 }
2382
2383 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2384 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002385 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002386}
2387
John Zulauf1d5f9c12022-05-13 14:51:08 -06002388void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002389 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002390 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002391}
2392
John Zulauf3c788ef2022-02-22 12:12:30 -07002393ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002394 // The execution references ensure lifespan for the referenced child CB's...
2395 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002396 InsertRecordedAccessLogEntries(recorded_context);
2397 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002398 return tag_range;
2399}
2400
John Zulauf3c788ef2022-02-22 12:12:30 -07002401void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2402 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2403 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2404}
2405
John Zulauf41a9c7c2021-12-07 15:59:53 -07002406ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2407 ResourceUsageTag next = access_log_.size();
2408 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2409 return next;
2410}
2411
2412ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2413 command_number_++;
2414 subcommand_number_ = 0;
2415 ResourceUsageTag next = access_log_.size();
2416 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2417 return next;
2418}
2419
2420ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2421 if (index == 0) {
2422 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2423 }
2424 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2425}
2426
John Zulaufbb890452021-12-14 11:30:18 -07002427void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2428 auto tag = sync_op->Record(this);
2429 // As renderpass operations can have side effects on the command buffer access context,
2430 // update the sync operation to record these if any.
2431 if (current_renderpass_context_) {
2432 const auto &rpc = *current_renderpass_context_;
2433 sync_op->SetReplayContext(rpc.GetCurrentSubpass(), rpc.GetReplayContext());
2434 }
2435 sync_ops_.emplace_back(tag, std::move(sync_op));
2436}
2437
John Zulaufae842002021-04-15 18:20:55 -06002438class HazardDetectFirstUse {
2439 public:
John Zulaufbb890452021-12-14 11:30:18 -07002440 HazardDetectFirstUse(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
2441 const ReplayTrackbackBarriersAction *replay_barrier)
2442 : recorded_use_(recorded_use), tag_range_(tag_range), replay_barrier_(replay_barrier) {}
John Zulaufae842002021-04-15 18:20:55 -06002443 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufbb890452021-12-14 11:30:18 -07002444 if (replay_barrier_) {
2445 // Intentional copy to apply the replay barrier
2446 auto access = pos->second;
2447 (*replay_barrier_)(&access);
2448 return access.DetectHazard(recorded_use_, tag_range_);
2449 }
John Zulaufae842002021-04-15 18:20:55 -06002450 return pos->second.DetectHazard(recorded_use_, tag_range_);
2451 }
2452 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2453 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2454 }
2455
2456 private:
2457 const ResourceAccessState &recorded_use_;
2458 const ResourceUsageRange &tag_range_;
John Zulaufbb890452021-12-14 11:30:18 -07002459 const ReplayTrackbackBarriersAction *replay_barrier_;
John Zulaufae842002021-04-15 18:20:55 -06002460};
2461
2462// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2463// hazards will be detected
John Zulaufbb890452021-12-14 11:30:18 -07002464HazardResult AccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range, const AccessContext &access_context,
2465 const ReplayTrackbackBarriersAction *replay_barrier) const {
John Zulaufae842002021-04-15 18:20:55 -06002466 HazardResult hazard;
2467 for (const auto address_type : kAddressTypes) {
2468 const auto &recorded_access_map = GetAccessStateMap(address_type);
2469 for (const auto &recorded_access : recorded_access_map) {
2470 // Cull any entries not in the current tag range
2471 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulaufbb890452021-12-14 11:30:18 -07002472 HazardDetectFirstUse detector(recorded_access.second, tag_range, replay_barrier);
John Zulaufae842002021-04-15 18:20:55 -06002473 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2474 if (hazard.hazard) break;
2475 }
2476 }
2477
2478 return hazard;
2479}
2480
John Zulaufbb890452021-12-14 11:30:18 -07002481bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002482 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002483 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002484 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002485 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002486 if (!pipe) {
2487 return skip;
2488 }
2489
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002490 const auto raster_state = pipe->RasterizationState();
2491 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002492 return skip;
2493 }
sjfricke0bea06e2022-06-05 09:22:26 +09002494 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002495 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002496 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002497
John Zulauf1a224292020-06-30 14:52:13 -06002498 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002499 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002500 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2501 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002502 if (location >= subpass.colorAttachmentCount ||
2503 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002504 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002505 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002506 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2507 if (!view_gen.IsValid()) continue;
2508 HazardResult hazard =
2509 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2510 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002511 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002512 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002513 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002514 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002515 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002516 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002517 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2518 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002519 }
2520 }
2521 }
locke-lunarg37047832020-06-12 13:44:45 -06002522
2523 // PHASE1 TODO: Add layout based read/vs. write selection.
2524 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002525 const auto ds_state = pipe->DepthStencilState();
2526 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002527
2528 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2529 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2530 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002531 bool depth_write = false, stencil_write = false;
2532
2533 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002534 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002535 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2536 depth_write = true;
2537 }
2538 // PHASE1 TODO: It needs to check if stencil is writable.
2539 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2540 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2541 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002542 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002543 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2544 stencil_write = true;
2545 }
2546
2547 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2548 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002549 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2550 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2551 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002552 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002553 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002554 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002555 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002556 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002557 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002558 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002559 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002560 }
2561 }
2562 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002563 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2564 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2565 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002566 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002567 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002568 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002569 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002570 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002571 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002572 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002573 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002574 }
locke-lunarg61870c22020-06-09 14:51:50 -06002575 }
2576 }
2577 return skip;
2578}
2579
sjfricke0bea06e2022-06-05 09:22:26 +09002580void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2581 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002582 if (!pipe) {
2583 return;
2584 }
2585
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002586 const auto *raster_state = pipe->RasterizationState();
2587 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002588 return;
2589 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002590 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002591 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002592
John Zulauf1a224292020-06-30 14:52:13 -06002593 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002594 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002595 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2596 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002597 if (location >= subpass.colorAttachmentCount ||
2598 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002599 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002600 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002601 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2602 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2603 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2604 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002605 }
2606 }
locke-lunarg37047832020-06-12 13:44:45 -06002607
2608 // PHASE1 TODO: Add layout based read/vs. write selection.
2609 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002610 const auto *ds_state = pipe->DepthStencilState();
2611 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002612 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2613 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2614 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002615 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002616 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2617 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002618
2619 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002620 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2621 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002622 depth_write = true;
2623 }
2624 // PHASE1 TODO: It needs to check if stencil is writable.
2625 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2626 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2627 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002628 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002629 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2630 stencil_write = true;
2631 }
2632
John Zulaufd0ec59f2021-03-13 14:25:08 -07002633 if (depth_write || stencil_write) {
2634 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2635 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2636 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2637 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002638 }
locke-lunarg61870c22020-06-09 14:51:50 -06002639 }
2640}
2641
sjfricke0bea06e2022-06-05 09:22:26 +09002642bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002643 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002644 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002645 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002646 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002647 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002648 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002649
John Zulauf355e49b2020-04-24 15:11:15 -06002650 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002651 if (next_subpass >= subpass_contexts_.size()) {
2652 return skip;
2653 }
John Zulauf1507ee42020-05-18 11:33:09 -06002654 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002655 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002656 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002657 if (!skip) {
2658 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2659 // on a copy of the (empty) next context.
2660 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2661 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002662 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002663 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002664 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002665 }
John Zulauf7635de32020-05-29 17:14:15 -06002666 return skip;
2667}
sjfricke0bea06e2022-06-05 09:22:26 +09002668bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002669 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002670 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002671 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002672 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002673 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2674 cmd_type);
2675 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002676 return skip;
2677}
2678
John Zulauf64ffe552021-02-06 10:25:07 -07002679AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002680 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002681}
2682
John Zulaufbb890452021-12-14 11:30:18 -07002683bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002684 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002685 bool skip = false;
2686
John Zulauf7635de32020-05-29 17:14:15 -06002687 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2688 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2689 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2690 // to apply and only copy then, if this proves a hot spot.
2691 std::unique_ptr<AccessContext> proxy_for_current;
2692
John Zulauf355e49b2020-04-24 15:11:15 -06002693 // Validate the "finalLayout" transitions to external
2694 // Get them from where there we're hidding in the extra entry.
2695 const auto &final_transitions = rp_state_->subpass_transitions.back();
2696 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002697 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002698 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002699 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2700 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002701
2702 if (transition.prev_pass == current_subpass_) {
2703 if (!proxy_for_current) {
2704 // 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 -07002705 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002706 }
2707 context = proxy_for_current.get();
2708 }
2709
John Zulaufa0a98292020-09-18 09:30:10 -06002710 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2711 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002712 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002713 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002714 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002715 if (hazard.tag == kInvalidTag) {
2716 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002717 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002718 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2719 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2720 " final image layout transition (old_layout: %s, new_layout: %s).",
2721 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2722 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2723 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002724 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002725 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2726 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2727 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2728 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2729 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002730 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002731 }
John Zulauf355e49b2020-04-24 15:11:15 -06002732 }
2733 }
2734 return skip;
2735}
2736
John Zulauf14940722021-04-12 15:19:02 -06002737void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002738 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002739 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002740}
2741
John Zulauf14940722021-04-12 15:19:02 -06002742void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002743 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2744 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002745
2746 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2747 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002748 const AttachmentViewGen &view_gen = attachment_views_[i];
2749 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002750
2751 const auto &ci = attachment_ci[i];
2752 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002753 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002754 const bool is_color = !(has_depth || has_stencil);
2755
2756 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002757 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2758 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2759 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2760 SyncOrdering::kColorAttachment, tag);
2761 }
John Zulauf1507ee42020-05-18 11:33:09 -06002762 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002763 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002764 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2765 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2766 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2767 SyncOrdering::kDepthStencilAttachment, tag);
2768 }
John Zulauf1507ee42020-05-18 11:33:09 -06002769 }
2770 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002771 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2772 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2773 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2774 SyncOrdering::kDepthStencilAttachment, tag);
2775 }
John Zulauf1507ee42020-05-18 11:33:09 -06002776 }
2777 }
2778 }
2779 }
2780}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002781AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2782 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2783 AttachmentViewGenVector view_gens;
2784 VkExtent3D extent = CastTo3D(render_area.extent);
2785 VkOffset3D offset = CastTo3D(render_area.offset);
2786 view_gens.reserve(attachment_views.size());
2787 for (const auto *view : attachment_views) {
2788 view_gens.emplace_back(view, offset, extent);
2789 }
2790 return view_gens;
2791}
John Zulauf64ffe552021-02-06 10:25:07 -07002792RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2793 VkQueueFlags queue_flags,
2794 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2795 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002796 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulauf355e49b2020-04-24 15:11:15 -06002797 // Add this for all subpasses here so that they exsist during next subpass validation
John Zulauf64ffe552021-02-06 10:25:07 -07002798 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
John Zulaufbb890452021-12-14 11:30:18 -07002799 replay_context_ = std::make_shared<ReplayRenderpassContext>();
2800 auto &replay_subpass_contexts = replay_context_->subpass_contexts;
2801 replay_subpass_contexts.reserve(rp_state_->createInfo.subpassCount);
John Zulauf355e49b2020-04-24 15:11:15 -06002802 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002803 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulaufbb890452021-12-14 11:30:18 -07002804 replay_subpass_contexts.emplace_back(queue_flags, rp_state_->subpass_dependencies[pass], replay_subpass_contexts);
John Zulauf355e49b2020-04-24 15:11:15 -06002805 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002806 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002807}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002808void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002809 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002810 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2811 RecordLayoutTransitions(barrier_tag);
2812 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002813}
John Zulauf1507ee42020-05-18 11:33:09 -06002814
John Zulauf41a9c7c2021-12-07 15:59:53 -07002815void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2816 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002817 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002818 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2819 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002820
ziga-lunarg31a3e772022-03-22 11:48:46 +01002821 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2822 return;
2823 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002824 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2825 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002826 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002827 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2828 RecordLayoutTransitions(barrier_tag);
2829 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002830}
2831
John Zulauf41a9c7c2021-12-07 15:59:53 -07002832void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2833 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002834 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002835 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2836 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002837
John Zulauf355e49b2020-04-24 15:11:15 -06002838 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002839 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002840
2841 // Add the "finalLayout" transitions to external
2842 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002843 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2844 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2845 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002846 const auto &final_transitions = rp_state_->subpass_transitions.back();
2847 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002848 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002849 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002850 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002851 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002852 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002853 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002854 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002855 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002856 }
2857}
2858
John Zulauf06f6f1e2022-04-19 15:28:11 -06002859SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2860 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002861 SyncExecScope result;
2862 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002863 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002864 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002865 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2866 return result;
2867}
2868
Jeremy Gebben40a22942020-12-22 14:22:06 -07002869SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002870 SyncExecScope result;
2871 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002872 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2873 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002874 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2875 return result;
2876}
2877
2878SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
John Zulaufc523bf62021-02-16 08:20:34 -07002879 src_exec_scope = src;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002880 src_access_scope = 0;
John Zulaufc523bf62021-02-16 08:20:34 -07002881 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002882 dst_access_scope = 0;
2883}
2884
2885template <typename Barrier>
2886SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst) {
John Zulaufc523bf62021-02-16 08:20:34 -07002887 src_exec_scope = src;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002888 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002889 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002890 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2891}
2892
2893SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002894 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2895 if (barrier) {
2896 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002897 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002898 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002899
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002900 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002901 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002902 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2903
2904 } else {
2905 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002906 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002907 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2908
2909 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002910 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002911 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2912 }
2913}
2914
2915template <typename Barrier>
2916SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2917 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2918 src_exec_scope = src.exec_scope;
2919 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2920
2921 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002922 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002923 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002924}
2925
John Zulaufb02c1eb2020-10-06 16:33:36 -06002926// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2927void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002928 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002929 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002930 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002931 }
2932}
2933
John Zulauf89311b42020-09-29 16:28:47 -06002934// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2935// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2936// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002937void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002938 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002939 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002940 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002941 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002942 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002943 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002944 }
John Zulaufbb890452021-12-14 11:30:18 -07002945 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002946}
John Zulauf9cb530d2019-09-30 14:14:10 -06002947HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2948 HazardResult hazard;
2949 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002950 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002951 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002952 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002953 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002954 }
2955 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002956 // Write operation:
2957 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2958 // If reads exists -- test only against them because either:
2959 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2960 // * 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
2961 // the current write happens after the reads, so just test the write against the reades
2962 // Otherwise test against last_write
2963 //
2964 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002965 if (last_reads.size()) {
2966 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002967 if (IsReadHazard(usage_stage, read_access)) {
2968 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2969 break;
2970 }
2971 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002972 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002973 // Write-After-Write check -- if we have a previous write to test against
2974 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002975 }
2976 }
2977 return hazard;
2978}
2979
John Zulauf4fa68462021-04-26 21:04:22 -06002980HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002981 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf4fa68462021-04-26 21:04:22 -06002982 return DetectHazard(usage_index, ordering);
2983}
2984
2985HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering) const {
John Zulauf69133422020-05-20 14:55:53 -06002986 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2987 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002988 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002989 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002990 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2991 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002992 if (IsRead(usage_bit)) {
2993 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2994 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2995 if (is_raw_hazard) {
2996 // NOTE: we know last_write is non-zero
2997 // See if the ordering rules save us from the simple RAW check above
2998 // First check to see if the current usage is covered by the ordering rules
2999 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3000 const bool usage_is_ordered =
3001 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3002 if (usage_is_ordered) {
3003 // Now see of the most recent write (or a subsequent read) are ordered
3004 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
3005 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003006 }
3007 }
John Zulauf4285ee92020-09-23 10:20:52 -06003008 if (is_raw_hazard) {
3009 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3010 }
John Zulauf5c628d02021-05-04 15:46:36 -06003011 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3012 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
3013 return DetectBarrierHazard(usage_index, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003014 } else {
3015 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003016 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003017 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003018 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003019 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003020 if (usage_write_is_ordered) {
3021 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
3022 ordered_stages = GetOrderedStages(ordering);
3023 }
3024 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3025 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003026 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003027 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3028 if (IsReadHazard(usage_stage, read_access)) {
3029 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3030 break;
3031 }
John Zulaufd14743a2020-07-03 09:42:39 -06003032 }
3033 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003034 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3035 bool ilt_ilt_hazard = false;
3036 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3037 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3038 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3039 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3040 }
3041 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003042 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003043 }
John Zulauf69133422020-05-20 14:55:53 -06003044 }
3045 }
3046 return hazard;
3047}
3048
John Zulaufae842002021-04-15 18:20:55 -06003049HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range) const {
3050 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003051 using Size = FirstAccesses::size_type;
3052 const auto &recorded_accesses = recorded_use.first_accesses_;
3053 Size count = recorded_accesses.size();
3054 if (count) {
3055 const auto &last_access = recorded_accesses.back();
3056 bool do_write_last = IsWrite(last_access.usage_index);
3057 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003058
John Zulauf4fa68462021-04-26 21:04:22 -06003059 for (Size i = 0; i < count; ++count) {
3060 const auto &first = recorded_accesses[i];
3061 // Skip and quit logic
3062 if (first.tag < tag_range.begin) continue;
3063 if (first.tag >= tag_range.end) {
3064 do_write_last = false; // ignore last since we know it can't be in tag_range
3065 break;
3066 }
3067
3068 hazard = DetectHazard(first.usage_index, first.ordering_rule);
3069 if (hazard.hazard) {
3070 hazard.AddRecordedAccess(first);
3071 break;
3072 }
3073 }
3074
3075 if (do_write_last && tag_range.includes(last_access.tag)) {
3076 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3077 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3078 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3079 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3080 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3081 // the barrier that applies them
3082 barrier |= recorded_use.first_write_layout_ordering_;
3083 }
3084 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3085 // the active context
3086 if (recorded_use.first_read_stages_) {
3087 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3088 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3089 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3090 // active context.
3091 barrier.exec_scope |= recorded_use.first_read_stages_;
3092 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3093 barrier.access_scope |= FlagBit(last_access.usage_index);
3094 }
3095 hazard = DetectHazard(last_access.usage_index, barrier);
3096 if (hazard.hazard) {
3097 hazard.AddRecordedAccess(last_access);
3098 }
3099 }
John Zulaufae842002021-04-15 18:20:55 -06003100 }
3101 return hazard;
3102}
3103
John Zulauf2f952d22020-02-10 11:34:51 -07003104// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003105HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003106 HazardResult hazard;
3107 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003108 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3109 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3110 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003111 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003112 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003113 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003114 }
3115 } else {
John Zulauf14940722021-04-12 15:19:02 -06003116 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003117 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003118 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003119 // 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 -07003120 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003121 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003122 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003123 break;
3124 }
3125 }
John Zulauf2f952d22020-02-10 11:34:51 -07003126 }
3127 }
3128 return hazard;
3129}
3130
John Zulaufae842002021-04-15 18:20:55 -06003131HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3132 ResourceUsageTag start_tag) const {
3133 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003134 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003135 // Skip and quit logic
3136 if (first.tag < tag_range.begin) continue;
3137 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003138
3139 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003140 if (hazard.hazard) {
3141 hazard.AddRecordedAccess(first);
3142 break;
3143 }
John Zulaufae842002021-04-15 18:20:55 -06003144 }
3145 return hazard;
3146}
3147
Jeremy Gebben40a22942020-12-22 14:22:06 -07003148HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003149 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003150 // Only supporting image layout transitions for now
3151 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3152 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003153 // only test for WAW if there no intervening read operations.
3154 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003155 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003156 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003157 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003158 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003159 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003160 break;
3161 }
3162 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003163 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3164 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3165 }
3166
3167 return hazard;
3168}
3169
Jeremy Gebben40a22942020-12-22 14:22:06 -07003170HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07003171 const SyncStageAccessFlags &src_access_scope,
John Zulauf14940722021-04-12 15:19:02 -06003172 const ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003173 // Only supporting image layout transitions for now
3174 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3175 HazardResult hazard;
3176 // only test for WAW if there no intervening read operations.
3177 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3178
John Zulaufab7756b2020-12-29 16:10:16 -07003179 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003180 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
3181 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07003182 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003183 if (read_access.tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003184 // The read is in the events first synchronization scope, so we use a barrier hazard check
3185 // If the read stage is not in the src sync scope
3186 // *AND* not execution chained with an existing sync barrier (that's the or)
3187 // then the barrier access is unsafe (R/W after R)
3188 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
3189 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3190 break;
3191 }
3192 } else {
3193 // The read not in the event first sync scope and so is a hazard vs. the layout transition
3194 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3195 }
3196 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003197 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003198 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
John Zulauf14940722021-04-12 15:19:02 -06003199 if (write_tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003200 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3201 // So do a normal barrier hazard check
3202 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3203 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3204 }
3205 } else {
3206 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06003207 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3208 }
John Zulaufd14743a2020-07-03 09:42:39 -06003209 }
John Zulauf361fb532020-07-22 10:45:39 -06003210
John Zulauf0cb5be22020-01-23 12:18:22 -07003211 return hazard;
3212}
3213
John Zulauf5f13a792020-03-10 07:31:21 -06003214// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3215// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3216// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3217void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003218 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003219 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3220 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003221 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003222 } else if (other.write_tag == write_tag) {
3223 // 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 -06003224 // dependency chaining logic or any stage expansion)
3225 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003226 pending_write_barriers |= other.pending_write_barriers;
3227 pending_layout_transition |= other.pending_layout_transition;
3228 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003229 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003230
John Zulaufd14743a2020-07-03 09:42:39 -06003231 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003232 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003233 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003234 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003235 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003236 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003237 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003238 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3239 // but we should wait on profiling data for that.
3240 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003241 auto &my_read = last_reads[my_read_index];
3242 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003243 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003244 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003245 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003246 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003247 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003248 my_read.pending_dep_chain = other_read.pending_dep_chain;
3249 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3250 // May require tracking more than one access per stage.
3251 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003252 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003253 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003254 // Since I'm overwriting the fragement stage read, also update the input attachment info
3255 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003256 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003257 }
John Zulauf14940722021-04-12 15:19:02 -06003258 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003259 // The read tags match so merge the barriers
3260 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003261 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003262 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003263 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003264
John Zulauf5f13a792020-03-10 07:31:21 -06003265 break;
3266 }
3267 }
3268 } else {
3269 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003270 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003271 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003272 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003273 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003274 }
John Zulauf5f13a792020-03-10 07:31:21 -06003275 }
3276 }
John Zulauf361fb532020-07-22 10:45:39 -06003277 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003278 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3279 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003280
3281 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3282 // of the copy and other into this using the update first logic.
3283 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3284 // of the other first_accesses... )
3285 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3286 FirstAccesses firsts(std::move(first_accesses_));
3287 first_accesses_.clear();
3288 first_read_stages_ = 0U;
3289 auto a = firsts.begin();
3290 auto a_end = firsts.end();
3291 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003292 // TODO: Determine whether some tag offset will be needed for PHASE II
3293 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003294 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3295 ++a;
3296 }
3297 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3298 }
3299 for (; a != a_end; ++a) {
3300 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3301 }
3302 }
John Zulauf5f13a792020-03-10 07:31:21 -06003303}
3304
John Zulauf14940722021-04-12 15:19:02 -06003305void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003306 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3307 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003308 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003309 // Mulitple outstanding reads may be of interest and do dependency chains independently
3310 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3311 const auto usage_stage = PipelineStageBit(usage_index);
3312 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003313 for (auto &read_access : last_reads) {
3314 if (read_access.stage == usage_stage) {
3315 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003316 } else if (read_access.barriers & usage_stage) {
3317 read_access.sync_stages |= usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003318 }
3319 }
3320 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003321 for (auto &read_access : last_reads) {
3322 if (read_access.barriers & usage_stage) {
3323 read_access.sync_stages |= usage_stage;
3324 }
3325 }
John Zulaufab7756b2020-12-29 16:10:16 -07003326 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003327 last_read_stages |= usage_stage;
3328 }
John Zulauf4285ee92020-09-23 10:20:52 -06003329
3330 // 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 -07003331 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003332 // TODO Revisit re: multiple reads for a given stage
3333 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003334 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003335 } else {
3336 // Assume write
3337 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003338 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003339 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003340 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003341}
John Zulauf5f13a792020-03-10 07:31:21 -06003342
John Zulauf89311b42020-09-29 16:28:47 -06003343// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3344// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3345// We can overwrite them as *this* write is now after them.
3346//
3347// 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 -06003348void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003349 ClearRead();
3350 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003351 write_tag = tag;
3352 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003353}
3354
John Zulauf1d5f9c12022-05-13 14:51:08 -06003355void ResourceAccessState::ClearWrite() {
3356 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3357 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3358 write_barriers.reset();
3359 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3360 last_write.reset();
3361
3362 write_tag = 0;
3363 write_queue = QueueSyncState::kQueueIdInvalid;
3364}
3365
3366void ResourceAccessState::ClearRead() {
3367 last_reads.clear();
3368 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3369}
3370
John Zulauf89311b42020-09-29 16:28:47 -06003371// Apply the memory barrier without updating the existing barriers. The execution barrier
3372// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3373// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3374// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003375template <typename ScopeOps>
3376void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003377 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3378 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003379 // 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 -06003380 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003381 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3382 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003383 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003384 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003385 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003386 if (layout_transition) {
3387 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3388 }
John Zulaufa0a98292020-09-18 09:30:10 -06003389 }
John Zulauf89311b42020-09-29 16:28:47 -06003390 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3391 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003392
John Zulauf89311b42020-09-29 16:28:47 -06003393 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003394 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3395 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003396 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3397
John Zulaufab7756b2020-12-29 16:10:16 -07003398 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003399 // 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 -06003400 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003401 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3402 stages_in_scope |= read_access.stage;
3403 }
3404 }
3405
3406 for (auto &read_access : last_reads) {
3407 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3408 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3409 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3410 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003411 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003412 }
3413 }
John Zulaufa0a98292020-09-18 09:30:10 -06003414 }
John Zulaufa0a98292020-09-18 09:30:10 -06003415}
3416
John Zulauf14940722021-04-12 15:19:02 -06003417void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003418 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003419 // 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 -06003420 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003421 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003422 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3423 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003424 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003425 }
John Zulauf89311b42020-09-29 16:28:47 -06003426
3427 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003428 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003429 for (auto &read_access : last_reads) {
3430 read_access.barriers |= read_access.pending_dep_chain;
3431 read_execution_barriers |= read_access.barriers;
3432 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003433 }
3434
3435 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3436 write_dependency_chain |= pending_write_dep_chain;
3437 write_barriers |= pending_write_barriers;
3438 pending_write_dep_chain = 0;
3439 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003440}
3441
John Zulauf1d5f9c12022-05-13 14:51:08 -06003442bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3443 return (queue == usage_queue) && (tag <= usage_tag);
3444}
3445
3446bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3447
3448bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3449
3450// Return if the resulting state is "empty"
3451template <typename Pred>
3452bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3453 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3454
3455 // Use the predicate to build a mask of the read stages we are synchronizing
3456 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003457 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003458 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003459 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3460 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003461 }
3462 }
3463
John Zulauf434c4e62022-05-19 16:03:56 -06003464 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3465 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3466 uint32_t unsync_count = 0;
3467 for (auto &read_access : last_reads) {
3468 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3469 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3470 sync_reads |= read_access.stage;
3471 } else {
3472 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003473 }
3474 }
3475
3476 if (unsync_count) {
3477 if (sync_reads) {
3478 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3479 ReadStates unsync_reads;
3480 unsync_reads.reserve(unsync_count);
3481 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3482 for (auto &read_access : last_reads) {
3483 if (0 == (read_access.stage & sync_reads)) {
3484 unsync_reads.emplace_back(read_access);
3485 unsync_read_stages |= read_access.stage;
3486 }
3487 }
3488 last_read_stages = unsync_read_stages;
3489 last_reads = std::move(unsync_reads);
3490 }
3491 } else {
3492 // Nothing remains (or it was empty to begin with)
3493 ClearRead();
3494 }
3495
3496 bool all_clear = last_reads.size() == 0;
3497 if (last_write.any()) {
3498 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3499 // Clear any predicated write, or any the write from any any access with synchronized reads.
3500 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3501 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3502 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3503 ClearWrite();
3504 } else {
3505 all_clear = false;
3506 }
3507 }
3508 return all_clear;
3509}
3510
John Zulaufae842002021-04-15 18:20:55 -06003511bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3512 if (!first_accesses_.size()) return false;
3513 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3514 return tag_range.intersects(first_access_range);
3515}
3516
John Zulauf1d5f9c12022-05-13 14:51:08 -06003517void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3518 if (last_write.any()) write_tag += offset;
3519 for (auto &read_access : last_reads) {
3520 read_access.tag += offset;
3521 }
3522 for (auto &first : first_accesses_) {
3523 first.tag += offset;
3524 }
3525}
3526
3527ResourceAccessState::ResourceAccessState()
3528 : write_barriers(~SyncStageAccessFlags(0)),
3529 write_dependency_chain(0),
3530 write_tag(),
3531 write_queue(QueueSyncState::kQueueIdInvalid),
3532 last_write(0),
3533 input_attachment_read(false),
3534 last_read_stages(0),
3535 read_execution_barriers(0),
3536 pending_write_dep_chain(0),
3537 pending_layout_transition(false),
3538 pending_write_barriers(0),
3539 pending_layout_ordering_(),
3540 first_accesses_(),
3541 first_read_stages_(0U),
3542 first_write_layout_ordering_() {}
3543
John Zulauf59e25072020-07-17 10:55:21 -06003544// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003545VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3546 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003547
John Zulaufab7756b2020-12-29 16:10:16 -07003548 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003549 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003550 barriers = read_access.barriers;
3551 break;
John Zulauf59e25072020-07-17 10:55:21 -06003552 }
3553 }
John Zulauf4285ee92020-09-23 10:20:52 -06003554
John Zulauf59e25072020-07-17 10:55:21 -06003555 return barriers;
3556}
3557
John Zulauf1d5f9c12022-05-13 14:51:08 -06003558void ResourceAccessState::SetQueueId(QueueId id) {
3559 for (auto &read_access : last_reads) {
3560 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3561 read_access.queue = id;
3562 }
3563 }
3564 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3565 write_queue = id;
3566 }
3567}
3568
John Zulauf00119522022-05-23 19:07:42 -06003569bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3570 return 0 != (write_dependency_chain & src_exec_scope);
3571}
3572
3573bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3574 return (src_access_scope & last_write).any();
3575}
3576
John Zulaufb7578302022-05-19 13:50:18 -06003577bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3578 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003579 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3580}
3581
3582bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3583 SyncStageAccessFlags src_access_scope) const {
3584 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003585}
3586
3587bool ResourceAccessState::WriteInEventScope(const SyncStageAccessFlags &src_access_scope, ResourceUsageTag scope_tag) const {
3588 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3589 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3590 // in order to know if it's in the excecution scope
John Zulauf00119522022-05-23 19:07:42 -06003591 return (write_tag < scope_tag) && WriteInScope(src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003592}
3593
John Zulaufcb7e1672022-05-04 13:46:08 -06003594bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003595 assert(IsRead(usage));
3596 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3597 // * the previous reads are not hazards, and thus last_write must be visible and available to
3598 // any reads that happen after.
3599 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3600 // 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 -07003601 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003602}
3603
Jeremy Gebben40a22942020-12-22 14:22:06 -07003604VkPipelineStageFlags2KHR ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003605 // Whether the stage are in the ordering scope only matters if the current write is ordered
Jeremy Gebben40a22942020-12-22 14:22:06 -07003606 VkPipelineStageFlags2KHR ordered_stages = last_read_stages & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003607 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003608 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003609 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003610 // 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 -07003611 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003612 }
3613
3614 return ordered_stages;
3615}
3616
John Zulauf14940722021-04-12 15:19:02 -06003617void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003618 // Only record until we record a write.
3619 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003620 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003621 if (0 == (usage_stage & first_read_stages_)) {
3622 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003623 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003624 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003625 if (0 == (read_execution_barriers & usage_stage)) {
3626 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3627 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3628 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003629 }
3630 }
3631}
3632
John Zulauf4fa68462021-04-26 21:04:22 -06003633void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3634 // Only call this after recording an image layout transition
3635 assert(first_accesses_.size());
3636 if (first_accesses_.back().tag == tag) {
3637 // 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 +02003638 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003639 first_write_layout_ordering_ = layout_ordering;
3640 }
3641}
3642
John Zulauf1d5f9c12022-05-13 14:51:08 -06003643ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3644 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3645 : stage(stage_),
3646 access(access_),
3647 barriers(barriers_),
3648 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3649 tag(tag_),
3650 queue(QueueSyncState::kQueueIdInvalid),
3651 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3652
John Zulaufee984022022-04-13 16:39:50 -06003653void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3654 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3655 stage = stage_;
3656 access = access_;
3657 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003658 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003659 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003660 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 -06003661}
3662
John Zulauf00119522022-05-23 19:07:42 -06003663// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3664// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3665// that have bee applied (via semaphore) to those accesses can be chained off of.
3666bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3667 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3668 return (exec_scope & effective_stages) != 0;
3669}
3670
John Zulauf697c0e12022-04-19 16:31:12 -06003671ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3672 ResourceUsageRange reserve;
3673 reserve.begin = tag_limit_.fetch_add(tag_count);
3674 reserve.end = reserve.begin + tag_count;
3675 return reserve;
3676}
3677
John Zulaufbbda4572022-04-19 16:20:45 -06003678const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3679 return GetMappedPlainFromShared(queue_sync_states_, queue);
3680}
3681
3682QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3683
3684std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3685 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3686}
3687
3688std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3689 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3690}
3691
John Zulauf1d5f9c12022-05-13 14:51:08 -06003692template <typename BatchSet, typename Predicate>
3693static BatchSet GetQueueLastBatchSnapshotImpl(const SyncValidator::QueueSyncStatesMap &queues, Predicate &&pred) {
3694 BatchSet snapshot;
3695 for (auto &queue : queues) {
John Zulauf697c0e12022-04-19 16:31:12 -06003696 auto batch = queue.second->LastBatch();
John Zulauf1d5f9c12022-05-13 14:51:08 -06003697 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003698 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003699 return snapshot;
3700}
3701
3702template <typename Predicate>
3703QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
3704 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::ConstBatchSet, Predicate>(queue_sync_states_,
3705 std::forward<Predicate>(pred));
3706}
3707
3708template <typename Predicate>
3709QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
3710 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::BatchSet, Predicate>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf697c0e12022-04-19 16:31:12 -06003711}
3712
John Zulaufcb7e1672022-05-04 13:46:08 -06003713bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3714 const std::shared_ptr<QueueBatchContext> &batch,
3715 const VkSemaphoreSubmitInfo &signal_info) {
3716 const SyncExecScope exec_scope =
3717 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3718 const VkSemaphore sem = sem_state->semaphore();
3719 auto signal_it = signaled_.find(sem);
3720 std::shared_ptr<Signal> insert_signal;
3721 if (signal_it == signaled_.end()) {
3722 if (prev_) {
3723 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3724 if (prev_sig) {
3725 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3726 insert_signal = std::make_shared<Signal>(*prev_sig);
3727 }
3728 }
3729 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3730 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003731 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003732
3733 bool success = false;
3734 if (!signal_it->second) {
3735 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3736 success = true;
3737 }
3738
3739 return success;
3740}
3741
3742std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3743 std::shared_ptr<Signal> unsignaled;
3744 const auto found_it = signaled_.find(sem);
3745 if (found_it != signaled_.end()) {
3746 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3747 // a bit.
3748 unsignaled = std::move(found_it->second);
3749 if (!prev_) {
3750 // No parent, not need to keep the entry
3751 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3752 signaled_.erase(found_it);
3753 }
3754 } else if (prev_) {
3755 // We can't unsignal prev_ because it's const * by design.
3756 // We put in an empty placeholder
3757 signaled_.emplace(sem, std::shared_ptr<Signal>());
3758 unsignaled = GetPrev(sem);
3759 }
3760 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3761 // but CoreChecks should have reported it
3762
3763 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003764 return unsignaled;
3765}
3766
John Zulaufcb7e1672022-05-04 13:46:08 -06003767void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3768 // Overwrite the s tate with the last state from this
3769 if (from) {
3770 assert(sem == from->sem_state->semaphore());
3771 signaled_[sem] = std::move(from);
3772 } else {
3773 signaled_.erase(sem);
3774 }
3775}
3776
3777void SignaledSemaphores::Reset() {
3778 signaled_.clear();
3779 prev_ = nullptr;
3780}
3781
John Zulaufea943c52022-02-22 11:05:17 -07003782std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3783 // If we don't have one, make it.
3784 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3785 assert(cb_state.get());
3786 auto queue_flags = cb_state->GetQueueFlags();
3787 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3788}
3789
John Zulaufcb7e1672022-05-04 13:46:08 -06003790std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003791 return GetMappedInsert(cb_access_state, command_buffer,
3792 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3793}
3794
3795std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3796 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3797}
3798
3799const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3800 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3801}
3802
3803CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3804 return GetAccessContextShared(command_buffer).get();
3805}
3806
3807CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3808 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3809}
3810
John Zulaufd1f85d42020-04-15 12:23:15 -06003811void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003812 auto *access_context = GetAccessContextNoInsert(command_buffer);
3813 if (access_context) {
3814 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003815 }
3816}
3817
John Zulaufd1f85d42020-04-15 12:23:15 -06003818void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3819 auto access_found = cb_access_state.find(command_buffer);
3820 if (access_found != cb_access_state.end()) {
3821 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003822 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003823 cb_access_state.erase(access_found);
3824 }
3825}
3826
John Zulauf9cb530d2019-09-30 14:14:10 -06003827bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3828 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3829 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003830 const auto *cb_context = GetAccessContext(commandBuffer);
3831 assert(cb_context);
3832 if (!cb_context) return skip;
3833 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003834
John Zulauf3d84f1b2020-03-09 13:33:25 -06003835 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003836 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3837 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003838
3839 for (uint32_t region = 0; region < regionCount; region++) {
3840 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003841 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003842 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003843 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003844 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003845 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003846 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003847 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003848 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003849 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003850 }
John Zulauf16adfc92020-04-08 10:28:33 -06003851 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003852 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003853 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003854 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003855 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003856 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003857 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003858 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003859 }
3860 }
3861 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003862 }
3863 return skip;
3864}
3865
3866void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3867 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003868 auto *cb_context = GetAccessContext(commandBuffer);
3869 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003870 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003871 auto *context = cb_context->GetCurrentAccessContext();
3872
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003873 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3874 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003875
3876 for (uint32_t region = 0; region < regionCount; region++) {
3877 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003878 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003879 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003880 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003881 }
John Zulauf16adfc92020-04-08 10:28:33 -06003882 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003883 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003884 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003885 }
3886 }
3887}
3888
John Zulauf4a6105a2020-11-17 15:11:05 -07003889void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3890 // Clear out events from the command buffer contexts
3891 for (auto &cb_context : cb_access_state) {
3892 cb_context.second->RecordDestroyEvent(event);
3893 }
3894}
3895
Tony-LunarGef035472021-11-02 10:23:33 -06003896bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
3897 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04003898 bool skip = false;
3899 const auto *cb_context = GetAccessContext(commandBuffer);
3900 assert(cb_context);
3901 if (!cb_context) return skip;
3902 const auto *context = cb_context->GetCurrentAccessContext();
3903
3904 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003905 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3906 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003907
3908 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3909 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3910 if (src_buffer) {
3911 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003912 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003913 if (hazard.hazard) {
3914 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09003915 skip |=
3916 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
3917 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
3918 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
3919 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003920 }
3921 }
3922 if (dst_buffer && !skip) {
3923 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003924 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003925 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09003926 skip |=
3927 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
3928 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
3929 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
3930 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003931 }
3932 }
3933 if (skip) break;
3934 }
3935 return skip;
3936}
3937
Tony-LunarGef035472021-11-02 10:23:33 -06003938bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3939 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3940 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3941}
3942
3943bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
3944 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3945}
3946
3947void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04003948 auto *cb_context = GetAccessContext(commandBuffer);
3949 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06003950 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04003951 auto *context = cb_context->GetCurrentAccessContext();
3952
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003953 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3954 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003955
3956 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3957 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3958 if (src_buffer) {
3959 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003960 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003961 }
3962 if (dst_buffer) {
3963 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003964 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003965 }
3966 }
3967}
3968
Tony-LunarGef035472021-11-02 10:23:33 -06003969void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3970 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3971}
3972
3973void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
3974 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3975}
3976
John Zulauf5c5e88d2019-12-26 11:22:02 -07003977bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3978 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3979 const VkImageCopy *pRegions) const {
3980 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003981 const auto *cb_access_context = GetAccessContext(commandBuffer);
3982 assert(cb_access_context);
3983 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003984
John Zulauf3d84f1b2020-03-09 13:33:25 -06003985 const auto *context = cb_access_context->GetCurrentAccessContext();
3986 assert(context);
3987 if (!context) return skip;
3988
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003989 auto src_image = Get<IMAGE_STATE>(srcImage);
3990 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003991 for (uint32_t region = 0; region < regionCount; region++) {
3992 const auto &copy_region = pRegions[region];
3993 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003994 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02003995 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003996 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003997 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003998 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003999 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004000 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004001 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004002 }
4003
4004 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004005 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004006 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004007 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004008 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004009 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004010 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004011 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004012 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004013 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004014 }
4015 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004016
John Zulauf5c5e88d2019-12-26 11:22:02 -07004017 return skip;
4018}
4019
4020void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4021 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4022 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004023 auto *cb_access_context = GetAccessContext(commandBuffer);
4024 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004025 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004026 auto *context = cb_access_context->GetCurrentAccessContext();
4027 assert(context);
4028
Jeremy Gebben9f537102021-10-05 16:37:12 -06004029 auto src_image = Get<IMAGE_STATE>(srcImage);
4030 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004031
4032 for (uint32_t region = 0; region < regionCount; region++) {
4033 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004034 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004035 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004036 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004037 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004038 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004039 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004040 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004041 }
4042 }
4043}
4044
Tony-LunarGb61514a2021-11-02 12:36:51 -06004045bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4046 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004047 bool skip = false;
4048 const auto *cb_access_context = GetAccessContext(commandBuffer);
4049 assert(cb_access_context);
4050 if (!cb_access_context) return skip;
4051
4052 const auto *context = cb_access_context->GetCurrentAccessContext();
4053 assert(context);
4054 if (!context) return skip;
4055
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004056 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4057 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004058
Jeff Leger178b1e52020-10-05 12:22:23 -04004059 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4060 const auto &copy_region = pCopyImageInfo->pRegions[region];
4061 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004062 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004063 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004064 if (hazard.hazard) {
4065 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004066 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004067 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004068 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004069 }
4070 }
4071
4072 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004073 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004074 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004075 if (hazard.hazard) {
4076 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004077 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004078 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004079 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004080 }
4081 if (skip) break;
4082 }
4083 }
4084
4085 return skip;
4086}
4087
Tony-LunarGb61514a2021-11-02 12:36:51 -06004088bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4089 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4090 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4091}
4092
4093bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4094 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4095}
4096
4097void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004098 auto *cb_access_context = GetAccessContext(commandBuffer);
4099 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004100 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004101 auto *context = cb_access_context->GetCurrentAccessContext();
4102 assert(context);
4103
Jeremy Gebben9f537102021-10-05 16:37:12 -06004104 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4105 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004106
4107 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4108 const auto &copy_region = pCopyImageInfo->pRegions[region];
4109 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004110 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004111 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004112 }
4113 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004114 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004115 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004116 }
4117 }
4118}
4119
Tony-LunarGb61514a2021-11-02 12:36:51 -06004120void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4121 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4122}
4123
4124void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4125 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4126}
4127
John Zulauf9cb530d2019-09-30 14:14:10 -06004128bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4129 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4130 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4131 uint32_t bufferMemoryBarrierCount,
4132 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4133 uint32_t imageMemoryBarrierCount,
4134 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4135 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004136 const auto *cb_access_context = GetAccessContext(commandBuffer);
4137 assert(cb_access_context);
4138 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004139
John Zulauf36ef9282021-02-02 11:47:24 -07004140 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4141 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4142 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4143 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004144 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004145 return skip;
4146}
4147
4148void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4149 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4150 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4151 uint32_t bufferMemoryBarrierCount,
4152 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4153 uint32_t imageMemoryBarrierCount,
4154 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004155 auto *cb_access_context = GetAccessContext(commandBuffer);
4156 assert(cb_access_context);
4157 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004158
John Zulauf1bf30522021-09-03 15:39:06 -06004159 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4160 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4161 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4162 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004163}
4164
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004165bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4166 const VkDependencyInfoKHR *pDependencyInfo) const {
4167 bool skip = false;
4168 const auto *cb_access_context = GetAccessContext(commandBuffer);
4169 assert(cb_access_context);
4170 if (!cb_access_context) return skip;
4171
4172 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4173 skip = pipeline_barrier.Validate(*cb_access_context);
4174 return skip;
4175}
4176
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004177bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4178 const VkDependencyInfo *pDependencyInfo) const {
4179 bool skip = false;
4180 const auto *cb_access_context = GetAccessContext(commandBuffer);
4181 assert(cb_access_context);
4182 if (!cb_access_context) return skip;
4183
4184 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4185 skip = pipeline_barrier.Validate(*cb_access_context);
4186 return skip;
4187}
4188
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004189void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4190 auto *cb_access_context = GetAccessContext(commandBuffer);
4191 assert(cb_access_context);
4192 if (!cb_access_context) return;
4193
John Zulauf1bf30522021-09-03 15:39:06 -06004194 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4195 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004196}
4197
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004198void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4199 auto *cb_access_context = GetAccessContext(commandBuffer);
4200 assert(cb_access_context);
4201 if (!cb_access_context) return;
4202
4203 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4204 *pDependencyInfo);
4205}
4206
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004207void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004208 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004209 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004210
John Zulauf5f13a792020-03-10 07:31:21 -06004211 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4212 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004213 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004214 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4215 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004216
John Zulauf1d5f9c12022-05-13 14:51:08 -06004217 QueueId queue_id = QueueSyncState::kQueueIdBase;
4218 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004219 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004220 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004221 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4222 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004223}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004224
John Zulauf355e49b2020-04-24 15:11:15 -06004225bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004226 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004227 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004228 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004229 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004230 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004231 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004232 }
John Zulauf355e49b2020-04-24 15:11:15 -06004233 return skip;
4234}
4235
4236bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4237 VkSubpassContents contents) const {
4238 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004239 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004240 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004241 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004242 return skip;
4243}
4244
4245bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004246 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004247 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004248 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004249 return skip;
4250}
4251
4252bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4253 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004254 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004255 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004256 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004257 return skip;
4258}
4259
John Zulauf3d84f1b2020-03-09 13:33:25 -06004260void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4261 VkResult result) {
4262 // The state tracker sets up the command buffer state
4263 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4264
4265 // Create/initialize the structure that trackers accesses at the command buffer scope.
4266 auto cb_access_context = GetAccessContext(commandBuffer);
4267 assert(cb_access_context);
4268 cb_access_context->Reset();
4269}
4270
4271void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004272 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004273 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004274 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004275 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004276 }
4277}
4278
4279void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4280 VkSubpassContents contents) {
4281 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004282 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004283 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004284 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004285}
4286
4287void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4288 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4289 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004290 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004291}
4292
4293void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4294 const VkRenderPassBeginInfo *pRenderPassBegin,
4295 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4296 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004297 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004298}
4299
Mike Schuchardt2df08912020-12-15 16:28:09 -08004300bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004301 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004302 bool skip = false;
4303
4304 auto cb_context = GetAccessContext(commandBuffer);
4305 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004306 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004307 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004308 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004309}
4310
4311bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4312 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004313 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004314 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004315 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004316 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4317 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004318 return skip;
4319}
4320
Mike Schuchardt2df08912020-12-15 16:28:09 -08004321bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4322 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004323 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004324 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004325 return skip;
4326}
4327
4328bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4329 const VkSubpassEndInfo *pSubpassEndInfo) const {
4330 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004331 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004332 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004333}
4334
4335void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004336 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004337 auto cb_context = GetAccessContext(commandBuffer);
4338 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004339 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004340
sjfricke0bea06e2022-06-05 09:22:26 +09004341 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004342}
4343
4344void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4345 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004346 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004347 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004348 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004349}
4350
4351void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4352 const VkSubpassEndInfo *pSubpassEndInfo) {
4353 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004354 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004355}
4356
4357void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4358 const VkSubpassEndInfo *pSubpassEndInfo) {
4359 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004360 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004361}
4362
sfricke-samsung85584a72021-09-30 21:43:38 -07004363bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004364 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004365 bool skip = false;
4366
4367 auto cb_context = GetAccessContext(commandBuffer);
4368 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004369 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004370
sjfricke0bea06e2022-06-05 09:22:26 +09004371 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004372 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004373 return skip;
4374}
4375
4376bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4377 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004378 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004379 return skip;
4380}
4381
Mike Schuchardt2df08912020-12-15 16:28:09 -08004382bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004383 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004384 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004385 return skip;
4386}
4387
4388bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004389 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004390 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004391 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004392 return skip;
4393}
4394
sjfricke0bea06e2022-06-05 09:22:26 +09004395void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4396 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004397 // Resolve the all subpass contexts to the command buffer contexts
4398 auto cb_context = GetAccessContext(commandBuffer);
4399 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004400 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004401
sjfricke0bea06e2022-06-05 09:22:26 +09004402 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004403}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004404
John Zulauf33fc1d52020-07-17 11:01:10 -06004405// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4406// updates to a resource which do not conflict at the byte level.
4407// TODO: Revisit this rule to see if it needs to be tighter or looser
4408// TODO: Add programatic control over suppression heuristics
4409bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4410 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4411}
4412
John Zulauf3d84f1b2020-03-09 13:33:25 -06004413void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004414 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004415 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004416}
4417
4418void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004419 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004420 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004421}
4422
4423void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004424 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004425 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004426}
locke-lunarga19c71d2020-03-02 18:17:04 -07004427
sfricke-samsung71f04e32022-03-16 01:21:21 -05004428template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004429bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004430 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4431 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004432 bool skip = false;
4433 const auto *cb_access_context = GetAccessContext(commandBuffer);
4434 assert(cb_access_context);
4435 if (!cb_access_context) return skip;
4436
4437 const auto *context = cb_access_context->GetCurrentAccessContext();
4438 assert(context);
4439 if (!context) return skip;
4440
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004441 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4442 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004443
4444 for (uint32_t region = 0; region < regionCount; region++) {
4445 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004446 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004447 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004448 if (src_buffer) {
4449 ResourceAccessRange src_range =
4450 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004451 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004452 if (hazard.hazard) {
4453 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004454 skip |=
4455 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4456 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4457 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4458 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004459 }
4460 }
4461
Jeremy Gebben40a22942020-12-22 14:22:06 -07004462 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004463 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004464 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004465 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004466 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004467 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004468 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004469 }
4470 if (skip) break;
4471 }
4472 if (skip) break;
4473 }
4474 return skip;
4475}
4476
Jeff Leger178b1e52020-10-05 12:22:23 -04004477bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4478 VkImageLayout dstImageLayout, uint32_t regionCount,
4479 const VkBufferImageCopy *pRegions) const {
4480 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004481 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004482}
4483
4484bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4485 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4486 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4487 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004488 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4489}
4490
4491bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4492 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4493 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4494 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4495 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004496}
4497
sfricke-samsung71f04e32022-03-16 01:21:21 -05004498template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004499void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004500 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4501 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004502 auto *cb_access_context = GetAccessContext(commandBuffer);
4503 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004504
Jeff Leger178b1e52020-10-05 12:22:23 -04004505 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004506 auto *context = cb_access_context->GetCurrentAccessContext();
4507 assert(context);
4508
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004509 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4510 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004511
4512 for (uint32_t region = 0; region < regionCount; region++) {
4513 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004514 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004515 if (src_buffer) {
4516 ResourceAccessRange src_range =
4517 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004518 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004519 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004520 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004521 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004522 }
4523 }
4524}
4525
Jeff Leger178b1e52020-10-05 12:22:23 -04004526void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4527 VkImageLayout dstImageLayout, uint32_t regionCount,
4528 const VkBufferImageCopy *pRegions) {
4529 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004530 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004531}
4532
4533void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4534 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4535 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4536 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4537 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004538 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4539}
4540
4541void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4542 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4543 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4544 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4545 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4546 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004547}
4548
sfricke-samsung71f04e32022-03-16 01:21:21 -05004549template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004550bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004551 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4552 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004553 bool skip = false;
4554 const auto *cb_access_context = GetAccessContext(commandBuffer);
4555 assert(cb_access_context);
4556 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004557
locke-lunarga19c71d2020-03-02 18:17:04 -07004558 const auto *context = cb_access_context->GetCurrentAccessContext();
4559 assert(context);
4560 if (!context) return skip;
4561
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004562 auto src_image = Get<IMAGE_STATE>(srcImage);
4563 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004564 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004565 for (uint32_t region = 0; region < regionCount; region++) {
4566 const auto &copy_region = pRegions[region];
4567 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004568 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004569 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004570 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004571 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004572 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004573 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004574 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004575 }
John Zulauf477700e2021-01-06 11:41:49 -07004576 if (dst_mem) {
4577 ResourceAccessRange dst_range =
4578 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004579 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004580 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004581 skip |=
4582 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4583 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4584 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4585 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004586 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004587 }
4588 }
4589 if (skip) break;
4590 }
4591 return skip;
4592}
4593
Jeff Leger178b1e52020-10-05 12:22:23 -04004594bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4595 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4596 const VkBufferImageCopy *pRegions) const {
4597 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004598 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004599}
4600
4601bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4602 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4603 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4604 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004605 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4606}
4607
4608bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4609 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4610 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4611 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4612 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004613}
4614
sfricke-samsung71f04e32022-03-16 01:21:21 -05004615template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004616void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004617 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004618 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004619 auto *cb_access_context = GetAccessContext(commandBuffer);
4620 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004621
Jeff Leger178b1e52020-10-05 12:22:23 -04004622 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004623 auto *context = cb_access_context->GetCurrentAccessContext();
4624 assert(context);
4625
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004626 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004627 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004628 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004629 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004630
4631 for (uint32_t region = 0; region < regionCount; region++) {
4632 const auto &copy_region = pRegions[region];
4633 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004634 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004635 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004636 if (dst_buffer) {
4637 ResourceAccessRange dst_range =
4638 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004639 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004640 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004641 }
4642 }
4643}
4644
Jeff Leger178b1e52020-10-05 12:22:23 -04004645void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4646 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4647 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004648 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004649}
4650
4651void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4652 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4653 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4654 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4655 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004656 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4657}
4658
4659void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4660 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4661 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4662 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4663 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4664 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004665}
4666
4667template <typename RegionType>
4668bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4669 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004670 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004671 bool skip = false;
4672 const auto *cb_access_context = GetAccessContext(commandBuffer);
4673 assert(cb_access_context);
4674 if (!cb_access_context) return skip;
4675
4676 const auto *context = cb_access_context->GetCurrentAccessContext();
4677 assert(context);
4678 if (!context) return skip;
4679
sjfricke0bea06e2022-06-05 09:22:26 +09004680 const char *caller_name = CommandTypeString(cmd_type);
4681
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004682 auto src_image = Get<IMAGE_STATE>(srcImage);
4683 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004684
4685 for (uint32_t region = 0; region < regionCount; region++) {
4686 const auto &blit_region = pRegions[region];
4687 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004688 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4689 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4690 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4691 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4692 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4693 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004694 auto hazard =
4695 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004696 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004697 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004698 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004699 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004700 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004701 }
4702 }
4703
4704 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004705 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4706 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4707 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4708 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4709 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4710 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004711 auto hazard =
4712 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004713 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004714 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004715 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004716 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004717 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004718 }
4719 if (skip) break;
4720 }
4721 }
4722
4723 return skip;
4724}
4725
Jeff Leger178b1e52020-10-05 12:22:23 -04004726bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4727 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4728 const VkImageBlit *pRegions, VkFilter filter) const {
4729 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004730 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004731}
4732
4733bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4734 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4735 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4736 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004737 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004738}
4739
Tony-LunarG542ae912021-11-04 16:06:44 -06004740bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4741 const VkBlitImageInfo2 *pBlitImageInfo) const {
4742 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004743 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4744 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004745}
4746
Jeff Leger178b1e52020-10-05 12:22:23 -04004747template <typename RegionType>
4748void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4749 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4750 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004751 auto *cb_access_context = GetAccessContext(commandBuffer);
4752 assert(cb_access_context);
4753 auto *context = cb_access_context->GetCurrentAccessContext();
4754 assert(context);
4755
Jeremy Gebben9f537102021-10-05 16:37:12 -06004756 auto src_image = Get<IMAGE_STATE>(srcImage);
4757 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004758
4759 for (uint32_t region = 0; region < regionCount; region++) {
4760 const auto &blit_region = pRegions[region];
4761 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004762 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4763 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4764 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4765 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4766 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4767 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004768 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004769 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004770 }
4771 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004772 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4773 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4774 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4775 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4776 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4777 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004778 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004779 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004780 }
4781 }
4782}
locke-lunarg36ba2592020-04-03 09:42:04 -06004783
Jeff Leger178b1e52020-10-05 12:22:23 -04004784void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4785 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4786 const VkImageBlit *pRegions, VkFilter filter) {
4787 auto *cb_access_context = GetAccessContext(commandBuffer);
4788 assert(cb_access_context);
4789 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4790 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4791 pRegions, filter);
4792 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4793}
4794
4795void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4796 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4797 auto *cb_access_context = GetAccessContext(commandBuffer);
4798 assert(cb_access_context);
4799 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4800 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4801 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4802 pBlitImageInfo->filter, tag);
4803}
4804
Tony-LunarG542ae912021-11-04 16:06:44 -06004805void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4806 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4807 auto *cb_access_context = GetAccessContext(commandBuffer);
4808 assert(cb_access_context);
4809 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4810 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4811 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4812 pBlitImageInfo->filter, tag);
4813}
4814
John Zulauffaea0ee2021-01-14 14:01:32 -07004815bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4816 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4817 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09004818 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004819 bool skip = false;
4820 if (drawCount == 0) return skip;
4821
sjfricke0bea06e2022-06-05 09:22:26 +09004822 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004823 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004824 VkDeviceSize size = struct_size;
4825 if (drawCount == 1 || stride == size) {
4826 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004827 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004828 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4829 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004830 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004831 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004832 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004833 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004834 }
4835 } else {
4836 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004837 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004838 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4839 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004840 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004841 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
4842 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
4843 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004844 break;
4845 }
4846 }
4847 }
4848 return skip;
4849}
4850
John Zulauf14940722021-04-12 15:19:02 -06004851void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004852 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4853 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004854 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004855 VkDeviceSize size = struct_size;
4856 if (drawCount == 1 || stride == size) {
4857 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004858 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004859 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004860 } else {
4861 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004862 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004863 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4864 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004865 }
4866 }
4867}
4868
John Zulauffaea0ee2021-01-14 14:01:32 -07004869bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4870 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09004871 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004872 bool skip = false;
4873
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004874 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004875 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004876 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4877 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004878 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004879 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
4880 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
4881 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004882 }
4883 return skip;
4884}
4885
John Zulauf14940722021-04-12 15:19:02 -06004886void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004887 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004888 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004889 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004890}
4891
locke-lunarg36ba2592020-04-03 09:42:04 -06004892bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004893 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004894 const auto *cb_access_context = GetAccessContext(commandBuffer);
4895 assert(cb_access_context);
4896 if (!cb_access_context) return skip;
4897
sjfricke0bea06e2022-06-05 09:22:26 +09004898 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004899 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004900}
4901
4902void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004903 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004904 auto *cb_access_context = GetAccessContext(commandBuffer);
4905 assert(cb_access_context);
4906 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004907
locke-lunarg61870c22020-06-09 14:51:50 -06004908 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004909}
locke-lunarge1a67022020-04-29 00:15:36 -06004910
4911bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004912 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004913 const auto *cb_access_context = GetAccessContext(commandBuffer);
4914 assert(cb_access_context);
4915 if (!cb_access_context) return skip;
4916
4917 const auto *context = cb_access_context->GetCurrentAccessContext();
4918 assert(context);
4919 if (!context) return skip;
4920
sjfricke0bea06e2022-06-05 09:22:26 +09004921 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07004922 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09004923 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06004924 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004925}
4926
4927void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004928 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004929 auto *cb_access_context = GetAccessContext(commandBuffer);
4930 assert(cb_access_context);
4931 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4932 auto *context = cb_access_context->GetCurrentAccessContext();
4933 assert(context);
4934
locke-lunarg61870c22020-06-09 14:51:50 -06004935 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4936 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004937}
4938
4939bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4940 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004941 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004942 const auto *cb_access_context = GetAccessContext(commandBuffer);
4943 assert(cb_access_context);
4944 if (!cb_access_context) return skip;
4945
sjfricke0bea06e2022-06-05 09:22:26 +09004946 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
4947 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
4948 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06004949 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004950}
4951
4952void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4953 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004954 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004955 auto *cb_access_context = GetAccessContext(commandBuffer);
4956 assert(cb_access_context);
4957 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004958
locke-lunarg61870c22020-06-09 14:51:50 -06004959 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4960 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4961 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004962}
4963
4964bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4965 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004966 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004967 const auto *cb_access_context = GetAccessContext(commandBuffer);
4968 assert(cb_access_context);
4969 if (!cb_access_context) return skip;
4970
sjfricke0bea06e2022-06-05 09:22:26 +09004971 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
4972 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
4973 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06004974 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004975}
4976
4977void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4978 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004979 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004980 auto *cb_access_context = GetAccessContext(commandBuffer);
4981 assert(cb_access_context);
4982 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004983
locke-lunarg61870c22020-06-09 14:51:50 -06004984 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4985 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4986 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004987}
4988
4989bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4990 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004991 bool skip = false;
4992 if (drawCount == 0) return skip;
4993
locke-lunargff255f92020-05-13 18:53:52 -06004994 const auto *cb_access_context = GetAccessContext(commandBuffer);
4995 assert(cb_access_context);
4996 if (!cb_access_context) return skip;
4997
4998 const auto *context = cb_access_context->GetCurrentAccessContext();
4999 assert(context);
5000 if (!context) return skip;
5001
sjfricke0bea06e2022-06-05 09:22:26 +09005002 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5003 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005004 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005005 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005006
5007 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5008 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5009 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005010 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005011 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005012}
5013
5014void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5015 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005016 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005017 if (drawCount == 0) return;
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_DRAWINDIRECT);
5021 auto *context = cb_access_context->GetCurrentAccessContext();
5022 assert(context);
5023
locke-lunarg61870c22020-06-09 14:51:50 -06005024 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5025 cb_access_context->RecordDrawSubpassAttachment(tag);
5026 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005027
5028 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5029 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5030 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005031 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005032}
5033
5034bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5035 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005036 bool skip = false;
5037 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005038 const auto *cb_access_context = GetAccessContext(commandBuffer);
5039 assert(cb_access_context);
5040 if (!cb_access_context) return skip;
5041
5042 const auto *context = cb_access_context->GetCurrentAccessContext();
5043 assert(context);
5044 if (!context) return skip;
5045
sjfricke0bea06e2022-06-05 09:22:26 +09005046 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5047 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005048 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005049 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005050
5051 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5052 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5053 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005054 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005055 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005056}
5057
5058void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5059 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005060 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005061 auto *cb_access_context = GetAccessContext(commandBuffer);
5062 assert(cb_access_context);
5063 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5064 auto *context = cb_access_context->GetCurrentAccessContext();
5065 assert(context);
5066
locke-lunarg61870c22020-06-09 14:51:50 -06005067 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5068 cb_access_context->RecordDrawSubpassAttachment(tag);
5069 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005070
5071 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5072 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5073 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005074 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005075}
5076
5077bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5078 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005079 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -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
5085 const auto *context = cb_access_context->GetCurrentAccessContext();
5086 assert(context);
5087 if (!context) return skip;
5088
sjfricke0bea06e2022-06-05 09:22:26 +09005089 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5090 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005091 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005092 maxDrawCount, stride, cmd_type);
5093 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005094
5095 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5096 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5097 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005098 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005099 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005100}
5101
5102bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5103 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5104 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005105 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005106 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005107}
5108
sfricke-samsung85584a72021-09-30 21:43:38 -07005109void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5110 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5111 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005112 auto *cb_access_context = GetAccessContext(commandBuffer);
5113 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005114 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005115 auto *context = cb_access_context->GetCurrentAccessContext();
5116 assert(context);
5117
locke-lunarg61870c22020-06-09 14:51:50 -06005118 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5119 cb_access_context->RecordDrawSubpassAttachment(tag);
5120 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5121 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005122
5123 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5124 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5125 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005126 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005127}
5128
sfricke-samsung85584a72021-09-30 21:43:38 -07005129void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5130 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5131 uint32_t stride) {
5132 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5133 stride);
5134 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5135 CMD_DRAWINDIRECTCOUNT);
5136}
locke-lunarge1a67022020-04-29 00:15:36 -06005137bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5138 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5139 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005140 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005141 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005142}
5143
5144void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5145 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5146 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005147 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5148 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005149 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5150 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005151}
5152
5153bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5154 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5155 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005156 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005157 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005158}
5159
5160void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5161 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5162 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005163 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5164 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005165 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5166 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005167}
5168
5169bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5170 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005171 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005172 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005173 const auto *cb_access_context = GetAccessContext(commandBuffer);
5174 assert(cb_access_context);
5175 if (!cb_access_context) return skip;
5176
5177 const auto *context = cb_access_context->GetCurrentAccessContext();
5178 assert(context);
5179 if (!context) return skip;
5180
sjfricke0bea06e2022-06-05 09:22:26 +09005181 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5182 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005183 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005184 offset, maxDrawCount, stride, cmd_type);
5185 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005186
5187 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5188 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5189 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005190 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005191 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005192}
5193
5194bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5195 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5196 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005197 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005198 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005199}
5200
sfricke-samsung85584a72021-09-30 21:43:38 -07005201void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5202 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5203 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005204 auto *cb_access_context = GetAccessContext(commandBuffer);
5205 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005206 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005207 auto *context = cb_access_context->GetCurrentAccessContext();
5208 assert(context);
5209
locke-lunarg61870c22020-06-09 14:51:50 -06005210 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5211 cb_access_context->RecordDrawSubpassAttachment(tag);
5212 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5213 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005214
5215 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5216 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005217 // We will update the index and vertex buffer in SubmitQueue in the future.
5218 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005219}
5220
sfricke-samsung85584a72021-09-30 21:43:38 -07005221void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5222 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5223 uint32_t maxDrawCount, uint32_t stride) {
5224 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5225 maxDrawCount, stride);
5226 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5227 CMD_DRAWINDEXEDINDIRECTCOUNT);
5228}
5229
locke-lunarge1a67022020-04-29 00:15:36 -06005230bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5231 VkDeviceSize offset, VkBuffer countBuffer,
5232 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5233 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005234 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005235 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005236}
5237
5238void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5239 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5240 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005241 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5242 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005243 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5244 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005245}
5246
5247bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5248 VkDeviceSize offset, VkBuffer countBuffer,
5249 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5250 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005251 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005252 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005253}
5254
5255void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5256 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5257 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005258 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5259 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005260 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5261 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005262}
5263
5264bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5265 const VkClearColorValue *pColor, uint32_t rangeCount,
5266 const VkImageSubresourceRange *pRanges) const {
5267 bool skip = false;
5268 const auto *cb_access_context = GetAccessContext(commandBuffer);
5269 assert(cb_access_context);
5270 if (!cb_access_context) return skip;
5271
5272 const auto *context = cb_access_context->GetCurrentAccessContext();
5273 assert(context);
5274 if (!context) return skip;
5275
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005276 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005277
5278 for (uint32_t index = 0; index < rangeCount; index++) {
5279 const auto &range = pRanges[index];
5280 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005281 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005282 if (hazard.hazard) {
5283 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005284 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005285 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005286 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005287 }
5288 }
5289 }
5290 return skip;
5291}
5292
5293void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5294 const VkClearColorValue *pColor, uint32_t rangeCount,
5295 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005296 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005297 auto *cb_access_context = GetAccessContext(commandBuffer);
5298 assert(cb_access_context);
5299 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5300 auto *context = cb_access_context->GetCurrentAccessContext();
5301 assert(context);
5302
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005303 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005304
5305 for (uint32_t index = 0; index < rangeCount; index++) {
5306 const auto &range = pRanges[index];
5307 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005308 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005309 }
5310 }
5311}
5312
5313bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5314 VkImageLayout imageLayout,
5315 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5316 const VkImageSubresourceRange *pRanges) const {
5317 bool skip = false;
5318 const auto *cb_access_context = GetAccessContext(commandBuffer);
5319 assert(cb_access_context);
5320 if (!cb_access_context) return skip;
5321
5322 const auto *context = cb_access_context->GetCurrentAccessContext();
5323 assert(context);
5324 if (!context) return skip;
5325
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005326 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005327
5328 for (uint32_t index = 0; index < rangeCount; index++) {
5329 const auto &range = pRanges[index];
5330 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005331 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005332 if (hazard.hazard) {
5333 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005334 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005335 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005336 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005337 }
5338 }
5339 }
5340 return skip;
5341}
5342
5343void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5344 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5345 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005346 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005347 auto *cb_access_context = GetAccessContext(commandBuffer);
5348 assert(cb_access_context);
5349 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5350 auto *context = cb_access_context->GetCurrentAccessContext();
5351 assert(context);
5352
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005353 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005354
5355 for (uint32_t index = 0; index < rangeCount; index++) {
5356 const auto &range = pRanges[index];
5357 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005358 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005359 }
5360 }
5361}
5362
5363bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5364 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5365 VkDeviceSize dstOffset, VkDeviceSize stride,
5366 VkQueryResultFlags flags) const {
5367 bool skip = false;
5368 const auto *cb_access_context = GetAccessContext(commandBuffer);
5369 assert(cb_access_context);
5370 if (!cb_access_context) return skip;
5371
5372 const auto *context = cb_access_context->GetCurrentAccessContext();
5373 assert(context);
5374 if (!context) return skip;
5375
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005376 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005377
5378 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005379 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005380 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005381 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005382 skip |=
5383 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5384 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005385 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005386 }
5387 }
locke-lunargff255f92020-05-13 18:53:52 -06005388
5389 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005390 return skip;
5391}
5392
5393void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5394 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5395 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005396 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5397 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005398 auto *cb_access_context = GetAccessContext(commandBuffer);
5399 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005400 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005401 auto *context = cb_access_context->GetCurrentAccessContext();
5402 assert(context);
5403
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005404 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005405
5406 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005407 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005408 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005409 }
locke-lunargff255f92020-05-13 18:53:52 -06005410
5411 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005412}
5413
5414bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5415 VkDeviceSize size, uint32_t data) const {
5416 bool skip = false;
5417 const auto *cb_access_context = GetAccessContext(commandBuffer);
5418 assert(cb_access_context);
5419 if (!cb_access_context) return skip;
5420
5421 const auto *context = cb_access_context->GetCurrentAccessContext();
5422 assert(context);
5423 if (!context) return skip;
5424
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005425 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005426
5427 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005428 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005429 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005430 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005431 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005432 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005433 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005434 }
5435 }
5436 return skip;
5437}
5438
5439void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5440 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005441 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005442 auto *cb_access_context = GetAccessContext(commandBuffer);
5443 assert(cb_access_context);
5444 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5445 auto *context = cb_access_context->GetCurrentAccessContext();
5446 assert(context);
5447
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005448 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005449
5450 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005451 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005452 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005453 }
5454}
5455
5456bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5457 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5458 const VkImageResolve *pRegions) const {
5459 bool skip = false;
5460 const auto *cb_access_context = GetAccessContext(commandBuffer);
5461 assert(cb_access_context);
5462 if (!cb_access_context) return skip;
5463
5464 const auto *context = cb_access_context->GetCurrentAccessContext();
5465 assert(context);
5466 if (!context) return skip;
5467
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005468 auto src_image = Get<IMAGE_STATE>(srcImage);
5469 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005470
5471 for (uint32_t region = 0; region < regionCount; region++) {
5472 const auto &resolve_region = pRegions[region];
5473 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005474 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005475 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005476 if (hazard.hazard) {
5477 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005478 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005479 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005480 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005481 }
5482 }
5483
5484 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005485 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005486 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005487 if (hazard.hazard) {
5488 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005489 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005490 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005491 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005492 }
5493 if (skip) break;
5494 }
5495 }
5496
5497 return skip;
5498}
5499
5500void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5501 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5502 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005503 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5504 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005505 auto *cb_access_context = GetAccessContext(commandBuffer);
5506 assert(cb_access_context);
5507 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5508 auto *context = cb_access_context->GetCurrentAccessContext();
5509 assert(context);
5510
Jeremy Gebben9f537102021-10-05 16:37:12 -06005511 auto src_image = Get<IMAGE_STATE>(srcImage);
5512 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005513
5514 for (uint32_t region = 0; region < regionCount; region++) {
5515 const auto &resolve_region = pRegions[region];
5516 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005517 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005518 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005519 }
5520 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005521 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005522 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005523 }
5524 }
5525}
5526
Tony-LunarG562fc102021-11-12 13:58:35 -07005527bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5528 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005529 bool skip = false;
5530 const auto *cb_access_context = GetAccessContext(commandBuffer);
5531 assert(cb_access_context);
5532 if (!cb_access_context) return skip;
5533
5534 const auto *context = cb_access_context->GetCurrentAccessContext();
5535 assert(context);
5536 if (!context) return skip;
5537
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005538 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5539 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005540
5541 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5542 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5543 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005544 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005545 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005546 if (hazard.hazard) {
5547 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005548 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005549 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005550 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005551 }
5552 }
5553
5554 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005555 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005556 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005557 if (hazard.hazard) {
5558 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005559 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005560 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005561 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005562 }
5563 if (skip) break;
5564 }
5565 }
5566
5567 return skip;
5568}
5569
Tony-LunarG562fc102021-11-12 13:58:35 -07005570bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5571 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5572 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5573}
5574
5575bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5576 const VkResolveImageInfo2 *pResolveImageInfo) const {
5577 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5578}
5579
5580void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5581 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005582 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5583 auto *cb_access_context = GetAccessContext(commandBuffer);
5584 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005585 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005586 auto *context = cb_access_context->GetCurrentAccessContext();
5587 assert(context);
5588
Jeremy Gebben9f537102021-10-05 16:37:12 -06005589 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5590 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005591
5592 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5593 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5594 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005595 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005596 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005597 }
5598 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005599 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005600 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005601 }
5602 }
5603}
5604
Tony-LunarG562fc102021-11-12 13:58:35 -07005605void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5606 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5607 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5608}
5609
5610void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5611 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5612}
5613
locke-lunarge1a67022020-04-29 00:15:36 -06005614bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5615 VkDeviceSize dataSize, const void *pData) const {
5616 bool skip = false;
5617 const auto *cb_access_context = GetAccessContext(commandBuffer);
5618 assert(cb_access_context);
5619 if (!cb_access_context) return skip;
5620
5621 const auto *context = cb_access_context->GetCurrentAccessContext();
5622 assert(context);
5623 if (!context) return skip;
5624
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005625 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005626
5627 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005628 // VK_WHOLE_SIZE not allowed
5629 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005630 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005631 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005632 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005633 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005634 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005635 }
5636 }
5637 return skip;
5638}
5639
5640void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5641 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005642 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005643 auto *cb_access_context = GetAccessContext(commandBuffer);
5644 assert(cb_access_context);
5645 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5646 auto *context = cb_access_context->GetCurrentAccessContext();
5647 assert(context);
5648
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005649 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005650
5651 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005652 // VK_WHOLE_SIZE not allowed
5653 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005654 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005655 }
5656}
locke-lunargff255f92020-05-13 18:53:52 -06005657
5658bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5659 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5660 bool skip = false;
5661 const auto *cb_access_context = GetAccessContext(commandBuffer);
5662 assert(cb_access_context);
5663 if (!cb_access_context) return skip;
5664
5665 const auto *context = cb_access_context->GetCurrentAccessContext();
5666 assert(context);
5667 if (!context) return skip;
5668
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005669 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005670
5671 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005672 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005673 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005674 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005675 skip |=
5676 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5677 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005678 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005679 }
5680 }
5681 return skip;
5682}
5683
5684void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5685 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005686 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005687 auto *cb_access_context = GetAccessContext(commandBuffer);
5688 assert(cb_access_context);
5689 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5690 auto *context = cb_access_context->GetCurrentAccessContext();
5691 assert(context);
5692
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005693 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005694
5695 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005696 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005697 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005698 }
5699}
John Zulauf49beb112020-11-04 16:06:31 -07005700
5701bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5702 bool skip = false;
5703 const auto *cb_context = GetAccessContext(commandBuffer);
5704 assert(cb_context);
5705 if (!cb_context) return skip;
5706
John Zulauf36ef9282021-02-02 11:47:24 -07005707 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005708 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005709}
5710
5711void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5712 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5713 auto *cb_context = GetAccessContext(commandBuffer);
5714 assert(cb_context);
5715 if (!cb_context) return;
John Zulauf1bf30522021-09-03 15:39:06 -06005716 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005717}
5718
John Zulauf4edde622021-02-15 08:54:50 -07005719bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5720 const VkDependencyInfoKHR *pDependencyInfo) const {
5721 bool skip = false;
5722 const auto *cb_context = GetAccessContext(commandBuffer);
5723 assert(cb_context);
5724 if (!cb_context || !pDependencyInfo) return skip;
5725
5726 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5727 return set_event_op.Validate(*cb_context);
5728}
5729
Tony-LunarGc43525f2021-11-15 16:12:38 -07005730bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5731 const VkDependencyInfo *pDependencyInfo) const {
5732 bool skip = false;
5733 const auto *cb_context = GetAccessContext(commandBuffer);
5734 assert(cb_context);
5735 if (!cb_context || !pDependencyInfo) return skip;
5736
5737 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5738 return set_event_op.Validate(*cb_context);
5739}
5740
John Zulauf4edde622021-02-15 08:54:50 -07005741void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5742 const VkDependencyInfoKHR *pDependencyInfo) {
5743 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5744 auto *cb_context = GetAccessContext(commandBuffer);
5745 assert(cb_context);
5746 if (!cb_context || !pDependencyInfo) return;
5747
John Zulauf1bf30522021-09-03 15:39:06 -06005748 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
John Zulauf4edde622021-02-15 08:54:50 -07005749}
5750
Tony-LunarGc43525f2021-11-15 16:12:38 -07005751void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5752 const VkDependencyInfo *pDependencyInfo) {
5753 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5754 auto *cb_context = GetAccessContext(commandBuffer);
5755 assert(cb_context);
5756 if (!cb_context || !pDependencyInfo) return;
5757
5758 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5759}
5760
John Zulauf49beb112020-11-04 16:06:31 -07005761bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5762 VkPipelineStageFlags stageMask) const {
5763 bool skip = false;
5764 const auto *cb_context = GetAccessContext(commandBuffer);
5765 assert(cb_context);
5766 if (!cb_context) return skip;
5767
John Zulauf36ef9282021-02-02 11:47:24 -07005768 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005769 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005770}
5771
5772void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5773 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5774 auto *cb_context = GetAccessContext(commandBuffer);
5775 assert(cb_context);
5776 if (!cb_context) return;
5777
John Zulauf1bf30522021-09-03 15:39:06 -06005778 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005779}
5780
John Zulauf4edde622021-02-15 08:54:50 -07005781bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5782 VkPipelineStageFlags2KHR stageMask) const {
5783 bool skip = false;
5784 const auto *cb_context = GetAccessContext(commandBuffer);
5785 assert(cb_context);
5786 if (!cb_context) return skip;
5787
5788 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5789 return reset_event_op.Validate(*cb_context);
5790}
5791
Tony-LunarGa2662db2021-11-16 07:26:24 -07005792bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5793 VkPipelineStageFlags2 stageMask) const {
5794 bool skip = false;
5795 const auto *cb_context = GetAccessContext(commandBuffer);
5796 assert(cb_context);
5797 if (!cb_context) return skip;
5798
5799 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5800 return reset_event_op.Validate(*cb_context);
5801}
5802
John Zulauf4edde622021-02-15 08:54:50 -07005803void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5804 VkPipelineStageFlags2KHR stageMask) {
5805 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5806 auto *cb_context = GetAccessContext(commandBuffer);
5807 assert(cb_context);
5808 if (!cb_context) return;
5809
John Zulauf1bf30522021-09-03 15:39:06 -06005810 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005811}
5812
Tony-LunarGa2662db2021-11-16 07:26:24 -07005813void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5814 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5815 auto *cb_context = GetAccessContext(commandBuffer);
5816 assert(cb_context);
5817 if (!cb_context) return;
5818
5819 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5820}
5821
John Zulauf49beb112020-11-04 16:06:31 -07005822bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5823 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5824 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5825 uint32_t bufferMemoryBarrierCount,
5826 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5827 uint32_t imageMemoryBarrierCount,
5828 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5829 bool skip = false;
5830 const auto *cb_context = GetAccessContext(commandBuffer);
5831 assert(cb_context);
5832 if (!cb_context) return skip;
5833
John Zulauf36ef9282021-02-02 11:47:24 -07005834 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5835 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5836 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005837 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005838}
5839
5840void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5841 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5842 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5843 uint32_t bufferMemoryBarrierCount,
5844 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5845 uint32_t imageMemoryBarrierCount,
5846 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5847 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5848 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5849 imageMemoryBarrierCount, pImageMemoryBarriers);
5850
5851 auto *cb_context = GetAccessContext(commandBuffer);
5852 assert(cb_context);
5853 if (!cb_context) return;
5854
John Zulauf1bf30522021-09-03 15:39:06 -06005855 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06005856 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06005857 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07005858}
5859
John Zulauf4edde622021-02-15 08:54:50 -07005860bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5861 const VkDependencyInfoKHR *pDependencyInfos) const {
5862 bool skip = false;
5863 const auto *cb_context = GetAccessContext(commandBuffer);
5864 assert(cb_context);
5865 if (!cb_context) return skip;
5866
5867 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5868 skip |= wait_events_op.Validate(*cb_context);
5869 return skip;
5870}
5871
5872void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5873 const VkDependencyInfoKHR *pDependencyInfos) {
5874 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5875
5876 auto *cb_context = GetAccessContext(commandBuffer);
5877 assert(cb_context);
5878 if (!cb_context) return;
5879
John Zulauf1bf30522021-09-03 15:39:06 -06005880 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5881 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07005882}
5883
Tony-LunarG1364cf52021-11-17 16:10:11 -07005884bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5885 const VkDependencyInfo *pDependencyInfos) const {
5886 bool skip = false;
5887 const auto *cb_context = GetAccessContext(commandBuffer);
5888 assert(cb_context);
5889 if (!cb_context) return skip;
5890
5891 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5892 skip |= wait_events_op.Validate(*cb_context);
5893 return skip;
5894}
5895
5896void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5897 const VkDependencyInfo *pDependencyInfos) {
5898 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5899
5900 auto *cb_context = GetAccessContext(commandBuffer);
5901 assert(cb_context);
5902 if (!cb_context) return;
5903
5904 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5905 pDependencyInfos);
5906}
5907
John Zulauf4a6105a2020-11-17 15:11:05 -07005908void SyncEventState::ResetFirstScope() {
5909 for (const auto address_type : kAddressTypes) {
5910 first_scope[static_cast<size_t>(address_type)].clear();
5911 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005912 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06005913 first_scope_set = false;
5914 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07005915}
5916
5917// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09005918SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005919 IgnoreReason reason = NotIgnored;
5920
sjfricke0bea06e2022-06-05 09:22:26 +09005921 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07005922 reason = SetVsWait2;
5923 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
5924 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07005925 } else if (unsynchronized_set) {
5926 reason = SetRace;
John Zulauf78b1f892021-09-20 15:02:09 -06005927 } else if (first_scope_set) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005928 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005929 if (missing_bits) reason = MissingStageBits;
5930 }
5931
5932 return reason;
5933}
5934
Jeremy Gebben40a22942020-12-22 14:22:06 -07005935bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005936 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5937 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5938 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005939}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005940
John Zulaufbb890452021-12-14 11:30:18 -07005941void SyncOpBase::SetReplayContext(uint32_t subpass, ReplayContextPtr &&replay) {
5942 subpass_ = subpass;
5943 replay_context_ = std::move(replay);
5944}
5945
5946const ReplayTrackbackBarriersAction *SyncOpBase::GetReplayTrackback() const {
5947 if (replay_context_) {
5948 assert(subpass_ < replay_context_->subpass_contexts.size());
5949 return &replay_context_->subpass_contexts[subpass_];
5950 }
5951 return nullptr;
5952}
5953
sjfricke0bea06e2022-06-05 09:22:26 +09005954SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07005955 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5956 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07005957 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5958 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5959 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09005960 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07005961 auto &barrier_set = barriers_[0];
5962 barrier_set.dependency_flags = dependencyFlags;
5963 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
5964 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005965 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07005966 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
5967 pMemoryBarriers);
5968 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5969 bufferMemoryBarrierCount, pBufferMemoryBarriers);
5970 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5971 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005972}
5973
sjfricke0bea06e2022-06-05 09:22:26 +09005974SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07005975 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09005976 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07005977 for (uint32_t i = 0; i < event_count; i++) {
5978 const auto &dep_info = dep_infos[i];
5979 auto &barrier_set = barriers_[i];
5980 barrier_set.dependency_flags = dep_info.dependencyFlags;
5981 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
5982 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
5983 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
5984 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5985 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
5986 dep_info.pMemoryBarriers);
5987 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
5988 dep_info.pBufferMemoryBarriers);
5989 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
5990 dep_info.pImageMemoryBarriers);
5991 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005992}
5993
sjfricke0bea06e2022-06-05 09:22:26 +09005994SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07005995 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5996 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5997 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5998 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5999 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006000 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6001 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6002 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006003
sjfricke0bea06e2022-06-05 09:22:26 +09006004SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006005 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006006 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006007
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006008bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6009 bool skip = false;
6010 const auto *context = cb_context.GetCurrentAccessContext();
6011 assert(context);
6012 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006013 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6014
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006015 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006016 const auto &barrier_set = barriers_[0];
6017 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6018 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6019 const auto *image_state = image_barrier.image.get();
6020 if (!image_state) continue;
6021 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6022 if (hazard.hazard) {
6023 // PHASE1 TODO -- add tag information to log msg when useful.
6024 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006025 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006026 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6027 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6028 string_SyncHazard(hazard.hazard), image_barrier.index,
6029 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006030 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006031 }
6032 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006033 return skip;
6034}
6035
John Zulaufd5115702021-01-18 12:34:33 -07006036struct SyncOpPipelineBarrierFunctorFactory {
6037 using BarrierOpFunctor = PipelineBarrierOp;
6038 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6039 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6040 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6041 using BufferRange = ResourceAccessRange;
6042 using ImageRange = subresource_adapter::ImageRangeGenerator;
6043 using GlobalRange = ResourceAccessRange;
6044
John Zulauf00119522022-05-23 19:07:42 -06006045 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6046 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006047 }
John Zulauf14940722021-04-12 15:19:02 -06006048 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006049 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6050 }
John Zulauf00119522022-05-23 19:07:42 -06006051 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6052 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006053 }
6054
6055 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6056 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6057 const auto base_address = ResourceBaseAddress(buffer);
6058 return (range + base_address);
6059 }
John Zulauf110413c2021-03-20 05:38:38 -06006060 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006061 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006062
6063 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006064 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006065 return range_gen;
6066 }
6067 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6068};
6069
6070template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006071void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6072 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006073 for (const auto &barrier : barriers) {
6074 const auto *state = barrier.GetState();
6075 if (state) {
6076 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006077 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006078 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6079 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6080 }
6081 }
6082}
6083
6084template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006085void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6086 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006087 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6088 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006089 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006090 }
6091 for (const auto address_type : kAddressTypes) {
6092 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6093 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6094 }
6095}
6096
John Zulauf8eda1562021-04-13 17:06:41 -06006097ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006098 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf8eda1562021-04-13 17:06:41 -06006099 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006100 const QueueId queue_id = cb_context->GetQueueId();
sjfricke0bea06e2022-06-05 09:22:26 +09006101 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf00119522022-05-23 19:07:42 -06006102 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006103 return tag;
6104}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006105
John Zulauf00119522022-05-23 19:07:42 -06006106void SyncOpPipelineBarrier::ReplayRecord(QueueId queue_id, const ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006107 SyncEventsContext *events_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006108 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006109 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6110 assert(barriers_.size() == 1);
6111 const auto &barrier_set = barriers_[0];
John Zulauf00119522022-05-23 19:07:42 -06006112 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6113 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6114 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006115 if (barrier_set.single_exec_scope) {
John Zulauf8eda1562021-04-13 17:06:41 -06006116 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006117 } else {
6118 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulauf8eda1562021-04-13 17:06:41 -06006119 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006120 }
6121 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006122}
6123
John Zulauf8eda1562021-04-13 17:06:41 -06006124bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006125 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006126 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6127 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006128 return false;
6129}
6130
John Zulauf4edde622021-02-15 08:54:50 -07006131void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6132 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6133 const VkMemoryBarrier *barriers) {
6134 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006135 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006136 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006137 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006138 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006139 }
6140 if (0 == memory_barrier_count) {
6141 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006142 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006143 }
John Zulauf4edde622021-02-15 08:54:50 -07006144 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006145}
6146
John Zulauf4edde622021-02-15 08:54:50 -07006147void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6148 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6149 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6150 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006151 for (uint32_t index = 0; index < barrier_count; index++) {
6152 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006153 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006154 if (buffer) {
6155 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6156 const auto range = MakeRange(barrier.offset, barrier_size);
6157 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006158 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006159 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006160 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006161 }
6162 }
6163}
6164
John Zulauf4edde622021-02-15 08:54:50 -07006165void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006166 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006167 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006168 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006169 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006170 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6171 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6172 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006173 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006174 }
John Zulauf4edde622021-02-15 08:54:50 -07006175 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006176}
6177
John Zulauf4edde622021-02-15 08:54:50 -07006178void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6179 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006180 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006181 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006182 for (uint32_t index = 0; index < barrier_count; index++) {
6183 const auto &barrier = barriers[index];
6184 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6185 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006186 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006187 if (buffer) {
6188 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6189 const auto range = MakeRange(barrier.offset, barrier_size);
6190 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006191 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006192 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006193 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006194 }
6195 }
6196}
6197
John Zulauf4edde622021-02-15 08:54:50 -07006198void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6199 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6200 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6201 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006202 for (uint32_t index = 0; index < barrier_count; index++) {
6203 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006204 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006205 if (image) {
6206 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6207 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006208 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006209 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006210 image_memory_barriers.emplace_back();
6211 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006212 }
6213 }
6214}
John Zulaufd5115702021-01-18 12:34:33 -07006215
John Zulauf4edde622021-02-15 08:54:50 -07006216void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6217 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006218 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006219 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006220 for (uint32_t index = 0; index < barrier_count; index++) {
6221 const auto &barrier = barriers[index];
6222 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6223 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006224 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006225 if (image) {
6226 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6227 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006228 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006229 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006230 image_memory_barriers.emplace_back();
6231 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006232 }
6233 }
6234}
6235
sjfricke0bea06e2022-06-05 09:22:26 +09006236SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6237 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6238 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6239 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6240 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6241 const VkImageMemoryBarrier *pImageMemoryBarriers)
6242 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006243 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6244 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006245 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006246}
6247
sjfricke0bea06e2022-06-05 09:22:26 +09006248SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6249 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6250 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006251 MakeEventsList(sync_state, eventCount, pEvents);
6252 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6253}
6254
John Zulauf610e28c2021-08-03 17:46:23 -06006255const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6256
John Zulaufd5115702021-01-18 12:34:33 -07006257bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006258 bool skip = false;
6259 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006260 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006261
John Zulauf610e28c2021-08-03 17:46:23 -06006262 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006263 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6264 const auto &barrier_set = barriers_[barrier_set_index];
6265 if (barrier_set.single_exec_scope) {
6266 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6267 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6268 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6269 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6270 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6271 } else {
6272 const auto &barriers = barrier_set.memory_barriers;
6273 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6274 const auto &barrier = barriers[barrier_index];
6275 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6276 const std::string vuid =
6277 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6278 skip =
6279 sync_state.LogInfo(command_buffer_handle, vuid,
6280 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6281 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6282 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6283 }
6284 }
6285 }
6286 }
John Zulaufd5115702021-01-18 12:34:33 -07006287 }
6288
John Zulauf610e28c2021-08-03 17:46:23 -06006289 // The rest is common to record time and replay time.
6290 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6291 return skip;
6292}
6293
John Zulaufbb890452021-12-14 11:30:18 -07006294bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006295 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006296 const auto &sync_state = exec_context.GetSyncState();
John Zulauf610e28c2021-08-03 17:46:23 -06006297
Jeremy Gebben40a22942020-12-22 14:22:06 -07006298 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006299 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006300 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006301 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006302 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006303 size_t barrier_set_index = 0;
6304 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006305 for (const auto &event : events_) {
6306 const auto *sync_event = events_context->Get(event.get());
6307 const auto &barrier_set = barriers_[barrier_set_index];
6308 if (!sync_event) {
6309 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6310 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6311 // new validation error... wait without previously submitted set event...
6312 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 -07006313 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006314 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006315 }
John Zulauf610e28c2021-08-03 17:46:23 -06006316
6317 // For replay calls, don't revalidate "same command buffer" events
6318 if (sync_event->last_command_tag > base_tag) continue;
6319
John Zulauf78394fc2021-07-12 15:41:40 -06006320 const auto event_handle = sync_event->event->event();
6321 // TODO add "destroyed" checks
6322
John Zulauf78b1f892021-09-20 15:02:09 -06006323 if (sync_event->first_scope_set) {
6324 // Only accumulate barrier and event stages if there is a pending set in the current context
6325 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6326 event_stage_masks |= sync_event->scope.mask_param;
6327 }
6328
John Zulauf78394fc2021-07-12 15:41:40 -06006329 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006330
sjfricke0bea06e2022-06-05 09:22:26 +09006331 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006332 if (ignore_reason) {
6333 switch (ignore_reason) {
6334 case SyncEventState::ResetWaitRace:
6335 case SyncEventState::Reset2WaitRace: {
6336 // Four permuations of Reset and Wait calls...
6337 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006338 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006339 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006340 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6341 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006342 }
6343 const char *const message =
6344 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6345 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6346 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006347 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006348 break;
6349 }
6350 case SyncEventState::SetRace: {
6351 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6352 // this event
6353 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6354 const char *const message =
6355 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6356 const char *const reason = "First synchronization scope is undefined.";
6357 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6358 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006359 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006360 break;
6361 }
6362 case SyncEventState::MissingStageBits: {
6363 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6364 // Issue error message that event waited for is not in wait events scope
6365 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6366 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6367 ". Bits missing from srcStageMask %s. %s";
6368 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6369 sync_state.report_data->FormatHandle(event_handle).c_str(),
6370 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006371 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006372 break;
6373 }
6374 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006375 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006376 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6377 sync_state.report_data->FormatHandle(event_handle).c_str(),
6378 CommandTypeString(sync_event->last_command));
6379 break;
6380 }
6381 default:
6382 assert(ignore_reason == SyncEventState::NotIgnored);
6383 }
6384 } else if (barrier_set.image_memory_barriers.size()) {
6385 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006386 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006387 assert(context);
6388 for (const auto &image_memory_barrier : image_memory_barriers) {
6389 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6390 const auto *image_state = image_memory_barrier.image.get();
6391 if (!image_state) continue;
6392 const auto &subresource_range = image_memory_barrier.range;
6393 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
6394 const auto hazard =
6395 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
6396 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
6397 if (hazard.hazard) {
6398 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6399 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6400 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6401 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006402 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006403 break;
6404 }
6405 }
6406 }
6407 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6408 // 03839
6409 barrier_set_index += barrier_set_incr;
6410 }
John Zulaufd5115702021-01-18 12:34:33 -07006411
6412 // 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 -07006413 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 -07006414 if (extra_stage_bits) {
6415 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006416 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6417 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006418 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006419 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006420 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006421 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006422 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006423 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006424 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006425 " vkCmdSetEvent may be in previously submitted command buffer.");
6426 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006427 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006428 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006429 }
6430 }
6431 return skip;
6432}
6433
6434struct SyncOpWaitEventsFunctorFactory {
6435 using BarrierOpFunctor = WaitEventBarrierOp;
6436 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6437 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6438 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6439 using BufferRange = EventSimpleRangeGenerator;
6440 using ImageRange = EventImageRangeGenerator;
6441 using GlobalRange = EventSimpleRangeGenerator;
6442
6443 // Need to restrict to only valid exec and access scope for this event
6444 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6445 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006446 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006447 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6448 return barrier;
6449 }
John Zulauf00119522022-05-23 19:07:42 -06006450 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006451 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006452 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006453 }
John Zulauf14940722021-04-12 15:19:02 -06006454 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006455 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6456 }
John Zulauf00119522022-05-23 19:07:42 -06006457 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006458 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006459 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006460 }
6461
6462 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6463 const AccessAddressType address_type = GetAccessAddressType(buffer);
6464 const auto base_address = ResourceBaseAddress(buffer);
6465 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6466 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6467 return filtered_range_gen;
6468 }
John Zulauf110413c2021-03-20 05:38:38 -06006469 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006470 if (!SimpleBinding(image)) return ImageRange();
6471 const auto address_type = GetAccessAddressType(image);
6472 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006473 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6474 false);
John Zulaufd5115702021-01-18 12:34:33 -07006475 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6476
6477 return filtered_range_gen;
6478 }
6479 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6480 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6481 }
6482 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6483 SyncEventState *sync_event;
6484};
6485
John Zulauf8eda1562021-04-13 17:06:41 -06006486ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006487 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006488 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006489 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufd5115702021-01-18 12:34:33 -07006490 assert(access_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006491 if (!access_context) return tag;
John Zulauf669dfd52021-01-27 17:15:28 -07006492 auto *events_context = cb_context->GetCurrentEventsContext();
6493 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006494 if (!events_context) return tag;
John Zulaufd5115702021-01-18 12:34:33 -07006495
John Zulauf00119522022-05-23 19:07:42 -06006496 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006497 return tag;
6498}
6499
John Zulauf00119522022-05-23 19:07:42 -06006500void SyncOpWaitEvents::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6501 SyncEventsContext *events_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006502 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6503 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6504 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
6505 access_context->ResolvePreviousAccesses();
6506
John Zulauf4edde622021-02-15 08:54:50 -07006507 size_t barrier_set_index = 0;
6508 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6509 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006510 for (auto &event_shared : events_) {
6511 if (!event_shared.get()) continue;
6512 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006513
sjfricke0bea06e2022-06-05 09:22:26 +09006514 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006515 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006516
John Zulauf4edde622021-02-15 08:54:50 -07006517 const auto &barrier_set = barriers_[barrier_set_index];
6518 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006519 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006520 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6521 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6522 // of the barriers is maintained.
6523 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006524 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6525 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6526 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006527
6528 // Apply the global barrier to the event itself (for race condition tracking)
6529 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6530 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6531 sync_event->barriers |= dst.exec_scope;
6532 } else {
6533 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6534 sync_event->barriers = 0U;
6535 }
John Zulauf4edde622021-02-15 08:54:50 -07006536 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006537 }
6538
6539 // Apply the pending barriers
6540 ResolvePendingBarrierFunctor apply_pending_action(tag);
6541 access_context->ApplyToContext(apply_pending_action);
6542}
6543
John Zulauf8eda1562021-04-13 17:06:41 -06006544bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006545 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6546 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006547}
6548
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006549bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6550 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6551 bool skip = false;
6552 const auto *cb_access_context = GetAccessContext(commandBuffer);
6553 assert(cb_access_context);
6554 if (!cb_access_context) return skip;
6555
6556 const auto *context = cb_access_context->GetCurrentAccessContext();
6557 assert(context);
6558 if (!context) return skip;
6559
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006560 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006561
6562 if (dst_buffer) {
6563 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6564 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6565 if (hazard.hazard) {
6566 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6567 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6568 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006569 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006570 }
6571 }
6572 return skip;
6573}
6574
John Zulauf669dfd52021-01-27 17:15:28 -07006575void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006576 events_.reserve(event_count);
6577 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006578 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006579 }
6580}
John Zulauf6ce24372021-01-30 05:56:25 -07006581
sjfricke0bea06e2022-06-05 09:22:26 +09006582SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006583 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006584 : SyncOpBase(cmd_type),
6585 event_(sync_state.Get<EVENT_STATE>(event)),
6586 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006587
John Zulauf1bf30522021-09-03 15:39:06 -06006588bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6589 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6590}
6591
John Zulaufbb890452021-12-14 11:30:18 -07006592bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6593 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006594 assert(events_context);
6595 bool skip = false;
6596 if (!events_context) return skip;
6597
John Zulaufbb890452021-12-14 11:30:18 -07006598 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006599 const auto *sync_event = events_context->Get(event_);
6600 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6601
John Zulauf1bf30522021-09-03 15:39:06 -06006602 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6603
John Zulauf6ce24372021-01-30 05:56:25 -07006604 const char *const set_wait =
6605 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6606 "hazards.";
6607 const char *message = set_wait; // Only one message this call.
6608 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6609 const char *vuid = nullptr;
6610 switch (sync_event->last_command) {
6611 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006612 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006613 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006614 // Needs a barrier between set and reset
6615 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6616 break;
John Zulauf4edde622021-02-15 08:54:50 -07006617 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006618 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006619 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006620 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6621 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6622 break;
6623 }
6624 default:
6625 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006626 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6627 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006628 break;
6629 }
6630 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006631 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6632 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006633 CommandTypeString(sync_event->last_command));
6634 }
6635 }
6636 return skip;
6637}
6638
John Zulauf8eda1562021-04-13 17:06:41 -06006639ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006640 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006641 auto *events_context = cb_context->GetCurrentEventsContext();
6642 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006643 if (!events_context) return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006644
6645 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf8eda1562021-04-13 17:06:41 -06006646 if (!sync_event) return tag; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006647
6648 // Update the event state
sjfricke0bea06e2022-06-05 09:22:26 +09006649 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006650 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006651 sync_event->unsynchronized_set = CMD_NONE;
6652 sync_event->ResetFirstScope();
6653 sync_event->barriers = 0U;
John Zulauf8eda1562021-04-13 17:06:41 -06006654
6655 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006656}
6657
John Zulauf8eda1562021-04-13 17:06:41 -06006658bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006659 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6660 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006661}
6662
John Zulauf00119522022-05-23 19:07:42 -06006663void SyncOpResetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6664 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006665
sjfricke0bea06e2022-06-05 09:22:26 +09006666SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006667 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006668 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006669 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulauf4edde622021-02-15 08:54:50 -07006670 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
6671 dep_info_() {}
6672
sjfricke0bea06e2022-06-05 09:22:26 +09006673SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006674 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006675 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006676 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulauf4edde622021-02-15 08:54:50 -07006677 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
Tony-LunarG273f32f2021-09-28 08:56:30 -06006678 dep_info_(new safe_VkDependencyInfo(&dep_info)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006679
6680bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006681 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6682}
6683bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006684 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6685 assert(exec_context);
6686 return DoValidate(*exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006687}
6688
John Zulaufbb890452021-12-14 11:30:18 -07006689bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006690 bool skip = false;
6691
John Zulaufbb890452021-12-14 11:30:18 -07006692 const auto &sync_state = exec_context.GetSyncState();
6693 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006694 assert(events_context);
6695 if (!events_context) return skip;
6696
6697 const auto *sync_event = events_context->Get(event_);
6698 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6699
John Zulauf610e28c2021-08-03 17:46:23 -06006700 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6701
John Zulauf6ce24372021-01-30 05:56:25 -07006702 const char *const reset_set =
6703 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6704 "hazards.";
6705 const char *const wait =
6706 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6707
6708 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006709 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006710 const char *message = nullptr;
6711 switch (sync_event->last_command) {
6712 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006713 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006714 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006715 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006716 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006717 message = reset_set;
6718 break;
6719 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006720 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006721 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006722 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006723 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006724 message = reset_set;
6725 break;
6726 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006727 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006728 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006729 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006730 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006731 message = wait;
6732 break;
6733 default:
6734 // The only other valid last command that wasn't one.
6735 assert(sync_event->last_command == CMD_NONE);
6736 break;
6737 }
John Zulauf4edde622021-02-15 08:54:50 -07006738 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006739 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006740 std::string vuid("SYNC-");
6741 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006742 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6743 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006744 CommandTypeString(sync_event->last_command));
6745 }
6746 }
6747
6748 return skip;
6749}
6750
John Zulauf8eda1562021-04-13 17:06:41 -06006751ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006752 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006753 auto *events_context = cb_context->GetCurrentEventsContext();
6754 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006755 const QueueId queue_id = cb_context->GetQueueId();
John Zulauf6ce24372021-01-30 05:56:25 -07006756 assert(events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006757 if (access_context && events_context) {
John Zulauf00119522022-05-23 19:07:42 -06006758 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006759 }
6760 return tag;
6761}
John Zulauf6ce24372021-01-30 05:56:25 -07006762
John Zulauf00119522022-05-23 19:07:42 -06006763void SyncOpSetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6764 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006765 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006766 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006767
6768 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6769 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6770 // any issues caused by naive scope setting here.
6771
6772 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6773 // Given:
6774 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6775 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6776
6777 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6778 sync_event->unsynchronized_set = sync_event->last_command;
6779 sync_event->ResetFirstScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006780 } else if (!sync_event->first_scope_set) {
John Zulauf6ce24372021-01-30 05:56:25 -07006781 // We only set the scope if there isn't one
6782 sync_event->scope = src_exec_scope_;
6783
6784 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
6785 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
6786 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
6787 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
6788 }
6789 };
6790 access_context->ForAll(set_scope);
6791 sync_event->unsynchronized_set = CMD_NONE;
John Zulauf78b1f892021-09-20 15:02:09 -06006792 sync_event->first_scope_set = true;
John Zulauf6ce24372021-01-30 05:56:25 -07006793 sync_event->first_scope_tag = tag;
6794 }
John Zulauf4edde622021-02-15 08:54:50 -07006795 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09006796 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006797 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006798 sync_event->barriers = 0U;
6799}
John Zulauf64ffe552021-02-06 10:25:07 -07006800
sjfricke0bea06e2022-06-05 09:22:26 +09006801SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07006802 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006803 const VkSubpassBeginInfo *pSubpassBeginInfo)
sjfricke0bea06e2022-06-05 09:22:26 +09006804 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07006805 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006806 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006807 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006808 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006809 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006810 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006811 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6812 // Note that this a safe to presist as long as shared_attachments is not cleared
6813 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006814 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006815 attachments_.emplace_back(attachment.get());
6816 }
6817 }
6818 if (pSubpassBeginInfo) {
6819 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6820 }
6821 }
6822}
6823
6824bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6825 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6826 bool skip = false;
6827
6828 assert(rp_state_.get());
6829 if (nullptr == rp_state_.get()) return skip;
6830 auto &rp_state = *rp_state_.get();
6831
6832 const uint32_t subpass = 0;
6833
6834 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
6835 // hasn't happened yet)
6836 const std::vector<AccessContext> empty_context_vector;
6837 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
6838 cb_context.GetCurrentAccessContext());
6839
6840 // Validate attachment operations
6841 if (attachments_.size() == 0) return skip;
6842 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07006843
6844 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
6845 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
6846 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
6847 // operations (though it's currently a messy approach)
6848 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09006849 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006850
6851 // Validate load operations if there were no layout transition hazards
6852 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06006853 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09006854 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006855 }
6856
6857 return skip;
6858}
6859
John Zulauf8eda1562021-04-13 17:06:41 -06006860ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf64ffe552021-02-06 10:25:07 -07006861 // TODO PHASE2 need to have a consistent way to record to either command buffer or queue contexts
6862 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09006863 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
6864 return cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
John Zulauf64ffe552021-02-06 10:25:07 -07006865}
6866
John Zulauf8eda1562021-04-13 17:06:41 -06006867bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006868 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006869 return false;
6870}
6871
John Zulauf00119522022-05-23 19:07:42 -06006872void SyncOpBeginRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006873 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006874
sjfricke0bea06e2022-06-05 09:22:26 +09006875SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
6876 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
6877 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07006878 if (pSubpassBeginInfo) {
6879 subpass_begin_info_.initialize(pSubpassBeginInfo);
6880 }
6881 if (pSubpassEndInfo) {
6882 subpass_end_info_.initialize(pSubpassEndInfo);
6883 }
6884}
6885
6886bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
6887 bool skip = false;
6888 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6889 if (!renderpass_context) return skip;
6890
sjfricke0bea06e2022-06-05 09:22:26 +09006891 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006892 return skip;
6893}
6894
John Zulauf8eda1562021-04-13 17:06:41 -06006895ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006896 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06006897}
6898
6899bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006900 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006901 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07006902}
6903
sjfricke0bea06e2022-06-05 09:22:26 +09006904SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
6905 const VkSubpassEndInfo *pSubpassEndInfo)
6906 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07006907 if (pSubpassEndInfo) {
6908 subpass_end_info_.initialize(pSubpassEndInfo);
6909 }
6910}
6911
John Zulauf00119522022-05-23 19:07:42 -06006912void SyncOpNextSubpass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6913 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006914
John Zulauf64ffe552021-02-06 10:25:07 -07006915bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6916 bool skip = false;
6917 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6918
6919 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09006920 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006921 return skip;
6922}
6923
John Zulauf8eda1562021-04-13 17:06:41 -06006924ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006925 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006926}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006927
John Zulauf8eda1562021-04-13 17:06:41 -06006928bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006929 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006930 return false;
6931}
6932
John Zulauf00119522022-05-23 19:07:42 -06006933void SyncOpEndRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006934 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006935
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006936void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6937 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
6938 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
6939 auto *cb_access_context = GetAccessContext(commandBuffer);
6940 assert(cb_access_context);
6941 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
6942 auto *context = cb_access_context->GetCurrentAccessContext();
6943 assert(context);
6944
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006945 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006946
6947 if (dst_buffer) {
6948 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6949 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
6950 }
6951}
John Zulaufd05c5842021-03-26 11:32:16 -06006952
John Zulaufae842002021-04-15 18:20:55 -06006953bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6954 const VkCommandBuffer *pCommandBuffers) const {
6955 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06006956 const auto *cb_context = GetAccessContext(commandBuffer);
6957 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006958
6959 // Heavyweight, but we need a proxy copy of the active command buffer access context
6960 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06006961
6962 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06006963 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006964 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
6965
John Zulaufae842002021-04-15 18:20:55 -06006966 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6967 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06006968
6969 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
6970 assert(recorded_context);
sjfricke0bea06e2022-06-05 09:22:26 +09006971 skip |= recorded_cb_context->ValidateFirstUse(&proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06006972
6973 // The barriers have already been applied in ValidatFirstUse
6974 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06006975 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06006976 }
6977
John Zulaufae842002021-04-15 18:20:55 -06006978 return skip;
6979}
6980
6981void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6982 const VkCommandBuffer *pCommandBuffers) {
6983 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06006984 auto *cb_context = GetAccessContext(commandBuffer);
6985 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006986 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006987 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06006988 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6989 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09006990 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006991 }
John Zulaufae842002021-04-15 18:20:55 -06006992}
6993
John Zulauf1d5f9c12022-05-13 14:51:08 -06006994void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
6995 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
6996 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
6997
6998 const auto queue_state = GetQueueSyncStateShared(queue);
6999 if (!queue_state) return; // Invalid queue
7000 QueueId waited_queue = queue_state->GetQueueId();
7001
7002 // We need to go through every queue batch context and clear all accesses this wait synchronizes
7003 // As usual -- two groups, the "last batch" and the signaled semaphores
7004 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
7005 // QueueBatchContext, track which we've done to avoid duplicate traversals
7006 QueueBatchContext::BatchSet waited;
7007 for (auto &queue : queue_sync_states_) {
7008 auto batch = queue.second->LastBatch();
7009 if (batch) {
7010 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
7011 waited.emplace(batch);
7012 }
7013 }
7014
7015 for (const auto &signaled : signaled_semaphores_) {
7016 auto &sem_sig = signaled.second;
7017 if (sem_sig && sem_sig->batch && (waited.find(sem_sig->batch) == waited.end())) {
7018 sem_sig->batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
7019 waited.emplace(sem_sig->batch);
7020 }
7021 }
7022 // TODO: Update Events and Fences affected by Wait
7023}
7024
7025void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7026 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
7027 for (auto &queue : queue_sync_states_) {
7028 auto batch = queue.second->LastBatch();
7029 if (batch) {
7030 batch->ApplyDeviceWait();
7031 }
7032 }
7033
7034 auto wait_no_list = [](std::shared_ptr<QueueBatchContext> &batch) {
7035 batch->ApplyDeviceWait();
7036 return false;
7037 };
7038
7039 GetQueueLastBatchSnapshot(wait_no_list);
7040
7041 // TODO: Update Events and Fences affected by Wait
7042}
7043
John Zulauf697c0e12022-04-19 16:31:12 -06007044struct QueueSubmitCmdState {
7045 std::shared_ptr<const QueueSyncState> queue;
7046 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007047 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007048 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007049 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7050 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007051};
7052
7053template <>
7054thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7055
John Zulaufbbda4572022-04-19 16:20:45 -06007056bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7057 VkFence fence) const {
7058 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007059
7060 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007061 if (!enabled[sync_validation_queue_submit]) return skip;
7062
John Zulauf00119522022-05-23 19:07:42 -06007063 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007064 const auto fence_state = Get<FENCE_STATE>(fence);
7065 cmd_state->queue = GetQueueSyncStateShared(queue);
7066 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007067
John Zulauf697c0e12022-04-19 16:31:12 -06007068 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7069 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7070
7071 // verify each submit batch
7072 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7073 // most recently created batch
7074 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7075 std::shared_ptr<QueueBatchContext> batch;
7076 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7077 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007078 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7079 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007080 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
7081
7082 // For each submit in the batch...
7083 for (const auto &cb : *batch) {
sjfricke0bea06e2022-06-05 09:22:26 +09007084 skip |= cb.cb->ValidateFirstUse(batch.get(), "vkQueueSubmit", cb.index);
John Zulauf697c0e12022-04-19 16:31:12 -06007085
7086 // The barriers have already been applied in ValidatFirstUse
7087 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007088 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
John Zulauf697c0e12022-04-19 16:31:12 -06007089 }
7090
John Zulauf697c0e12022-04-19 16:31:12 -06007091 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7092 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007093 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007094 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007095 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7096 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7097 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007098 }
7099 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7100 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7101 last_batch = batch;
7102 }
7103 // The most recently created batch will become the queue's "last batch" in the record phase
7104 if (batch) {
7105 cmd_state->last_batch = std::move(batch);
7106 }
7107
7108 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007109 return skip;
7110}
7111
7112void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7113 VkResult result) {
7114 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007115
John Zulaufcb7e1672022-05-04 13:46:08 -06007116 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007117 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7118
John Zulaufcb7e1672022-05-04 13:46:08 -06007119 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7120 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007121 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007122
7123 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007124 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7125
John Zulauf697c0e12022-04-19 16:31:12 -06007126 // Don't need to look up the queue state again, but we need a non-const version
7127 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007128
John Zulaufcb7e1672022-05-04 13:46:08 -06007129 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7130 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7131 // QBC's are those referenced by unwaited signals and the last batch.
7132 for (auto &sig_sem : cmd_state->signaled) {
7133 if (sig_sem.second && sig_sem.second->batch) {
7134 sig_sem.second->batch->ResetAccessLog();
7135 }
7136 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007137 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007138 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007139
John Zulaufcb7e1672022-05-04 13:46:08 -06007140 // Update the queue to point to the last batch from the submit
7141 if (cmd_state->last_batch) {
7142 cmd_state->last_batch->ResetAccessLog();
7143 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007144 }
7145
7146 // Update the global access log from the one built during validation
7147 global_access_log_.MergeMove(std::move(cmd_state->logger));
7148
John Zulauf697c0e12022-04-19 16:31:12 -06007149
7150 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007151}
7152
7153bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7154 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007155 bool skip = false;
7156 if (!enabled[sync_validation_queue_submit]) return skip;
7157
John Zulauf697c0e12022-04-19 16:31:12 -06007158 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007159 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007160}
7161
7162void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7163 VkFence fence, VkResult result) {
7164 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007165 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7166
7167 if (!enabled[sync_validation_queue_submit]) return;
7168
John Zulauf697c0e12022-04-19 16:31:12 -06007169 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007170}
7171
John Zulaufd0ec59f2021-03-13 14:25:08 -07007172AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7173 : view_(view), view_mask_(), gen_store_() {
7174 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7175 const IMAGE_STATE &image_state = *view_->image_state.get();
7176 const auto base_address = ResourceBaseAddress(image_state);
7177 const auto *encoder = image_state.fragment_encoder.get();
7178 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007179 // Get offset and extent for the view, accounting for possible depth slicing
7180 const VkOffset3D zero_offset = view->GetOffset();
7181 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007182 // Intentional copy
7183 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7184 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007185 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7186 view->IsDepthSliced());
7187 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007188
7189 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7190 if (depth && (depth != view_mask_)) {
7191 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007192 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007193 }
7194 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7195 if (stencil && (stencil != view_mask_)) {
7196 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007197 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7198 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007199 }
7200}
7201
7202const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7203 const ImageRangeGen *got = nullptr;
7204 switch (gen_type) {
7205 case kViewSubresource:
7206 got = &gen_store_[kViewSubresource];
7207 break;
7208 case kRenderArea:
7209 got = &gen_store_[kRenderArea];
7210 break;
7211 case kDepthOnlyRenderArea:
7212 got =
7213 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7214 break;
7215 case kStencilOnlyRenderArea:
7216 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7217 : &gen_store_[Gen::kStencilOnlyRenderArea];
7218 break;
7219 default:
7220 assert(got);
7221 }
7222 return got;
7223}
7224
7225AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7226 assert(IsValid());
7227 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7228 if (depth_op) {
7229 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7230 if (stencil_op) {
7231 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7232 return kRenderArea;
7233 }
7234 return kDepthOnlyRenderArea;
7235 }
7236 if (stencil_op) {
7237 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7238 return kStencilOnlyRenderArea;
7239 }
7240
7241 assert(depth_op || stencil_op);
7242 return kRenderArea;
7243}
7244
7245AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007246
7247void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
7248 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7249 for (auto &event_pair : map_) {
7250 assert(event_pair.second); // Shouldn't be storing empty
7251 auto &sync_event = *event_pair.second;
7252 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
7253 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
7254 sync_event.barriers |= dst.exec_scope;
7255 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7256 }
7257 }
7258}
John Zulaufbb890452021-12-14 11:30:18 -07007259
7260ReplayTrackbackBarriersAction::ReplayTrackbackBarriersAction(VkQueueFlags queue_flags,
7261 const SubpassDependencyGraphNode &subpass_dep,
7262 const std::vector<ReplayTrackbackBarriersAction> &replay_contexts) {
7263 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
7264 trackback_barriers.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
7265 for (const auto &prev_dep : subpass_dep.prev) {
7266 const auto prev_pass = prev_dep.first->pass;
7267 const auto &prev_barriers = prev_dep.second;
7268 trackback_barriers.emplace_back(&replay_contexts[prev_pass], queue_flags, prev_barriers);
7269 }
7270 if (has_barrier_from_external) {
7271 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
7272 trackback_barriers.emplace_back(nullptr, queue_flags, subpass_dep.barrier_from_external);
7273 }
7274}
7275
7276void ReplayTrackbackBarriersAction::operator()(ResourceAccessState *access) const {
7277 if (trackback_barriers.size() == 1) {
7278 trackback_barriers[0](access);
7279 } else {
7280 ResourceAccessState resolved;
7281 for (const auto &trackback : trackback_barriers) {
7282 ResourceAccessState access_copy = *access;
7283 trackback(&access_copy);
7284 resolved.Resolve(access_copy);
7285 }
7286 *access = resolved;
7287 }
7288}
7289
7290ReplayTrackbackBarriersAction::TrackbackBarriers::TrackbackBarriers(
7291 const ReplayTrackbackBarriersAction *source_subpass_, VkQueueFlags queue_flags_,
7292 const std::vector<const VkSubpassDependency2 *> &subpass_dependencies_)
7293 : Base(source_subpass_, queue_flags_, subpass_dependencies_) {}
7294
7295void ReplayTrackbackBarriersAction::TrackbackBarriers::operator()(ResourceAccessState *access) const {
7296 if (source_subpass) {
7297 (*source_subpass)(access);
7298 }
7299 access->ApplyBarriersImmediate(barriers);
7300}
John Zulauf697c0e12022-04-19 16:31:12 -06007301
John Zulaufcb7e1672022-05-04 13:46:08 -06007302QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
7303 : CommandExecutionContext(&sync_state), queue_state_(&queue_state), tag_range_(0, 0), batch_log_(nullptr) {}
7304
John Zulauf697c0e12022-04-19 16:31:12 -06007305template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007306void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7307 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007308 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007309 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007310}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007311void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
7312 QueueId queue_id = queue_state_->GetQueueId();
7313 auto tag_queue_op = [offset, queue_id](ResourceAccessState *access) {
7314 access->OffsetTag(offset);
7315 access->SetQueueId(queue_id);
7316 };
7317 GetCurrentAccessContext()->ResolveFromContext(tag_queue_op, recorded_context);
7318}
John Zulauf697c0e12022-04-19 16:31:12 -06007319
7320VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7321
John Zulauf1d5f9c12022-05-13 14:51:08 -06007322void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7323 QueueWaitWorm wait_worm(queue_id);
7324 access_context_.ForAll(wait_worm);
7325 if (wait_worm.erase_all) {
7326 access_context_.Reset();
7327 } else {
7328 // TODO: Profiling will tell us if we need a more efficient clean up.
7329 for (const auto &address : wait_worm.erase_list) {
7330 access_context_.DeleteAccess(address);
7331 }
7332 }
7333}
7334
7335// Clear all accesses
7336void QueueBatchContext::ApplyDeviceWait() { access_context_.Reset(); }
7337
John Zulaufcb7e1672022-05-04 13:46:08 -06007338void QueueBatchContext::WaitOneSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask, WaitBatchMap &batch_trackbacks,
7339 SignaledSemaphores &signaled) {
7340 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
7341 if (!sem_state) return; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007342
John Zulaufcb7e1672022-05-04 13:46:08 -06007343 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7344 auto signal_state = signaled.Unsignal(sem);
7345 if (!signal_state) return; // Invalid signal, skip it.
7346
7347 const auto &sem_batch = signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007348 assert(sem_batch);
7349
7350 const AccessContext *sem_context = sem_batch->GetCurrentAccessContext();
7351
7352 using TrackBackPtr = AccessContext::TrackBack *;
John Zulaufcb7e1672022-05-04 13:46:08 -06007353 const auto trackback_insert = batch_trackbacks.emplace(sem_batch.get(), TrackBackPtr());
John Zulauf697c0e12022-04-19 16:31:12 -06007354 const bool inserted = trackback_insert.second;
7355 const auto trackback_it = trackback_insert.first;
7356
John Zulaufcb7e1672022-05-04 13:46:08 -06007357 const SyncExecScope &sem_scope = signal_state->exec_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007358 const auto queue_flags = queue_state_->GetQueueFlags();
7359 SyncExecScope dst_mask = SyncExecScope::MakeDst(queue_flags, wait_mask);
7360 const SyncBarrier sem_barrier(sem_scope, sem_scope.valid_accesses, dst_mask, SyncStageAccessFlags());
7361 if (inserted) {
7362 // If this is the first time we referenced this QueueBatchContext
7363 trackback_it->second = access_context_.AddTrackBack(sem_context, sem_barrier);
7364 }
7365 assert(trackback_it->second);
7366 trackback_it->second->barriers.emplace_back(sem_barrier);
7367}
7368
7369// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7370template <>
7371class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7372 public:
7373 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7374 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7375 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7376 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7377 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7378 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7379
7380 private:
7381 const VkSubmitInfo &info_;
7382};
7383template <typename BatchInfo, typename Fn>
7384void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7385 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7386 Accessor batch(batch_info);
7387 const uint32_t wait_count = batch.WaitSemaphoreCount();
7388 for (uint32_t i = 0; i < wait_count; ++i) {
7389 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7390 }
7391}
7392
7393template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007394void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7395 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007396 // Create trackbacks for the access context for this batch based on the semaphores and the previous batch in this
7397 // queue.
7398 WaitBatchMap batch_trackbacks;
John Zulaufcb7e1672022-05-04 13:46:08 -06007399 ForEachWaitSemaphore(batch_info, [this, &batch_trackbacks, &signaled](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7400 WaitOneSemaphore(sem, wait_mask, batch_trackbacks, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007401 });
7402
John Zulauf78cb2082022-04-20 16:37:48 -06007403 // If there are no semaphores to the previous batch, make sure a "submit order" empty trackback is added
7404 if (prev && (batch_trackbacks.find(prev.get()) == batch_trackbacks.end())) {
7405 access_context_.AddTrackBack(prev->GetCurrentAccessContext(), SyncBarrier());
7406 }
7407
John Zulauf697c0e12022-04-19 16:31:12 -06007408 // Flatten all previous contexts into the current one (for dependency chaining reasons)
7409 access_context_.ResolvePreviousAccesses();
7410 access_context_.ClearTrackBacks();
7411
7412 // Gather async context information for hazard checks and conserve the QBC's for the async batches
7413 const auto end_it = batch_trackbacks.end();
John Zulauf78cb2082022-04-20 16:37:48 -06007414 async_batches_ = sync_state_->GetQueueLastBatchSnapshot(
7415 [&batch_trackbacks, end_it, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
John Zulauf697c0e12022-04-19 16:31:12 -06007416 const auto found_it = batch_trackbacks.find(batch.get());
John Zulauf78cb2082022-04-20 16:37:48 -06007417 return found_it == end_it && (batch != prev);
John Zulauf697c0e12022-04-19 16:31:12 -06007418 });
7419 for (const auto &async_batch : async_batches_) {
7420 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7421 }
7422}
7423
7424template <typename BatchInfo>
7425void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7426 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7427 Accessor batch(batch_info);
7428
7429 // Create the list of command buffers to submit
7430 const uint32_t cb_count = batch.CommandBufferCount();
7431 command_buffers_.reserve(cb_count);
7432 for (uint32_t index = 0; index < cb_count; ++index) {
7433 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7434 if (cb_context) {
7435 tag_range_.end += cb_context->GetTagLimit();
7436 command_buffers_.emplace_back(index, std::move(cb_context));
7437 }
7438 }
7439}
7440
7441// Look up the usage informaiton from the local or global logger
7442std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7443 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7444 std::stringstream out;
7445 AccessLogger::AccessRecord access = use_logger[tag];
7446 if (access.IsValid()) {
7447 const AccessLogger::BatchRecord &batch = *access.batch;
7448 const ResourceUsageRecord &record = *access.record;
7449 // Queue and Batch information
7450 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7451 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7452
7453 // Commandbuffer Usages Information
7454 out << record;
7455 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7456 out << ", reset_no: " << std::to_string(record.reset_count);
7457 }
7458 return out.str();
7459}
7460
7461VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7462
John Zulauf00119522022-05-23 19:07:42 -06007463QueueId QueueBatchContext::GetQueueId() const {
7464 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7465 return id;
7466}
7467
John Zulauf697c0e12022-04-19 16:31:12 -06007468void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7469 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7470 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7471 SetTagBias(global_tags.begin);
7472 // Add an access log for the batches range and point the batch at it.
7473 logger_ = &logger;
7474 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7475}
7476
7477void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7478 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7479 batch_log_->Append(submitted_cb.GetAccessLog());
7480}
7481
7482void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7483 const auto size = tag_range_.size();
7484 tag_range_.begin = bias;
7485 tag_range_.end = bias + size;
7486 access_context_.SetStartTag(bias);
7487}
7488
John Zulauf1d5f9c12022-05-13 14:51:08 -06007489QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7490
7491void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7492 bool erased = access.second.ApplyQueueTagWait(predicate);
7493 if (erased) {
7494 erase_list.emplace_back(address_type, access.first);
7495 } else {
7496 erase_all = false;
7497 }
7498}
7499
John Zulauf697c0e12022-04-19 16:31:12 -06007500AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7501 const ResourceUsageRange &range) {
7502 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7503 assert(inserted.second);
7504 return &inserted.first->second;
7505}
7506
7507void AccessLogger::MergeMove(AccessLogger &&child) {
7508 for (auto &range : child.access_log_map_) {
7509 BatchLog &child_batch = range.second;
7510 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7511 insert_pair.first->second = std::move(child_batch);
7512 assert(insert_pair.second);
7513 }
7514 child.Reset();
7515}
7516
7517void AccessLogger::Reset() {
7518 prev_ = nullptr;
7519 access_log_map_.clear();
7520}
7521
7522// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7523// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7524// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7525// the contexts Resolve all history from previous all contexts when created
7526void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7527 last_batch_ = std::move(last);
7528 last_batch_->ResetAccessLog();
7529}
7530
7531// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7532// scope state.
7533// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7534// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7535uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7536
7537void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7538 log_.insert(log_.end(), other.cbegin(), other.cend());
7539 for (const auto &record : other) {
7540 assert(record.cb_state);
7541 cbs_referenced_.insert(record.cb_state->shared_from_this());
7542 }
7543}
7544
7545AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7546 assert(index < log_.size());
7547 return AccessRecord{&batch_, &log_[index]};
7548}
7549
7550AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7551 AccessRecord access_record = {nullptr, nullptr};
7552
7553 auto found_range = access_log_map_.find(tag);
7554 if (found_range != access_log_map_.cend()) {
7555 const ResourceUsageTag bias = found_range->first.begin;
7556 assert(tag >= bias);
7557 access_record = found_range->second[tag - bias];
7558 } else if (prev_) {
7559 access_record = (*prev_)[tag];
7560 }
7561
7562 return access_record;
7563}
John Zulaufcb7e1672022-05-04 13:46:08 -06007564
7565std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
7566 std::shared_ptr<Signal> prev_state;
7567 if (prev_) {
7568 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7569 }
7570 return prev_state;
7571}