blob: 11709f898608067d295706a91f4497fddfc41cd8 [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},
654 image_state.createInfo.extent, base_address);
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,
John Zulaufbb890452021-12-14 11:30:18 -0700729 const CommandExecutionContext &exec_context, const char *func_name)
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),
John Zulauf7635de32020-05-29 17:14:15 -0600734 func_name_(func_name),
735 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) {
John Zulauffaea0ee2021-01-14 14:01:32 -0700742 skip_ |=
John Zulaufbb890452021-12-14 11:30:18 -0700743 exec_context_.GetSyncState().LogError(render_pass_, string_SyncHazardVUID(hazard.hazard),
744 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32
745 " to resolve attachment %" PRIu32 ". Access info %s.",
746 func_name_, string_SyncHazard(hazard.hazard), subpass_, aspect_name,
John Zulauf397e68b2022-04-19 11:44:07 -0600747 attachment_name, src_at, 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_;
John Zulauf7635de32020-05-29 17:14:15 -0600758 const char *func_name_;
759 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,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001139 const AttachmentViewGenVector &attachment_views, const char *func_name) 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) {
John Zulaufee984022022-04-13 16:39:50 -06001167 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001168 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001169 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1170 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1171 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1172 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1173 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1174 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001175 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001176 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1177 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1178 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1179 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1180 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001181 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001182 }
John Zulauf355e49b2020-04-24 15:11:15 -06001183 }
1184 }
1185 return skip;
1186}
1187
John Zulaufbb890452021-12-14 11:30:18 -07001188bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001189 const VkRect2D &render_area, uint32_t subpass,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001190 const AttachmentViewGenVector &attachment_views, const char *func_name) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001191 bool skip = false;
1192 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001193
John Zulauf1507ee42020-05-18 11:33:09 -06001194 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1195 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001196 const auto &view_gen = attachment_views[i];
1197 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001198 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001199
1200 // Need check in the following way
1201 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1202 // vs. transition
1203 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1204 // for each aspect loaded.
1205
1206 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001207 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001208 const bool is_color = !(has_depth || has_stencil);
1209
1210 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001211 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001212
John Zulaufaff20662020-06-01 14:07:58 -06001213 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001214 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001215
John Zulaufb02c1eb2020-10-06 16:33:36 -06001216 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001217 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001218 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001219 aspect = "color";
1220 } else {
John Zulauf57261402021-08-13 11:32:06 -06001221 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001222 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1223 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001224 aspect = "depth";
1225 }
John Zulauf57261402021-08-13 11:32:06 -06001226 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001227 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1228 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001229 aspect = "stencil";
1230 checked_stencil = true;
1231 }
1232 }
1233
1234 if (hazard.hazard) {
1235 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001236 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001237 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001238 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001239 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001240 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1241 " aspect %s during load with loadOp %s.",
1242 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1243 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001244 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001245 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001246 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001247 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001248 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001249 }
1250 }
1251 }
1252 }
1253 return skip;
1254}
1255
John Zulaufaff20662020-06-01 14:07:58 -06001256// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1257// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1258// store is part of the same Next/End operation.
1259// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001260bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001261 const VkRect2D &render_area, uint32_t subpass,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001262 const AttachmentViewGenVector &attachment_views, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06001263 bool skip = false;
1264 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001265
1266 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1267 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001268 const AttachmentViewGen &view_gen = attachment_views[i];
1269 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001270 const auto &ci = attachment_ci[i];
1271
1272 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1273 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1274 // sake, we treat DONT_CARE as writing.
1275 const bool has_depth = FormatHasDepth(ci.format);
1276 const bool has_stencil = FormatHasStencil(ci.format);
1277 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001278 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001279 if (!has_stencil && !store_op_stores) continue;
1280
1281 HazardResult hazard;
1282 const char *aspect = nullptr;
1283 bool checked_stencil = false;
1284 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001285 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1286 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001287 aspect = "color";
1288 } else {
John Zulauf57261402021-08-13 11:32:06 -06001289 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001290 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001291 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1292 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001293 aspect = "depth";
1294 }
1295 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001296 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1297 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001298 aspect = "stencil";
1299 checked_stencil = true;
1300 }
1301 }
1302
1303 if (hazard.hazard) {
1304 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1305 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001306 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1307 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1308 " %s aspect during store with %s %s. Access info %s",
1309 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect,
1310 op_type_string, store_op_string,
1311 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001312 }
1313 }
1314 }
1315 return skip;
1316}
1317
John Zulaufbb890452021-12-14 11:30:18 -07001318bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001319 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
1320 const char *func_name, uint32_t subpass) const {
John Zulaufbb890452021-12-14 11:30:18 -07001321 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, func_name);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001322 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001323 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001324}
1325
John Zulauf06f6f1e2022-04-19 15:28:11 -06001326AccessContext::TrackBack *AccessContext::AddTrackBack(const AccessContext *context, const SyncBarrier &barrier) {
1327 prev_.emplace_back(context, barrier);
1328 return &prev_.back();
1329}
1330
1331void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1332
John Zulauf3d84f1b2020-03-09 13:33:25 -06001333class HazardDetector {
1334 SyncStageAccessIndex usage_index_;
1335
1336 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001337 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001338 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001339 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001340 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001341 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001342};
1343
John Zulauf69133422020-05-20 14:55:53 -06001344class HazardDetectorWithOrdering {
1345 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001346 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001347
1348 public:
1349 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001350 return pos->second.DetectHazard(usage_index_, ordering_rule_);
John Zulauf69133422020-05-20 14:55:53 -06001351 }
John Zulauf14940722021-04-12 15:19:02 -06001352 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001353 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001354 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001355 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001356};
1357
John Zulauf16adfc92020-04-08 10:28:33 -06001358HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001359 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001360 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001361 const auto base_address = ResourceBaseAddress(buffer);
1362 HazardDetector detector(usage_index);
1363 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001364}
1365
John Zulauf69133422020-05-20 14:55:53 -06001366template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001367HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1368 DetectOptions options) const {
1369 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1370 if (!attachment_gen) return HazardResult();
1371
1372 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1373 const auto address_type = view_gen.GetAddressType();
1374 for (; range_gen->non_empty(); ++range_gen) {
1375 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1376 if (hazard.hazard) return hazard;
1377 }
1378
1379 return HazardResult();
1380}
1381
1382template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001383HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1384 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
1385 const VkExtent3D &extent, DetectOptions options) const {
1386 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001387 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001388 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1389 base_address);
1390 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001391 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001392 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001393 if (hazard.hazard) return hazard;
1394 }
1395 return HazardResult();
1396}
John Zulauf110413c2021-03-20 05:38:38 -06001397template <typename Detector>
1398HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1399 const VkImageSubresourceRange &subresource_range, DetectOptions options) const {
1400 if (!SimpleBinding(image)) return HazardResult();
1401 const auto base_address = ResourceBaseAddress(image);
1402 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
1403 const auto address_type = ImageAddressType(image);
1404 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001405 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1406 if (hazard.hazard) return hazard;
1407 }
1408 return HazardResult();
1409}
John Zulauf69133422020-05-20 14:55:53 -06001410
John Zulauf540266b2020-04-06 18:54:53 -06001411HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1412 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
1413 const VkExtent3D &extent) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001414 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1415 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001416 HazardDetector detector(current_usage);
1417 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001418}
1419
1420HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf110413c2021-03-20 05:38:38 -06001421 const VkImageSubresourceRange &subresource_range) const {
John Zulauf69133422020-05-20 14:55:53 -06001422 HazardDetector detector(current_usage);
John Zulauf110413c2021-03-20 05:38:38 -06001423 return DetectHazard(detector, image, subresource_range, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001424}
1425
John Zulaufd0ec59f2021-03-13 14:25:08 -07001426HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1427 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1428 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1429 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1430}
1431
John Zulauf69133422020-05-20 14:55:53 -06001432HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001433 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
John Zulauf69133422020-05-20 14:55:53 -06001434 const VkOffset3D &offset, const VkExtent3D &extent) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001435 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
John Zulauf69133422020-05-20 14:55:53 -06001436 return DetectHazard(detector, image, subresource_range, offset, extent, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001437}
1438
John Zulauf3d84f1b2020-03-09 13:33:25 -06001439class BarrierHazardDetector {
1440 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001441 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001442 SyncStageAccessFlags src_access_scope)
1443 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1444
John Zulauf5f13a792020-03-10 07:31:21 -06001445 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1446 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001447 }
John Zulauf14940722021-04-12 15:19:02 -06001448 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001449 // 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 -07001450 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001451 }
1452
1453 private:
1454 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001455 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001456 SyncStageAccessFlags src_access_scope_;
1457};
1458
John Zulauf4a6105a2020-11-17 15:11:05 -07001459class EventBarrierHazardDetector {
1460 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001461 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001462 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
John Zulauf14940722021-04-12 15:19:02 -06001463 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001464 : usage_index_(usage_index),
1465 src_exec_scope_(src_exec_scope),
1466 src_access_scope_(src_access_scope),
1467 event_scope_(event_scope),
1468 scope_pos_(event_scope.cbegin()),
1469 scope_end_(event_scope.cend()),
1470 scope_tag_(scope_tag) {}
1471
1472 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1473 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1474 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1475 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1476 if (scope_pos_ == scope_end_) return HazardResult();
1477 if (!scope_pos_->first.intersects(pos->first)) {
1478 event_scope_.lower_bound(pos->first);
1479 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1480 }
1481
1482 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1483 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1484 }
John Zulauf14940722021-04-12 15:19:02 -06001485 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001486 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1487 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1488 }
1489
1490 private:
1491 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001492 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001493 SyncStageAccessFlags src_access_scope_;
1494 const SyncEventState::ScopeMap &event_scope_;
1495 SyncEventState::ScopeMap::const_iterator scope_pos_;
1496 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf14940722021-04-12 15:19:02 -06001497 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001498};
1499
Jeremy Gebben40a22942020-12-22 14:22:06 -07001500HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001501 const SyncStageAccessFlags &src_access_scope,
1502 const VkImageSubresourceRange &subresource_range,
1503 const SyncEventState &sync_event, DetectOptions options) const {
1504 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1505 // first access scope map to use, and there's no easy way to plumb it in below.
1506 const auto address_type = ImageAddressType(image);
1507 const auto &event_scope = sync_event.FirstScope(address_type);
1508
1509 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1510 event_scope, sync_event.first_scope_tag);
John Zulauf110413c2021-03-20 05:38:38 -06001511 return DetectHazard(detector, image, subresource_range, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001512}
1513
John Zulaufd0ec59f2021-03-13 14:25:08 -07001514HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1515 DetectOptions options) const {
1516 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1517 barrier.src_access_scope);
1518 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1519}
1520
Jeremy Gebben40a22942020-12-22 14:22:06 -07001521HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001522 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001523 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001524 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001525 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
John Zulauf110413c2021-03-20 05:38:38 -06001526 return DetectHazard(detector, image, subresource_range, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001527}
1528
Jeremy Gebben40a22942020-12-22 14:22:06 -07001529HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001530 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001531 const VkImageMemoryBarrier &barrier) const {
1532 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1533 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1534 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1535}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001536HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001537 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001538 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001539}
John Zulauf355e49b2020-04-24 15:11:15 -06001540
John Zulauf9cb530d2019-09-30 14:14:10 -06001541template <typename Flags, typename Map>
1542SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1543 SyncStageAccessFlags scope = 0;
1544 for (const auto &bit_scope : map) {
1545 if (flag_mask < bit_scope.first) break;
1546
1547 if (flag_mask & bit_scope.first) {
1548 scope |= bit_scope.second;
1549 }
1550 }
1551 return scope;
1552}
1553
Jeremy Gebben40a22942020-12-22 14:22:06 -07001554SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001555 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1556}
1557
Jeremy Gebben40a22942020-12-22 14:22:06 -07001558SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1559 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001560}
1561
Jeremy Gebben40a22942020-12-22 14:22:06 -07001562// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1563SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001564 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1565 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1566 // 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 -06001567 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1568}
1569
1570template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001571void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001572 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1573 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001574 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001575 auto pos = accesses->lower_bound(range);
1576 if (pos == accesses->end() || !pos->first.intersects(range)) {
1577 // The range is empty, fill it with a default value.
1578 pos = action.Infill(accesses, pos, range);
1579 } else if (range.begin < pos->first.begin) {
1580 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001581 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001582 } else if (pos->first.begin < range.begin) {
1583 // Trim the beginning if needed
1584 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1585 ++pos;
1586 }
1587
1588 const auto the_end = accesses->end();
1589 while ((pos != the_end) && pos->first.intersects(range)) {
1590 if (pos->first.end > range.end) {
1591 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1592 }
1593
1594 pos = action(accesses, pos);
1595 if (pos == the_end) break;
1596
1597 auto next = pos;
1598 ++next;
1599 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1600 // Need to infill if next is disjoint
1601 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001602 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001603 next = action.Infill(accesses, next, new_range);
1604 }
1605 pos = next;
1606 }
1607}
John Zulaufd5115702021-01-18 12:34:33 -07001608
1609// Give a comparable interface for range generators and ranges
1610template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001611void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001612 assert(range);
1613 UpdateMemoryAccessState(accesses, *range, action);
1614}
1615
John Zulauf4a6105a2020-11-17 15:11:05 -07001616template <typename Action, typename RangeGen>
1617void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1618 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001619 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 -07001620 for (; range_gen->non_empty(); ++range_gen) {
1621 UpdateMemoryAccessState(accesses, *range_gen, action);
1622 }
1623}
John Zulauf9cb530d2019-09-30 14:14:10 -06001624
John Zulaufd0ec59f2021-03-13 14:25:08 -07001625template <typename Action, typename RangeGen>
1626void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1627 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1628 for (; range_gen->non_empty(); ++range_gen) {
1629 UpdateMemoryAccessState(accesses, *range_gen, action);
1630 }
1631}
John Zulauf9cb530d2019-09-30 14:14:10 -06001632struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001633 using Iterator = ResourceAccessRangeMap::iterator;
1634 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001635 // this is only called on gaps, and never returns a gap.
1636 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001637 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001638 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001639 }
John Zulauf5f13a792020-03-10 07:31:21 -06001640
John Zulauf5c5e88d2019-12-26 11:22:02 -07001641 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001642 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001643 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001644 return pos;
1645 }
1646
John Zulauf43cc7462020-12-03 12:33:12 -07001647 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001648 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001649 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001650 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001651 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001652 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001653 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001654 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001655};
1656
John Zulauf4a6105a2020-11-17 15:11:05 -07001657// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001658struct PipelineBarrierOp {
1659 SyncBarrier barrier;
1660 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001661 ResourceAccessState::QueueScopeOps scope;
1662 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1663 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001664 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001665 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001666};
John Zulauf00119522022-05-23 19:07:42 -06001667
John Zulauf4a6105a2020-11-17 15:11:05 -07001668// The barrier operation for wait events
1669struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001670 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001671 SyncBarrier barrier;
1672 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001673 // WIP Integrate Queue scoping into event scope operations
1674 WaitEventBarrierOp(const QueueId scope_queue, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
1675 bool layout_transition_)
John Zulaufb7578302022-05-19 13:50:18 -06001676 : scope_ops(scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1677 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001678};
John Zulauf1e331ec2020-12-04 18:29:38 -07001679
John Zulauf4a6105a2020-11-17 15:11:05 -07001680// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1681// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1682// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001683template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001684class ApplyBarrierOpsFunctor {
1685 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001686 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001687 // Only called with a gap, and pos at the lower_bound(range)
1688 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1689 if (!infill_default_) {
1690 return pos;
1691 }
1692 ResourceAccessState default_state;
1693 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1694 return inserted;
1695 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001696
John Zulauf5c628d02021-05-04 15:46:36 -06001697 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001698 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001699 for (const auto &op : barrier_ops_) {
1700 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001701 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001702
John Zulauf89311b42020-09-29 16:28:47 -06001703 if (resolve_) {
1704 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1705 // another walk
1706 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001707 }
1708 return pos;
1709 }
1710
John Zulauf89311b42020-09-29 16:28:47 -06001711 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001712 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1713 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001714 barrier_ops_.reserve(size_hint);
1715 }
John Zulauf5c628d02021-05-04 15:46:36 -06001716 void EmplaceBack(const BarrierOp &op) {
1717 barrier_ops_.emplace_back(op);
1718 infill_default_ |= op.layout_transition;
1719 }
John Zulauf89311b42020-09-29 16:28:47 -06001720
1721 private:
1722 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001723 bool infill_default_;
1724 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001725 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001726};
1727
John Zulauf4a6105a2020-11-17 15:11:05 -07001728// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1729// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1730template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001731class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1732 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1733
John Zulauf4a6105a2020-11-17 15:11:05 -07001734 public:
John Zulaufee984022022-04-13 16:39:50 -06001735 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001736};
1737
John Zulauf1e331ec2020-12-04 18:29:38 -07001738// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001739class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1740 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1741
John Zulauf1e331ec2020-12-04 18:29:38 -07001742 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001743 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001744};
1745
John Zulauf8e3c3e92021-01-06 11:19:36 -07001746void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001747 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001748 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001749 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001750}
1751
John Zulauf8e3c3e92021-01-06 11:19:36 -07001752void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001753 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001754 if (!SimpleBinding(buffer)) return;
1755 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001756 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001757}
John Zulauf355e49b2020-04-24 15:11:15 -06001758
John Zulauf8e3c3e92021-01-06 11:19:36 -07001759void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001760 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1761 if (!SimpleBinding(image)) return;
1762 const auto base_address = ResourceBaseAddress(image);
1763 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
1764 const auto address_type = ImageAddressType(image);
1765 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1766 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1767}
1768void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001769 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001770 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001771 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001772 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001773 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
1774 base_address);
1775 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001776 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001777 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001778}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001779
1780void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001781 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001782 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1783 if (!gen) return;
1784 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1785 const auto address_type = view_gen.GetAddressType();
1786 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1787 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001788}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001789
John Zulauf8e3c3e92021-01-06 11:19:36 -07001790void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001791 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001792 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001793 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1794 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001795 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001796}
1797
John Zulaufd0ec59f2021-03-13 14:25:08 -07001798template <typename Action, typename RangeGen>
1799void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1800 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1801 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001802}
1803
1804template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001805void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1806 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1807 if (!gen) return;
1808 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001809}
1810
John Zulaufd0ec59f2021-03-13 14:25:08 -07001811void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1812 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001813 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001814 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001815 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001816}
1817
John Zulaufd0ec59f2021-03-13 14:25:08 -07001818void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001819 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001820 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001821
1822 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1823 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001824 const auto &view_gen = attachment_views[i];
1825 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001826
1827 const auto &ci = attachment_ci[i];
1828 const bool has_depth = FormatHasDepth(ci.format);
1829 const bool has_stencil = FormatHasStencil(ci.format);
1830 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001831 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001832
1833 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001834 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1835 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001836 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001837 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001838 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1839 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001840 }
John Zulauf57261402021-08-13 11:32:06 -06001841 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001842 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001843 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1844 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001845 }
1846 }
1847 }
1848 }
1849}
1850
John Zulauf540266b2020-04-06 18:54:53 -06001851template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001852void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001853 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001854 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001855 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001856 }
1857}
1858
1859void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001860 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1861 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001862 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001863 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001864 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001865 }
1866 }
1867}
1868
John Zulauf4fa68462021-04-26 21:04:22 -06001869// Caller must ensure that lifespan of this is less than from
1870void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1871
John Zulauf355e49b2020-04-24 15:11:15 -06001872// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001873HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1874 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001875
John Zulauf355e49b2020-04-24 15:11:15 -06001876 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001877 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001878
1879 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001880 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1881 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001882 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001883 if (!hazard.hazard) {
1884 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001885 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001886 }
John Zulaufa0a98292020-09-18 09:30:10 -06001887
John Zulauf355e49b2020-04-24 15:11:15 -06001888 return hazard;
1889}
1890
John Zulaufb02c1eb2020-10-06 16:33:36 -06001891void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001892 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001893 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001894 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001895 for (const auto &transition : transitions) {
1896 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001897 const auto &view_gen = attachment_views[transition.attachment];
1898 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001899
1900 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1901 assert(trackback);
1902
1903 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001904 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001905 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001906 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001907 auto &target_map = GetAccessStateMap(address_type);
1908 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001909 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1910 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001911 }
1912
John Zulauf86356ca2020-10-19 11:46:41 -06001913 // If there were no transitions skip this global map walk
1914 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001915 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001916 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001917 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001918}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001919
locke-lunarg61870c22020-06-09 14:51:50 -06001920bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1921 const char *func_name) const {
1922 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001923 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001924 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001925 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001926 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001927 return skip;
1928 }
1929
1930 using DescriptorClass = cvdescriptorset::DescriptorClass;
1931 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1932 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06001933 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1934
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001935 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001936 const auto raster_state = pipe->RasterizationState();
1937 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001938 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001939 }
locke-lunarg61870c22020-06-09 14:51:50 -06001940 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001941 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06001942 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001943 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06001944 const auto descriptor_type = binding_it.GetType();
1945 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1946 auto array_idx = 0;
1947
1948 if (binding_it.IsVariableDescriptorCount()) {
1949 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1950 }
1951 SyncStageAccessIndex sync_index =
1952 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1953
1954 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1955 uint32_t index = i - index_range.start;
1956 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1957 switch (descriptor->GetClass()) {
1958 case DescriptorClass::ImageSampler:
1959 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07001960 if (descriptor->Invalid()) {
1961 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06001962 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07001963
1964 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
1965 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1966 const auto *img_view_state = image_descriptor->GetImageViewState();
1967 VkImageLayout image_layout = image_descriptor->GetImageLayout();
1968
John Zulauf361fb532020-07-22 10:45:39 -06001969 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06001970 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
1971 // Descriptors, so we do not have to worry about depth slicing here.
1972 // See: VUID 00343
1973 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06001974 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06001975 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06001976
1977 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1978 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1979 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06001980 // Input attachments are subject to raster ordering rules
1981 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001982 SyncOrdering::kRaster, offset, extent);
John Zulauf361fb532020-07-22 10:45:39 -06001983 } else {
John Zulauf110413c2021-03-20 05:38:38 -06001984 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range);
John Zulauf361fb532020-07-22 10:45:39 -06001985 }
John Zulauf110413c2021-03-20 05:38:38 -06001986
John Zulauf33fc1d52020-07-17 11:01:10 -06001987 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001988 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001989 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001990 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1991 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001992 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001993 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
1994 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
1995 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001996 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
1997 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001998 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06001999 }
2000 break;
2001 }
2002 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002003 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2004 if (texel_descriptor->Invalid()) {
2005 continue;
2006 }
2007 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2008 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002009 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002010 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002011 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002012 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002013 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002014 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
2015 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002016 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2017 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2018 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002019 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002020 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002021 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002022 }
2023 break;
2024 }
2025 case DescriptorClass::GeneralBuffer: {
2026 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002027 if (buffer_descriptor->Invalid()) {
2028 continue;
2029 }
2030 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002031 const ResourceAccessRange range =
2032 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002033 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002034 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002035 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002036 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002037 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
2038 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002039 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2040 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2041 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002042 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002043 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002044 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002045 }
2046 break;
2047 }
2048 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2049 default:
2050 break;
2051 }
2052 }
2053 }
2054 }
2055 return skip;
2056}
2057
2058void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002059 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002060 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002061 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002062 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002063 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002064 return;
2065 }
2066
2067 using DescriptorClass = cvdescriptorset::DescriptorClass;
2068 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2069 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002070 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2071
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002072 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002073 const auto raster_state = pipe->RasterizationState();
2074 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002075 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002076 }
locke-lunarg61870c22020-06-09 14:51:50 -06002077 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002078 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002079 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002080 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06002081 const auto descriptor_type = binding_it.GetType();
2082 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
2083 auto array_idx = 0;
2084
2085 if (binding_it.IsVariableDescriptorCount()) {
2086 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2087 }
2088 SyncStageAccessIndex sync_index =
2089 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2090
2091 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2092 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2093 switch (descriptor->GetClass()) {
2094 case DescriptorClass::ImageSampler:
2095 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002096 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2097 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2098 if (image_descriptor->Invalid()) {
2099 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002100 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002101 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002102 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2103 // Descriptors, so we do not have to worry about depth slicing here.
2104 // See: VUID 00343
2105 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002106 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002107 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002108 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2109 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2110 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2111 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002112 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002113 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2114 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002115 }
locke-lunarg61870c22020-06-09 14:51:50 -06002116 break;
2117 }
2118 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002119 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2120 if (texel_descriptor->Invalid()) {
2121 continue;
2122 }
2123 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2124 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002125 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002126 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002127 break;
2128 }
2129 case DescriptorClass::GeneralBuffer: {
2130 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002131 if (buffer_descriptor->Invalid()) {
2132 continue;
2133 }
2134 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002135 const ResourceAccessRange range =
2136 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002137 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002138 break;
2139 }
2140 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2141 default:
2142 break;
2143 }
2144 }
2145 }
2146 }
2147}
2148
2149bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2150 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002151 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002152 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002153 return skip;
2154 }
2155
2156 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2157 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002158 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002159
2160 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002161 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002162 if (binding_description.binding < binding_buffers_size) {
2163 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002164 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002165
locke-lunarg1ae57d62020-11-18 10:49:19 -07002166 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002167 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2168 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002169 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002170 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002171 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002172 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
John Zulauf397e68b2022-04-19 11:44:07 -06002173 func_name, string_SyncHazard(hazard.hazard),
2174 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2175 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002176 }
2177 }
2178 }
2179 return skip;
2180}
2181
John Zulauf14940722021-04-12 15:19:02 -06002182void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002183 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002184 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002185 return;
2186 }
2187 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2188 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002189 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002190
2191 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002192 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002193 if (binding_description.binding < binding_buffers_size) {
2194 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002195 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002196
locke-lunarg1ae57d62020-11-18 10:49:19 -07002197 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002198 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2199 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002200 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2201 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002202 }
2203 }
2204}
2205
2206bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2207 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002208 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002209 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002210 }
locke-lunarg61870c22020-06-09 14:51:50 -06002211
locke-lunarg1ae57d62020-11-18 10:49:19 -07002212 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002213 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002214 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2215 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002216 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002217 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002218 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002219 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
2220 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002221 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002222 }
2223
2224 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2225 // We will detect more accurate range in the future.
2226 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2227 return skip;
2228}
2229
John Zulauf14940722021-04-12 15:19:02 -06002230void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002231 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 -06002232
locke-lunarg1ae57d62020-11-18 10:49:19 -07002233 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002234 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002235 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2236 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002237 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002238
2239 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2240 // We will detect more accurate range in the future.
2241 RecordDrawVertex(UINT32_MAX, 0, tag);
2242}
2243
2244bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002245 bool skip = false;
2246 if (!current_renderpass_context_) return skip;
John Zulauf64ffe552021-02-06 10:25:07 -07002247 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), func_name);
locke-lunarg7077d502020-06-18 21:37:26 -06002248 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002249}
2250
John Zulauf14940722021-04-12 15:19:02 -06002251void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002252 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002253 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002254 }
locke-lunarg61870c22020-06-09 14:51:50 -06002255}
2256
John Zulauf00119522022-05-23 19:07:42 -06002257QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2258
John Zulauf41a9c7c2021-12-07 15:59:53 -07002259ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd, const RENDER_PASS_STATE &rp_state,
2260 const VkRect2D &render_area,
2261 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002262 // Create an access context the current renderpass.
John Zulauf41a9c7c2021-12-07 15:59:53 -07002263 const auto barrier_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2264 const auto load_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002265 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002266 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002267 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002268 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002269 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002270}
2271
John Zulauf41a9c7c2021-12-07 15:59:53 -07002272ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd) {
John Zulauf16adfc92020-04-08 10:28:33 -06002273 assert(current_renderpass_context_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002274 if (!current_renderpass_context_) return NextCommandTag(cmd);
2275
2276 auto store_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kStoreOp);
2277 auto barrier_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2278 auto load_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kLoadOp);
2279
2280 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002281 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002282 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002283}
2284
John Zulauf41a9c7c2021-12-07 15:59:53 -07002285ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd) {
John Zulauf16adfc92020-04-08 10:28:33 -06002286 assert(current_renderpass_context_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002287 if (!current_renderpass_context_) return NextCommandTag(cmd);
John Zulauf16adfc92020-04-08 10:28:33 -06002288
John Zulauf41a9c7c2021-12-07 15:59:53 -07002289 auto store_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kStoreOp);
2290 auto barrier_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2291
2292 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002293 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002294 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002295 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002296}
2297
John Zulauf4a6105a2020-11-17 15:11:05 -07002298void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2299 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002300 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002301 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002302 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002303 }
2304}
2305
John Zulaufae842002021-04-15 18:20:55 -06002306// The is the recorded cb context
John Zulaufbb890452021-12-14 11:30:18 -07002307bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext *proxy_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002308 uint32_t index) const {
2309 assert(proxy_context);
John Zulauf00119522022-05-23 19:07:42 -06002310 SyncEventsContext *const events_context = proxy_context->GetCurrentEventsContext();
2311 AccessContext *const access_context = proxy_context->GetCurrentAccessContext();
2312 const QueueId queue_id = proxy_context->GetQueueId();
John Zulauf4fa68462021-04-26 21:04:22 -06002313 const ResourceUsageTag base_tag = proxy_context->GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002314 bool skip = false;
2315 ResourceUsageRange tag_range = {0, 0};
2316 const AccessContext *recorded_context = GetCurrentAccessContext();
2317 assert(recorded_context);
2318 HazardResult hazard;
John Zulaufbb890452021-12-14 11:30:18 -07002319 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002320 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002321 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002322 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002323 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002324 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002325 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2326 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002327 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002328 };
John Zulaufbb890452021-12-14 11:30:18 -07002329 const ReplayTrackbackBarriersAction *replay_context = nullptr;
John Zulaufae842002021-04-15 18:20:55 -06002330 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002331 // we update the range to any include layout transition first use writes,
2332 // as they are stored along with the source scope (as effective barrier) when recorded
2333 tag_range.end = sync_op.tag + 1;
John Zulauf610e28c2021-08-03 17:46:23 -06002334 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, proxy_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002335
John Zulaufbb890452021-12-14 11:30:18 -07002336 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002337 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002338 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002339 }
2340 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002341 // Record the barrier into the proxy context.
John Zulauf00119522022-05-23 19:07:42 -06002342 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulaufbb890452021-12-14 11:30:18 -07002343 replay_context = sync_op.sync_op->GetReplayTrackback();
John Zulauf4fa68462021-04-26 21:04:22 -06002344 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002345 }
2346
John Zulaufbb890452021-12-14 11:30:18 -07002347 // Renderpasses may not cross command buffer boundaries
2348 assert(replay_context == nullptr);
2349
John Zulaufae842002021-04-15 18:20:55 -06002350 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002351 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulaufbb890452021-12-14 11:30:18 -07002352 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002353 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002354 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002355 }
2356
2357 return skip;
2358}
2359
John Zulauf1d5f9c12022-05-13 14:51:08 -06002360void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context, CMD_TYPE cmd) {
John Zulauf00119522022-05-23 19:07:42 -06002361 SyncEventsContext *const events_context = GetCurrentEventsContext();
2362 AccessContext *const access_context = GetCurrentAccessContext();
2363 const QueueId queue_id = GetQueueId();
2364
John Zulauf4fa68462021-04-26 21:04:22 -06002365 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2366 assert(recorded_context);
2367
2368 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2369 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002370 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002371 // we update the range to any include layout transition first use writes,
2372 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf00119522022-05-23 19:07:42 -06002373 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002374 }
2375
2376 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2377 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002378 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002379}
2380
John Zulauf1d5f9c12022-05-13 14:51:08 -06002381void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002382 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002383 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002384}
2385
John Zulauf3c788ef2022-02-22 12:12:30 -07002386ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002387 // The execution references ensure lifespan for the referenced child CB's...
2388 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002389 InsertRecordedAccessLogEntries(recorded_context);
2390 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002391 return tag_range;
2392}
2393
John Zulauf3c788ef2022-02-22 12:12:30 -07002394void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2395 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2396 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2397}
2398
John Zulauf41a9c7c2021-12-07 15:59:53 -07002399ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2400 ResourceUsageTag next = access_log_.size();
2401 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2402 return next;
2403}
2404
2405ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2406 command_number_++;
2407 subcommand_number_ = 0;
2408 ResourceUsageTag next = access_log_.size();
2409 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2410 return next;
2411}
2412
2413ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2414 if (index == 0) {
2415 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2416 }
2417 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2418}
2419
John Zulaufbb890452021-12-14 11:30:18 -07002420void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2421 auto tag = sync_op->Record(this);
2422 // As renderpass operations can have side effects on the command buffer access context,
2423 // update the sync operation to record these if any.
2424 if (current_renderpass_context_) {
2425 const auto &rpc = *current_renderpass_context_;
2426 sync_op->SetReplayContext(rpc.GetCurrentSubpass(), rpc.GetReplayContext());
2427 }
2428 sync_ops_.emplace_back(tag, std::move(sync_op));
2429}
2430
John Zulaufae842002021-04-15 18:20:55 -06002431class HazardDetectFirstUse {
2432 public:
John Zulaufbb890452021-12-14 11:30:18 -07002433 HazardDetectFirstUse(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
2434 const ReplayTrackbackBarriersAction *replay_barrier)
2435 : recorded_use_(recorded_use), tag_range_(tag_range), replay_barrier_(replay_barrier) {}
John Zulaufae842002021-04-15 18:20:55 -06002436 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufbb890452021-12-14 11:30:18 -07002437 if (replay_barrier_) {
2438 // Intentional copy to apply the replay barrier
2439 auto access = pos->second;
2440 (*replay_barrier_)(&access);
2441 return access.DetectHazard(recorded_use_, tag_range_);
2442 }
John Zulaufae842002021-04-15 18:20:55 -06002443 return pos->second.DetectHazard(recorded_use_, tag_range_);
2444 }
2445 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2446 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2447 }
2448
2449 private:
2450 const ResourceAccessState &recorded_use_;
2451 const ResourceUsageRange &tag_range_;
John Zulaufbb890452021-12-14 11:30:18 -07002452 const ReplayTrackbackBarriersAction *replay_barrier_;
John Zulaufae842002021-04-15 18:20:55 -06002453};
2454
2455// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2456// hazards will be detected
John Zulaufbb890452021-12-14 11:30:18 -07002457HazardResult AccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range, const AccessContext &access_context,
2458 const ReplayTrackbackBarriersAction *replay_barrier) const {
John Zulaufae842002021-04-15 18:20:55 -06002459 HazardResult hazard;
2460 for (const auto address_type : kAddressTypes) {
2461 const auto &recorded_access_map = GetAccessStateMap(address_type);
2462 for (const auto &recorded_access : recorded_access_map) {
2463 // Cull any entries not in the current tag range
2464 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulaufbb890452021-12-14 11:30:18 -07002465 HazardDetectFirstUse detector(recorded_access.second, tag_range, replay_barrier);
John Zulaufae842002021-04-15 18:20:55 -06002466 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2467 if (hazard.hazard) break;
2468 }
2469 }
2470
2471 return hazard;
2472}
2473
John Zulaufbb890452021-12-14 11:30:18 -07002474bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
2475 const CMD_BUFFER_STATE &cmd, const char *func_name) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002476 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002477 const auto &sync_state = exec_context.GetSyncState();
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002478 const auto *pipe = cmd.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002479 if (!pipe) {
2480 return skip;
2481 }
2482
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002483 const auto raster_state = pipe->RasterizationState();
2484 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002485 return skip;
2486 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002487 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002488 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002489
John Zulauf1a224292020-06-30 14:52:13 -06002490 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002491 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002492 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2493 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002494 if (location >= subpass.colorAttachmentCount ||
2495 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002496 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002497 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002498 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2499 if (!view_gen.IsValid()) continue;
2500 HazardResult hazard =
2501 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2502 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002503 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002504 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002505 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002506 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002507 func_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002508 sync_state.report_data->FormatHandle(view_handle).c_str(),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002509 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002510 location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002511 }
2512 }
2513 }
locke-lunarg37047832020-06-12 13:44:45 -06002514
2515 // PHASE1 TODO: Add layout based read/vs. write selection.
2516 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002517 const auto ds_state = pipe->DepthStencilState();
2518 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002519
2520 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2521 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2522 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002523 bool depth_write = false, stencil_write = false;
2524
2525 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002526 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002527 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2528 depth_write = true;
2529 }
2530 // PHASE1 TODO: It needs to check if stencil is writable.
2531 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2532 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2533 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002534 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002535 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2536 stencil_write = true;
2537 }
2538
2539 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2540 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002541 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2542 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2543 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002544 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002545 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002546 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002547 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002548 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002549 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
2550 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002551 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002552 }
2553 }
2554 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002555 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2556 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2557 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002558 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002559 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002560 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002561 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002562 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002563 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
2564 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002565 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002566 }
locke-lunarg61870c22020-06-09 14:51:50 -06002567 }
2568 }
2569 return skip;
2570}
2571
John Zulauf14940722021-04-12 15:19:02 -06002572void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002573 const auto *pipe = cmd.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002574 if (!pipe) {
2575 return;
2576 }
2577
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002578 const auto *raster_state = pipe->RasterizationState();
2579 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002580 return;
2581 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002582 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002583 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002584
John Zulauf1a224292020-06-30 14:52:13 -06002585 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002586 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002587 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2588 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002589 if (location >= subpass.colorAttachmentCount ||
2590 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002591 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002592 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002593 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2594 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2595 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2596 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002597 }
2598 }
locke-lunarg37047832020-06-12 13:44:45 -06002599
2600 // PHASE1 TODO: Add layout based read/vs. write selection.
2601 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002602 const auto *ds_state = pipe->DepthStencilState();
2603 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002604 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2605 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2606 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002607 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002608 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2609 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002610
2611 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002612 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2613 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002614 depth_write = true;
2615 }
2616 // PHASE1 TODO: It needs to check if stencil is writable.
2617 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2618 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2619 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002620 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002621 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2622 stencil_write = true;
2623 }
2624
John Zulaufd0ec59f2021-03-13 14:25:08 -07002625 if (depth_write || stencil_write) {
2626 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2627 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2628 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2629 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002630 }
locke-lunarg61870c22020-06-09 14:51:50 -06002631 }
2632}
2633
John Zulaufbb890452021-12-14 11:30:18 -07002634bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002635 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002636 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002637 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, func_name,
John Zulaufb027cdb2020-05-21 14:25:22 -06002638 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002639 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002640 func_name);
2641
John Zulauf355e49b2020-04-24 15:11:15 -06002642 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002643 if (next_subpass >= subpass_contexts_.size()) {
2644 return skip;
2645 }
John Zulauf1507ee42020-05-18 11:33:09 -06002646 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002647 skip |=
John Zulaufbb890452021-12-14 11:30:18 -07002648 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002649 if (!skip) {
2650 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2651 // on a copy of the (empty) next context.
2652 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2653 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002654 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002655 skip |=
John Zulaufbb890452021-12-14 11:30:18 -07002656 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002657 }
John Zulauf7635de32020-05-29 17:14:15 -06002658 return skip;
2659}
John Zulaufbb890452021-12-14 11:30:18 -07002660bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002661 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002662 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002663 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, func_name,
John Zulauf7635de32020-05-29 17:14:15 -06002664 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002665 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_,
John Zulaufd0ec59f2021-03-13 14:25:08 -07002666
2667 attachment_views_, func_name);
John Zulaufbb890452021-12-14 11:30:18 -07002668 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002669 return skip;
2670}
2671
John Zulauf64ffe552021-02-06 10:25:07 -07002672AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002673 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002674}
2675
John Zulaufbb890452021-12-14 11:30:18 -07002676bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
John Zulauf64ffe552021-02-06 10:25:07 -07002677 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002678 bool skip = false;
2679
John Zulauf7635de32020-05-29 17:14:15 -06002680 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2681 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2682 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2683 // to apply and only copy then, if this proves a hot spot.
2684 std::unique_ptr<AccessContext> proxy_for_current;
2685
John Zulauf355e49b2020-04-24 15:11:15 -06002686 // Validate the "finalLayout" transitions to external
2687 // Get them from where there we're hidding in the extra entry.
2688 const auto &final_transitions = rp_state_->subpass_transitions.back();
2689 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002690 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002691 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002692 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2693 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002694
2695 if (transition.prev_pass == current_subpass_) {
2696 if (!proxy_for_current) {
2697 // 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 -07002698 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002699 }
2700 context = proxy_for_current.get();
2701 }
2702
John Zulaufa0a98292020-09-18 09:30:10 -06002703 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2704 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002705 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002706 if (hazard.hazard) {
John Zulaufee984022022-04-13 16:39:50 -06002707 if (hazard.tag == kInvalidTag) {
2708 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002709 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002710 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2711 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2712 " final image layout transition (old_layout: %s, new_layout: %s).",
2713 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2714 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2715 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002716 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002717 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2718 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2719 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2720 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2721 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002722 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002723 }
John Zulauf355e49b2020-04-24 15:11:15 -06002724 }
2725 }
2726 return skip;
2727}
2728
John Zulauf14940722021-04-12 15:19:02 -06002729void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002730 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002731 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002732}
2733
John Zulauf14940722021-04-12 15:19:02 -06002734void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002735 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2736 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002737
2738 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2739 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002740 const AttachmentViewGen &view_gen = attachment_views_[i];
2741 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002742
2743 const auto &ci = attachment_ci[i];
2744 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002745 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002746 const bool is_color = !(has_depth || has_stencil);
2747
2748 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002749 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2750 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2751 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2752 SyncOrdering::kColorAttachment, tag);
2753 }
John Zulauf1507ee42020-05-18 11:33:09 -06002754 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002755 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002756 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2757 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2758 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2759 SyncOrdering::kDepthStencilAttachment, tag);
2760 }
John Zulauf1507ee42020-05-18 11:33:09 -06002761 }
2762 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002763 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2764 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2765 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2766 SyncOrdering::kDepthStencilAttachment, tag);
2767 }
John Zulauf1507ee42020-05-18 11:33:09 -06002768 }
2769 }
2770 }
2771 }
2772}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002773AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2774 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2775 AttachmentViewGenVector view_gens;
2776 VkExtent3D extent = CastTo3D(render_area.extent);
2777 VkOffset3D offset = CastTo3D(render_area.offset);
2778 view_gens.reserve(attachment_views.size());
2779 for (const auto *view : attachment_views) {
2780 view_gens.emplace_back(view, offset, extent);
2781 }
2782 return view_gens;
2783}
John Zulauf64ffe552021-02-06 10:25:07 -07002784RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2785 VkQueueFlags queue_flags,
2786 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2787 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002788 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulauf355e49b2020-04-24 15:11:15 -06002789 // Add this for all subpasses here so that they exsist during next subpass validation
John Zulauf64ffe552021-02-06 10:25:07 -07002790 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
John Zulaufbb890452021-12-14 11:30:18 -07002791 replay_context_ = std::make_shared<ReplayRenderpassContext>();
2792 auto &replay_subpass_contexts = replay_context_->subpass_contexts;
2793 replay_subpass_contexts.reserve(rp_state_->createInfo.subpassCount);
John Zulauf355e49b2020-04-24 15:11:15 -06002794 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002795 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulaufbb890452021-12-14 11:30:18 -07002796 replay_subpass_contexts.emplace_back(queue_flags, rp_state_->subpass_dependencies[pass], replay_subpass_contexts);
John Zulauf355e49b2020-04-24 15:11:15 -06002797 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002798 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002799}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002800void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002801 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002802 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2803 RecordLayoutTransitions(barrier_tag);
2804 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002805}
John Zulauf1507ee42020-05-18 11:33:09 -06002806
John Zulauf41a9c7c2021-12-07 15:59:53 -07002807void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2808 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002809 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002810 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2811 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002812
ziga-lunarg31a3e772022-03-22 11:48:46 +01002813 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2814 return;
2815 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002816 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2817 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002818 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002819 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2820 RecordLayoutTransitions(barrier_tag);
2821 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002822}
2823
John Zulauf41a9c7c2021-12-07 15:59:53 -07002824void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2825 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002826 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002827 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2828 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002829
John Zulauf355e49b2020-04-24 15:11:15 -06002830 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002831 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002832
2833 // Add the "finalLayout" transitions to external
2834 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002835 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2836 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2837 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002838 const auto &final_transitions = rp_state_->subpass_transitions.back();
2839 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002840 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002841 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002842 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002843 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002844 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002845 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002846 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002847 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002848 }
2849}
2850
John Zulauf06f6f1e2022-04-19 15:28:11 -06002851SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2852 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002853 SyncExecScope result;
2854 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002855 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002856 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002857 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2858 return result;
2859}
2860
Jeremy Gebben40a22942020-12-22 14:22:06 -07002861SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002862 SyncExecScope result;
2863 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002864 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2865 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002866 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2867 return result;
2868}
2869
2870SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
John Zulaufc523bf62021-02-16 08:20:34 -07002871 src_exec_scope = src;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002872 src_access_scope = 0;
John Zulaufc523bf62021-02-16 08:20:34 -07002873 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002874 dst_access_scope = 0;
2875}
2876
2877template <typename Barrier>
2878SyncBarrier::SyncBarrier(const Barrier &barrier, 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 = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002881 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002882 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2883}
2884
2885SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002886 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2887 if (barrier) {
2888 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002889 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002890 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002891
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002892 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002893 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002894 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2895
2896 } else {
2897 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002898 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002899 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2900
2901 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002902 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002903 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2904 }
2905}
2906
2907template <typename Barrier>
2908SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2909 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2910 src_exec_scope = src.exec_scope;
2911 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2912
2913 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002914 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002915 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002916}
2917
John Zulaufb02c1eb2020-10-06 16:33:36 -06002918// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2919void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002920 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002921 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002922 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002923 }
2924}
2925
John Zulauf89311b42020-09-29 16:28:47 -06002926// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2927// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2928// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002929void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002930 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002931 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002932 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002933 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002934 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002935 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002936 }
John Zulaufbb890452021-12-14 11:30:18 -07002937 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002938}
John Zulauf9cb530d2019-09-30 14:14:10 -06002939HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2940 HazardResult hazard;
2941 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002942 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002943 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002944 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002945 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002946 }
2947 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002948 // Write operation:
2949 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2950 // If reads exists -- test only against them because either:
2951 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2952 // * 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
2953 // the current write happens after the reads, so just test the write against the reades
2954 // Otherwise test against last_write
2955 //
2956 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002957 if (last_reads.size()) {
2958 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002959 if (IsReadHazard(usage_stage, read_access)) {
2960 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2961 break;
2962 }
2963 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002964 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002965 // Write-After-Write check -- if we have a previous write to test against
2966 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002967 }
2968 }
2969 return hazard;
2970}
2971
John Zulauf4fa68462021-04-26 21:04:22 -06002972HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002973 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf4fa68462021-04-26 21:04:22 -06002974 return DetectHazard(usage_index, ordering);
2975}
2976
2977HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering) const {
John Zulauf69133422020-05-20 14:55:53 -06002978 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2979 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002980 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002981 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002982 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2983 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002984 if (IsRead(usage_bit)) {
2985 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2986 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2987 if (is_raw_hazard) {
2988 // NOTE: we know last_write is non-zero
2989 // See if the ordering rules save us from the simple RAW check above
2990 // First check to see if the current usage is covered by the ordering rules
2991 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2992 const bool usage_is_ordered =
2993 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2994 if (usage_is_ordered) {
2995 // Now see of the most recent write (or a subsequent read) are ordered
2996 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
2997 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06002998 }
2999 }
John Zulauf4285ee92020-09-23 10:20:52 -06003000 if (is_raw_hazard) {
3001 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3002 }
John Zulauf5c628d02021-05-04 15:46:36 -06003003 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3004 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
3005 return DetectBarrierHazard(usage_index, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003006 } else {
3007 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003008 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003009 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003010 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003011 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003012 if (usage_write_is_ordered) {
3013 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
3014 ordered_stages = GetOrderedStages(ordering);
3015 }
3016 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3017 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003018 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003019 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3020 if (IsReadHazard(usage_stage, read_access)) {
3021 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3022 break;
3023 }
John Zulaufd14743a2020-07-03 09:42:39 -06003024 }
3025 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003026 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3027 bool ilt_ilt_hazard = false;
3028 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3029 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3030 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3031 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3032 }
3033 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003034 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003035 }
John Zulauf69133422020-05-20 14:55:53 -06003036 }
3037 }
3038 return hazard;
3039}
3040
John Zulaufae842002021-04-15 18:20:55 -06003041HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range) const {
3042 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003043 using Size = FirstAccesses::size_type;
3044 const auto &recorded_accesses = recorded_use.first_accesses_;
3045 Size count = recorded_accesses.size();
3046 if (count) {
3047 const auto &last_access = recorded_accesses.back();
3048 bool do_write_last = IsWrite(last_access.usage_index);
3049 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003050
John Zulauf4fa68462021-04-26 21:04:22 -06003051 for (Size i = 0; i < count; ++count) {
3052 const auto &first = recorded_accesses[i];
3053 // Skip and quit logic
3054 if (first.tag < tag_range.begin) continue;
3055 if (first.tag >= tag_range.end) {
3056 do_write_last = false; // ignore last since we know it can't be in tag_range
3057 break;
3058 }
3059
3060 hazard = DetectHazard(first.usage_index, first.ordering_rule);
3061 if (hazard.hazard) {
3062 hazard.AddRecordedAccess(first);
3063 break;
3064 }
3065 }
3066
3067 if (do_write_last && tag_range.includes(last_access.tag)) {
3068 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3069 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3070 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3071 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3072 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3073 // the barrier that applies them
3074 barrier |= recorded_use.first_write_layout_ordering_;
3075 }
3076 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3077 // the active context
3078 if (recorded_use.first_read_stages_) {
3079 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3080 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3081 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3082 // active context.
3083 barrier.exec_scope |= recorded_use.first_read_stages_;
3084 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3085 barrier.access_scope |= FlagBit(last_access.usage_index);
3086 }
3087 hazard = DetectHazard(last_access.usage_index, barrier);
3088 if (hazard.hazard) {
3089 hazard.AddRecordedAccess(last_access);
3090 }
3091 }
John Zulaufae842002021-04-15 18:20:55 -06003092 }
3093 return hazard;
3094}
3095
John Zulauf2f952d22020-02-10 11:34:51 -07003096// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003097HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003098 HazardResult hazard;
3099 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003100 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3101 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3102 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003103 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003104 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003105 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003106 }
3107 } else {
John Zulauf14940722021-04-12 15:19:02 -06003108 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003109 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003110 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003111 // 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 -07003112 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003113 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003114 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003115 break;
3116 }
3117 }
John Zulauf2f952d22020-02-10 11:34:51 -07003118 }
3119 }
3120 return hazard;
3121}
3122
John Zulaufae842002021-04-15 18:20:55 -06003123HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3124 ResourceUsageTag start_tag) const {
3125 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003126 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003127 // Skip and quit logic
3128 if (first.tag < tag_range.begin) continue;
3129 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003130
3131 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003132 if (hazard.hazard) {
3133 hazard.AddRecordedAccess(first);
3134 break;
3135 }
John Zulaufae842002021-04-15 18:20:55 -06003136 }
3137 return hazard;
3138}
3139
Jeremy Gebben40a22942020-12-22 14:22:06 -07003140HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003141 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003142 // Only supporting image layout transitions for now
3143 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3144 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003145 // only test for WAW if there no intervening read operations.
3146 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003147 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003148 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003149 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003150 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003151 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003152 break;
3153 }
3154 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003155 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3156 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3157 }
3158
3159 return hazard;
3160}
3161
Jeremy Gebben40a22942020-12-22 14:22:06 -07003162HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07003163 const SyncStageAccessFlags &src_access_scope,
John Zulauf14940722021-04-12 15:19:02 -06003164 const ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003165 // Only supporting image layout transitions for now
3166 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3167 HazardResult hazard;
3168 // only test for WAW if there no intervening read operations.
3169 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3170
John Zulaufab7756b2020-12-29 16:10:16 -07003171 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003172 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
3173 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07003174 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003175 if (read_access.tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003176 // The read is in the events first synchronization scope, so we use a barrier hazard check
3177 // If the read stage is not in the src sync scope
3178 // *AND* not execution chained with an existing sync barrier (that's the or)
3179 // then the barrier access is unsafe (R/W after R)
3180 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
3181 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3182 break;
3183 }
3184 } else {
3185 // The read not in the event first sync scope and so is a hazard vs. the layout transition
3186 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3187 }
3188 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003189 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003190 // 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 -06003191 if (write_tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003192 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3193 // So do a normal barrier hazard check
3194 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3195 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3196 }
3197 } else {
3198 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06003199 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3200 }
John Zulaufd14743a2020-07-03 09:42:39 -06003201 }
John Zulauf361fb532020-07-22 10:45:39 -06003202
John Zulauf0cb5be22020-01-23 12:18:22 -07003203 return hazard;
3204}
3205
John Zulauf5f13a792020-03-10 07:31:21 -06003206// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3207// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3208// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3209void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003210 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003211 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3212 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003213 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003214 } else if (other.write_tag == write_tag) {
3215 // 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 -06003216 // dependency chaining logic or any stage expansion)
3217 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003218 pending_write_barriers |= other.pending_write_barriers;
3219 pending_layout_transition |= other.pending_layout_transition;
3220 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003221 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003222
John Zulaufd14743a2020-07-03 09:42:39 -06003223 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003224 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003225 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003226 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003227 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003228 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003229 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003230 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3231 // but we should wait on profiling data for that.
3232 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003233 auto &my_read = last_reads[my_read_index];
3234 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003235 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003236 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003237 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003238 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003239 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003240 my_read.pending_dep_chain = other_read.pending_dep_chain;
3241 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3242 // May require tracking more than one access per stage.
3243 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003244 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003245 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003246 // Since I'm overwriting the fragement stage read, also update the input attachment info
3247 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003248 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003249 }
John Zulauf14940722021-04-12 15:19:02 -06003250 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003251 // The read tags match so merge the barriers
3252 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003253 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003254 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003255 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003256
John Zulauf5f13a792020-03-10 07:31:21 -06003257 break;
3258 }
3259 }
3260 } else {
3261 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003262 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003263 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003264 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003265 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003266 }
John Zulauf5f13a792020-03-10 07:31:21 -06003267 }
3268 }
John Zulauf361fb532020-07-22 10:45:39 -06003269 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003270 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3271 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003272
3273 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3274 // of the copy and other into this using the update first logic.
3275 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3276 // of the other first_accesses... )
3277 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3278 FirstAccesses firsts(std::move(first_accesses_));
3279 first_accesses_.clear();
3280 first_read_stages_ = 0U;
3281 auto a = firsts.begin();
3282 auto a_end = firsts.end();
3283 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003284 // TODO: Determine whether some tag offset will be needed for PHASE II
3285 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003286 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3287 ++a;
3288 }
3289 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3290 }
3291 for (; a != a_end; ++a) {
3292 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3293 }
3294 }
John Zulauf5f13a792020-03-10 07:31:21 -06003295}
3296
John Zulauf14940722021-04-12 15:19:02 -06003297void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003298 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3299 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003300 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003301 // Mulitple outstanding reads may be of interest and do dependency chains independently
3302 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3303 const auto usage_stage = PipelineStageBit(usage_index);
3304 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003305 for (auto &read_access : last_reads) {
3306 if (read_access.stage == usage_stage) {
3307 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003308 } else if (read_access.barriers & usage_stage) {
3309 read_access.sync_stages |= usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003310 }
3311 }
3312 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003313 for (auto &read_access : last_reads) {
3314 if (read_access.barriers & usage_stage) {
3315 read_access.sync_stages |= usage_stage;
3316 }
3317 }
John Zulaufab7756b2020-12-29 16:10:16 -07003318 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003319 last_read_stages |= usage_stage;
3320 }
John Zulauf4285ee92020-09-23 10:20:52 -06003321
3322 // 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 -07003323 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003324 // TODO Revisit re: multiple reads for a given stage
3325 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003326 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003327 } else {
3328 // Assume write
3329 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003330 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003331 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003332 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003333}
John Zulauf5f13a792020-03-10 07:31:21 -06003334
John Zulauf89311b42020-09-29 16:28:47 -06003335// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3336// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3337// We can overwrite them as *this* write is now after them.
3338//
3339// 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 -06003340void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003341 ClearRead();
3342 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003343 write_tag = tag;
3344 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003345}
3346
John Zulauf1d5f9c12022-05-13 14:51:08 -06003347void ResourceAccessState::ClearWrite() {
3348 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3349 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3350 write_barriers.reset();
3351 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3352 last_write.reset();
3353
3354 write_tag = 0;
3355 write_queue = QueueSyncState::kQueueIdInvalid;
3356}
3357
3358void ResourceAccessState::ClearRead() {
3359 last_reads.clear();
3360 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3361}
3362
John Zulauf89311b42020-09-29 16:28:47 -06003363// Apply the memory barrier without updating the existing barriers. The execution barrier
3364// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3365// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3366// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003367template <typename ScopeOps>
3368void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003369 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3370 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003371 // 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 -06003372 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003373 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3374 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003375 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003376 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003377 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003378 if (layout_transition) {
3379 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3380 }
John Zulaufa0a98292020-09-18 09:30:10 -06003381 }
John Zulauf89311b42020-09-29 16:28:47 -06003382 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3383 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003384
John Zulauf89311b42020-09-29 16:28:47 -06003385 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003386 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3387 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003388 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3389
John Zulaufab7756b2020-12-29 16:10:16 -07003390 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003391 // 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 -06003392 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003393 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3394 stages_in_scope |= read_access.stage;
3395 }
3396 }
3397
3398 for (auto &read_access : last_reads) {
3399 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3400 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3401 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3402 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003403 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003404 }
3405 }
John Zulaufa0a98292020-09-18 09:30:10 -06003406 }
John Zulaufa0a98292020-09-18 09:30:10 -06003407}
3408
John Zulauf14940722021-04-12 15:19:02 -06003409void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003410 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003411 // 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 -06003412 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003413 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003414 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3415 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003416 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003417 }
John Zulauf89311b42020-09-29 16:28:47 -06003418
3419 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003420 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003421 for (auto &read_access : last_reads) {
3422 read_access.barriers |= read_access.pending_dep_chain;
3423 read_execution_barriers |= read_access.barriers;
3424 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003425 }
3426
3427 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3428 write_dependency_chain |= pending_write_dep_chain;
3429 write_barriers |= pending_write_barriers;
3430 pending_write_dep_chain = 0;
3431 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003432}
3433
John Zulauf1d5f9c12022-05-13 14:51:08 -06003434bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3435 return (queue == usage_queue) && (tag <= usage_tag);
3436}
3437
3438bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3439
3440bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3441
3442// Return if the resulting state is "empty"
3443template <typename Pred>
3444bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3445 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3446
3447 // Use the predicate to build a mask of the read stages we are synchronizing
3448 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003449 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003450 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003451 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3452 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003453 }
3454 }
3455
John Zulauf434c4e62022-05-19 16:03:56 -06003456 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3457 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3458 uint32_t unsync_count = 0;
3459 for (auto &read_access : last_reads) {
3460 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3461 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3462 sync_reads |= read_access.stage;
3463 } else {
3464 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003465 }
3466 }
3467
3468 if (unsync_count) {
3469 if (sync_reads) {
3470 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3471 ReadStates unsync_reads;
3472 unsync_reads.reserve(unsync_count);
3473 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3474 for (auto &read_access : last_reads) {
3475 if (0 == (read_access.stage & sync_reads)) {
3476 unsync_reads.emplace_back(read_access);
3477 unsync_read_stages |= read_access.stage;
3478 }
3479 }
3480 last_read_stages = unsync_read_stages;
3481 last_reads = std::move(unsync_reads);
3482 }
3483 } else {
3484 // Nothing remains (or it was empty to begin with)
3485 ClearRead();
3486 }
3487
3488 bool all_clear = last_reads.size() == 0;
3489 if (last_write.any()) {
3490 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3491 // Clear any predicated write, or any the write from any any access with synchronized reads.
3492 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3493 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3494 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3495 ClearWrite();
3496 } else {
3497 all_clear = false;
3498 }
3499 }
3500 return all_clear;
3501}
3502
John Zulaufae842002021-04-15 18:20:55 -06003503bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3504 if (!first_accesses_.size()) return false;
3505 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3506 return tag_range.intersects(first_access_range);
3507}
3508
John Zulauf1d5f9c12022-05-13 14:51:08 -06003509void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3510 if (last_write.any()) write_tag += offset;
3511 for (auto &read_access : last_reads) {
3512 read_access.tag += offset;
3513 }
3514 for (auto &first : first_accesses_) {
3515 first.tag += offset;
3516 }
3517}
3518
3519ResourceAccessState::ResourceAccessState()
3520 : write_barriers(~SyncStageAccessFlags(0)),
3521 write_dependency_chain(0),
3522 write_tag(),
3523 write_queue(QueueSyncState::kQueueIdInvalid),
3524 last_write(0),
3525 input_attachment_read(false),
3526 last_read_stages(0),
3527 read_execution_barriers(0),
3528 pending_write_dep_chain(0),
3529 pending_layout_transition(false),
3530 pending_write_barriers(0),
3531 pending_layout_ordering_(),
3532 first_accesses_(),
3533 first_read_stages_(0U),
3534 first_write_layout_ordering_() {}
3535
John Zulauf59e25072020-07-17 10:55:21 -06003536// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003537VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3538 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003539
John Zulaufab7756b2020-12-29 16:10:16 -07003540 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003541 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003542 barriers = read_access.barriers;
3543 break;
John Zulauf59e25072020-07-17 10:55:21 -06003544 }
3545 }
John Zulauf4285ee92020-09-23 10:20:52 -06003546
John Zulauf59e25072020-07-17 10:55:21 -06003547 return barriers;
3548}
3549
John Zulauf1d5f9c12022-05-13 14:51:08 -06003550void ResourceAccessState::SetQueueId(QueueId id) {
3551 for (auto &read_access : last_reads) {
3552 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3553 read_access.queue = id;
3554 }
3555 }
3556 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3557 write_queue = id;
3558 }
3559}
3560
John Zulauf00119522022-05-23 19:07:42 -06003561bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3562 return 0 != (write_dependency_chain & src_exec_scope);
3563}
3564
3565bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3566 return (src_access_scope & last_write).any();
3567}
3568
John Zulaufb7578302022-05-19 13:50:18 -06003569bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3570 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003571 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3572}
3573
3574bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3575 SyncStageAccessFlags src_access_scope) const {
3576 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003577}
3578
3579bool ResourceAccessState::WriteInEventScope(const SyncStageAccessFlags &src_access_scope, ResourceUsageTag scope_tag) const {
3580 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3581 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3582 // in order to know if it's in the excecution scope
John Zulauf00119522022-05-23 19:07:42 -06003583 return (write_tag < scope_tag) && WriteInScope(src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003584}
3585
John Zulaufcb7e1672022-05-04 13:46:08 -06003586bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003587 assert(IsRead(usage));
3588 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3589 // * the previous reads are not hazards, and thus last_write must be visible and available to
3590 // any reads that happen after.
3591 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3592 // 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 -07003593 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003594}
3595
Jeremy Gebben40a22942020-12-22 14:22:06 -07003596VkPipelineStageFlags2KHR ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003597 // Whether the stage are in the ordering scope only matters if the current write is ordered
Jeremy Gebben40a22942020-12-22 14:22:06 -07003598 VkPipelineStageFlags2KHR ordered_stages = last_read_stages & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003599 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003600 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003601 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003602 // 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 -07003603 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003604 }
3605
3606 return ordered_stages;
3607}
3608
John Zulauf14940722021-04-12 15:19:02 -06003609void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003610 // Only record until we record a write.
3611 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003612 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003613 if (0 == (usage_stage & first_read_stages_)) {
3614 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003615 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003616 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003617 if (0 == (read_execution_barriers & usage_stage)) {
3618 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3619 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3620 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003621 }
3622 }
3623}
3624
John Zulauf4fa68462021-04-26 21:04:22 -06003625void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3626 // Only call this after recording an image layout transition
3627 assert(first_accesses_.size());
3628 if (first_accesses_.back().tag == tag) {
3629 // 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 +02003630 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003631 first_write_layout_ordering_ = layout_ordering;
3632 }
3633}
3634
John Zulauf1d5f9c12022-05-13 14:51:08 -06003635ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3636 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3637 : stage(stage_),
3638 access(access_),
3639 barriers(barriers_),
3640 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3641 tag(tag_),
3642 queue(QueueSyncState::kQueueIdInvalid),
3643 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3644
John Zulaufee984022022-04-13 16:39:50 -06003645void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3646 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3647 stage = stage_;
3648 access = access_;
3649 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003650 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003651 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003652 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 -06003653}
3654
John Zulauf00119522022-05-23 19:07:42 -06003655// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3656// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3657// that have bee applied (via semaphore) to those accesses can be chained off of.
3658bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3659 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3660 return (exec_scope & effective_stages) != 0;
3661}
3662
John Zulauf697c0e12022-04-19 16:31:12 -06003663ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3664 ResourceUsageRange reserve;
3665 reserve.begin = tag_limit_.fetch_add(tag_count);
3666 reserve.end = reserve.begin + tag_count;
3667 return reserve;
3668}
3669
John Zulaufbbda4572022-04-19 16:20:45 -06003670const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3671 return GetMappedPlainFromShared(queue_sync_states_, queue);
3672}
3673
3674QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3675
3676std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3677 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3678}
3679
3680std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3681 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3682}
3683
John Zulauf1d5f9c12022-05-13 14:51:08 -06003684template <typename BatchSet, typename Predicate>
3685static BatchSet GetQueueLastBatchSnapshotImpl(const SyncValidator::QueueSyncStatesMap &queues, Predicate &&pred) {
3686 BatchSet snapshot;
3687 for (auto &queue : queues) {
John Zulauf697c0e12022-04-19 16:31:12 -06003688 auto batch = queue.second->LastBatch();
John Zulauf1d5f9c12022-05-13 14:51:08 -06003689 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003690 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003691 return snapshot;
3692}
3693
3694template <typename Predicate>
3695QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
3696 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::ConstBatchSet, Predicate>(queue_sync_states_,
3697 std::forward<Predicate>(pred));
3698}
3699
3700template <typename Predicate>
3701QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
3702 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::BatchSet, Predicate>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf697c0e12022-04-19 16:31:12 -06003703}
3704
John Zulaufcb7e1672022-05-04 13:46:08 -06003705bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3706 const std::shared_ptr<QueueBatchContext> &batch,
3707 const VkSemaphoreSubmitInfo &signal_info) {
3708 const SyncExecScope exec_scope =
3709 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3710 const VkSemaphore sem = sem_state->semaphore();
3711 auto signal_it = signaled_.find(sem);
3712 std::shared_ptr<Signal> insert_signal;
3713 if (signal_it == signaled_.end()) {
3714 if (prev_) {
3715 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3716 if (prev_sig) {
3717 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3718 insert_signal = std::make_shared<Signal>(*prev_sig);
3719 }
3720 }
3721 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3722 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003723 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003724
3725 bool success = false;
3726 if (!signal_it->second) {
3727 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3728 success = true;
3729 }
3730
3731 return success;
3732}
3733
3734std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3735 std::shared_ptr<Signal> unsignaled;
3736 const auto found_it = signaled_.find(sem);
3737 if (found_it != signaled_.end()) {
3738 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3739 // a bit.
3740 unsignaled = std::move(found_it->second);
3741 if (!prev_) {
3742 // No parent, not need to keep the entry
3743 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3744 signaled_.erase(found_it);
3745 }
3746 } else if (prev_) {
3747 // We can't unsignal prev_ because it's const * by design.
3748 // We put in an empty placeholder
3749 signaled_.emplace(sem, std::shared_ptr<Signal>());
3750 unsignaled = GetPrev(sem);
3751 }
3752 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3753 // but CoreChecks should have reported it
3754
3755 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003756 return unsignaled;
3757}
3758
John Zulaufcb7e1672022-05-04 13:46:08 -06003759void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3760 // Overwrite the s tate with the last state from this
3761 if (from) {
3762 assert(sem == from->sem_state->semaphore());
3763 signaled_[sem] = std::move(from);
3764 } else {
3765 signaled_.erase(sem);
3766 }
3767}
3768
3769void SignaledSemaphores::Reset() {
3770 signaled_.clear();
3771 prev_ = nullptr;
3772}
3773
John Zulaufea943c52022-02-22 11:05:17 -07003774std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3775 // If we don't have one, make it.
3776 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3777 assert(cb_state.get());
3778 auto queue_flags = cb_state->GetQueueFlags();
3779 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3780}
3781
John Zulaufcb7e1672022-05-04 13:46:08 -06003782std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003783 return GetMappedInsert(cb_access_state, command_buffer,
3784 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3785}
3786
3787std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3788 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3789}
3790
3791const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3792 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3793}
3794
3795CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3796 return GetAccessContextShared(command_buffer).get();
3797}
3798
3799CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3800 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3801}
3802
John Zulaufd1f85d42020-04-15 12:23:15 -06003803void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003804 auto *access_context = GetAccessContextNoInsert(command_buffer);
3805 if (access_context) {
3806 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003807 }
3808}
3809
John Zulaufd1f85d42020-04-15 12:23:15 -06003810void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3811 auto access_found = cb_access_state.find(command_buffer);
3812 if (access_found != cb_access_state.end()) {
3813 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003814 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003815 cb_access_state.erase(access_found);
3816 }
3817}
3818
John Zulauf9cb530d2019-09-30 14:14:10 -06003819bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3820 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3821 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003822 const auto *cb_context = GetAccessContext(commandBuffer);
3823 assert(cb_context);
3824 if (!cb_context) return skip;
3825 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003826
John Zulauf3d84f1b2020-03-09 13:33:25 -06003827 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003828 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3829 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003830
3831 for (uint32_t region = 0; region < regionCount; region++) {
3832 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003833 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003834 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003835 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003836 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003837 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003838 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003839 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003840 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003841 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003842 }
John Zulauf16adfc92020-04-08 10:28:33 -06003843 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003844 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003845 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003846 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003847 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003848 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003849 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003850 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003851 }
3852 }
3853 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003854 }
3855 return skip;
3856}
3857
3858void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3859 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003860 auto *cb_context = GetAccessContext(commandBuffer);
3861 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003862 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003863 auto *context = cb_context->GetCurrentAccessContext();
3864
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003865 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3866 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003867
3868 for (uint32_t region = 0; region < regionCount; region++) {
3869 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003870 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003871 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003872 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003873 }
John Zulauf16adfc92020-04-08 10:28:33 -06003874 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003875 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003876 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003877 }
3878 }
3879}
3880
John Zulauf4a6105a2020-11-17 15:11:05 -07003881void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3882 // Clear out events from the command buffer contexts
3883 for (auto &cb_context : cb_access_state) {
3884 cb_context.second->RecordDestroyEvent(event);
3885 }
3886}
3887
Tony-LunarGef035472021-11-02 10:23:33 -06003888bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
3889 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04003890 bool skip = false;
3891 const auto *cb_context = GetAccessContext(commandBuffer);
3892 assert(cb_context);
3893 if (!cb_context) return skip;
3894 const auto *context = cb_context->GetCurrentAccessContext();
Tony-LunarGef035472021-11-02 10:23:33 -06003895 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04003896
3897 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003898 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3899 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003900
3901 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3902 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3903 if (src_buffer) {
3904 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003905 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003906 if (hazard.hazard) {
3907 // TODO -- add tag information to log msg when useful.
3908 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
Tony-LunarGef035472021-11-02 10:23:33 -06003909 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04003910 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06003911 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003912 }
3913 }
3914 if (dst_buffer && !skip) {
3915 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003916 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003917 if (hazard.hazard) {
3918 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
Tony-LunarGef035472021-11-02 10:23:33 -06003919 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04003920 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06003921 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003922 }
3923 }
3924 if (skip) break;
3925 }
3926 return skip;
3927}
3928
Tony-LunarGef035472021-11-02 10:23:33 -06003929bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3930 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3931 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3932}
3933
3934bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
3935 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3936}
3937
3938void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04003939 auto *cb_context = GetAccessContext(commandBuffer);
3940 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06003941 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04003942 auto *context = cb_context->GetCurrentAccessContext();
3943
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003944 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3945 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003946
3947 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3948 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3949 if (src_buffer) {
3950 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003951 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003952 }
3953 if (dst_buffer) {
3954 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003955 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003956 }
3957 }
3958}
3959
Tony-LunarGef035472021-11-02 10:23:33 -06003960void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3961 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3962}
3963
3964void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
3965 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3966}
3967
John Zulauf5c5e88d2019-12-26 11:22:02 -07003968bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3969 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3970 const VkImageCopy *pRegions) const {
3971 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003972 const auto *cb_access_context = GetAccessContext(commandBuffer);
3973 assert(cb_access_context);
3974 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003975
John Zulauf3d84f1b2020-03-09 13:33:25 -06003976 const auto *context = cb_access_context->GetCurrentAccessContext();
3977 assert(context);
3978 if (!context) return skip;
3979
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003980 auto src_image = Get<IMAGE_STATE>(srcImage);
3981 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003982 for (uint32_t region = 0; region < regionCount; region++) {
3983 const auto &copy_region = pRegions[region];
3984 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003985 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
John Zulauf3d84f1b2020-03-09 13:33:25 -06003986 copy_region.srcOffset, copy_region.extent);
3987 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003988 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003989 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003990 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003991 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003992 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003993 }
3994
3995 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003996 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
ziga-lunarg73746512022-03-23 23:08:17 +01003997 copy_region.dstOffset, copy_region.extent);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003998 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003999 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004000 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004001 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004002 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004003 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004004 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004005 }
4006 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004007
John Zulauf5c5e88d2019-12-26 11:22:02 -07004008 return skip;
4009}
4010
4011void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4012 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4013 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004014 auto *cb_access_context = GetAccessContext(commandBuffer);
4015 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004016 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004017 auto *context = cb_access_context->GetCurrentAccessContext();
4018 assert(context);
4019
Jeremy Gebben9f537102021-10-05 16:37:12 -06004020 auto src_image = Get<IMAGE_STATE>(srcImage);
4021 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004022
4023 for (uint32_t region = 0; region < regionCount; region++) {
4024 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004025 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004026 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004027 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004028 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004029 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004030 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004031 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004032 }
4033 }
4034}
4035
Tony-LunarGb61514a2021-11-02 12:36:51 -06004036bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4037 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004038 bool skip = false;
4039 const auto *cb_access_context = GetAccessContext(commandBuffer);
4040 assert(cb_access_context);
4041 if (!cb_access_context) return skip;
4042
4043 const auto *context = cb_access_context->GetCurrentAccessContext();
4044 assert(context);
4045 if (!context) return skip;
4046
Tony-LunarGb61514a2021-11-02 12:36:51 -06004047 const char *func_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004048 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4049 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004050
Jeff Leger178b1e52020-10-05 12:22:23 -04004051 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4052 const auto &copy_region = pCopyImageInfo->pRegions[region];
4053 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004054 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Jeff Leger178b1e52020-10-05 12:22:23 -04004055 copy_region.srcOffset, copy_region.extent);
4056 if (hazard.hazard) {
4057 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sfricke-samsung71f04e32022-03-16 01:21:21 -05004058 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04004059 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004060 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004061 }
4062 }
4063
4064 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004065 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
ziga-lunarg73746512022-03-23 23:08:17 +01004066 copy_region.dstOffset, copy_region.extent);
Jeff Leger178b1e52020-10-05 12:22:23 -04004067 if (hazard.hazard) {
4068 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sfricke-samsung71f04e32022-03-16 01:21:21 -05004069 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04004070 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004071 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004072 }
4073 if (skip) break;
4074 }
4075 }
4076
4077 return skip;
4078}
4079
Tony-LunarGb61514a2021-11-02 12:36:51 -06004080bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4081 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4082 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4083}
4084
4085bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4086 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4087}
4088
4089void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004090 auto *cb_access_context = GetAccessContext(commandBuffer);
4091 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004092 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004093 auto *context = cb_access_context->GetCurrentAccessContext();
4094 assert(context);
4095
Jeremy Gebben9f537102021-10-05 16:37:12 -06004096 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4097 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004098
4099 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4100 const auto &copy_region = pCopyImageInfo->pRegions[region];
4101 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004102 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004103 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004104 }
4105 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004106 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004107 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004108 }
4109 }
4110}
4111
Tony-LunarGb61514a2021-11-02 12:36:51 -06004112void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4113 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4114}
4115
4116void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4117 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4118}
4119
John Zulauf9cb530d2019-09-30 14:14:10 -06004120bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4121 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4122 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4123 uint32_t bufferMemoryBarrierCount,
4124 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4125 uint32_t imageMemoryBarrierCount,
4126 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4127 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004128 const auto *cb_access_context = GetAccessContext(commandBuffer);
4129 assert(cb_access_context);
4130 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004131
John Zulauf36ef9282021-02-02 11:47:24 -07004132 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4133 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4134 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4135 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004136 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004137 return skip;
4138}
4139
4140void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4141 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4142 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4143 uint32_t bufferMemoryBarrierCount,
4144 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4145 uint32_t imageMemoryBarrierCount,
4146 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004147 auto *cb_access_context = GetAccessContext(commandBuffer);
4148 assert(cb_access_context);
4149 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004150
John Zulauf1bf30522021-09-03 15:39:06 -06004151 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4152 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4153 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4154 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004155}
4156
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004157bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4158 const VkDependencyInfoKHR *pDependencyInfo) const {
4159 bool skip = false;
4160 const auto *cb_access_context = GetAccessContext(commandBuffer);
4161 assert(cb_access_context);
4162 if (!cb_access_context) return skip;
4163
4164 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4165 skip = pipeline_barrier.Validate(*cb_access_context);
4166 return skip;
4167}
4168
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004169bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4170 const VkDependencyInfo *pDependencyInfo) const {
4171 bool skip = false;
4172 const auto *cb_access_context = GetAccessContext(commandBuffer);
4173 assert(cb_access_context);
4174 if (!cb_access_context) return skip;
4175
4176 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4177 skip = pipeline_barrier.Validate(*cb_access_context);
4178 return skip;
4179}
4180
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004181void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4182 auto *cb_access_context = GetAccessContext(commandBuffer);
4183 assert(cb_access_context);
4184 if (!cb_access_context) return;
4185
John Zulauf1bf30522021-09-03 15:39:06 -06004186 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4187 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004188}
4189
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004190void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4191 auto *cb_access_context = GetAccessContext(commandBuffer);
4192 assert(cb_access_context);
4193 if (!cb_access_context) return;
4194
4195 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4196 *pDependencyInfo);
4197}
4198
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004199void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004200 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004201 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004202
John Zulauf5f13a792020-03-10 07:31:21 -06004203 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4204 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004205 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004206 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4207 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004208
John Zulauf1d5f9c12022-05-13 14:51:08 -06004209 QueueId queue_id = QueueSyncState::kQueueIdBase;
4210 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004211 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004212 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004213 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4214 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004215}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004216
John Zulauf355e49b2020-04-24 15:11:15 -06004217bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07004218 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004219 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004220 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004221 if (cb_context) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004222 SyncOpBeginRenderPass sync_op(cmd, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004223 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004224 }
John Zulauf355e49b2020-04-24 15:11:15 -06004225 return skip;
4226}
4227
4228bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4229 VkSubpassContents contents) const {
4230 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004231 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004232 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004233 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004234 return skip;
4235}
4236
4237bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004238 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004239 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004240 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004241 return skip;
4242}
4243
4244bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4245 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::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004248 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004249 return skip;
4250}
4251
John Zulauf3d84f1b2020-03-09 13:33:25 -06004252void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4253 VkResult result) {
4254 // The state tracker sets up the command buffer state
4255 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4256
4257 // Create/initialize the structure that trackers accesses at the command buffer scope.
4258 auto cb_access_context = GetAccessContext(commandBuffer);
4259 assert(cb_access_context);
4260 cb_access_context->Reset();
4261}
4262
4263void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07004264 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004265 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004266 if (cb_context) {
John Zulaufbb890452021-12-14 11:30:18 -07004267 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004268 }
4269}
4270
4271void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4272 VkSubpassContents contents) {
4273 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004274 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004275 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004276 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004277}
4278
4279void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4280 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4281 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004282 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004283}
4284
4285void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4286 const VkRenderPassBeginInfo *pRenderPassBegin,
4287 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4288 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004289 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004290}
4291
Mike Schuchardt2df08912020-12-15 16:28:09 -08004292bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07004293 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004294 bool skip = false;
4295
4296 auto cb_context = GetAccessContext(commandBuffer);
4297 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004298 if (!cb_context) return skip;
sfricke-samsung85584a72021-09-30 21:43:38 -07004299 SyncOpNextSubpass sync_op(cmd, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004300 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004301}
4302
4303bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4304 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004305 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004306 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004307 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004308 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4309 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004310 return skip;
4311}
4312
Mike Schuchardt2df08912020-12-15 16:28:09 -08004313bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4314 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004315 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004316 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004317 return skip;
4318}
4319
4320bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4321 const VkSubpassEndInfo *pSubpassEndInfo) const {
4322 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004323 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004324 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004325}
4326
4327void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07004328 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004329 auto cb_context = GetAccessContext(commandBuffer);
4330 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004331 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004332
John Zulaufbb890452021-12-14 11:30:18 -07004333 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004334}
4335
4336void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4337 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004338 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004339 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004340 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004341}
4342
4343void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4344 const VkSubpassEndInfo *pSubpassEndInfo) {
4345 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004346 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004347}
4348
4349void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4350 const VkSubpassEndInfo *pSubpassEndInfo) {
4351 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004352 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004353}
4354
sfricke-samsung85584a72021-09-30 21:43:38 -07004355bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4356 CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004357 bool skip = false;
4358
4359 auto cb_context = GetAccessContext(commandBuffer);
4360 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004361 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004362
sfricke-samsung85584a72021-09-30 21:43:38 -07004363 SyncOpEndRenderPass sync_op(cmd, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004364 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004365 return skip;
4366}
4367
4368bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4369 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004370 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004371 return skip;
4372}
4373
Mike Schuchardt2df08912020-12-15 16:28:09 -08004374bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004375 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004376 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004377 return skip;
4378}
4379
4380bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004381 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004382 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004383 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004384 return skip;
4385}
4386
sfricke-samsung85584a72021-09-30 21:43:38 -07004387void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004388 // Resolve the all subpass contexts to the command buffer contexts
4389 auto cb_context = GetAccessContext(commandBuffer);
4390 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004391 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004392
John Zulaufbb890452021-12-14 11:30:18 -07004393 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004394}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004395
John Zulauf33fc1d52020-07-17 11:01:10 -06004396// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4397// updates to a resource which do not conflict at the byte level.
4398// TODO: Revisit this rule to see if it needs to be tighter or looser
4399// TODO: Add programatic control over suppression heuristics
4400bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4401 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4402}
4403
John Zulauf3d84f1b2020-03-09 13:33:25 -06004404void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004405 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004406 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004407}
4408
4409void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004410 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004411 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004412}
4413
4414void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004415 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004416 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004417}
locke-lunarga19c71d2020-03-02 18:17:04 -07004418
sfricke-samsung71f04e32022-03-16 01:21:21 -05004419template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004420bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004421 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4422 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004423 bool skip = false;
4424 const auto *cb_access_context = GetAccessContext(commandBuffer);
4425 assert(cb_access_context);
4426 if (!cb_access_context) return skip;
4427
Tony Barbour845d29b2021-11-09 11:43:14 -07004428 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004429
locke-lunarga19c71d2020-03-02 18:17:04 -07004430 const auto *context = cb_access_context->GetCurrentAccessContext();
4431 assert(context);
4432 if (!context) return skip;
4433
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004434 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4435 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004436
4437 for (uint32_t region = 0; region < regionCount; region++) {
4438 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004439 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004440 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004441 if (src_buffer) {
4442 ResourceAccessRange src_range =
4443 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004444 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004445 if (hazard.hazard) {
4446 // PHASE1 TODO -- add tag information to log msg when useful.
4447 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4448 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
4449 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004450 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004451 }
4452 }
4453
Jeremy Gebben40a22942020-12-22 14:22:06 -07004454 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
John Zulauf477700e2021-01-06 11:41:49 -07004455 copy_region.imageOffset, copy_region.imageExtent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004456 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004457 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004458 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004459 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004460 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004461 }
4462 if (skip) break;
4463 }
4464 if (skip) break;
4465 }
4466 return skip;
4467}
4468
Jeff Leger178b1e52020-10-05 12:22:23 -04004469bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4470 VkImageLayout dstImageLayout, uint32_t regionCount,
4471 const VkBufferImageCopy *pRegions) const {
4472 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004473 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004474}
4475
4476bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4477 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4478 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4479 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004480 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4481}
4482
4483bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4484 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4485 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4486 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4487 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004488}
4489
sfricke-samsung71f04e32022-03-16 01:21:21 -05004490template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004491void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004492 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4493 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004494 auto *cb_access_context = GetAccessContext(commandBuffer);
4495 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004496
Jeff Leger178b1e52020-10-05 12:22:23 -04004497 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004498 auto *context = cb_access_context->GetCurrentAccessContext();
4499 assert(context);
4500
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004501 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4502 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004503
4504 for (uint32_t region = 0; region < regionCount; region++) {
4505 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004506 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004507 if (src_buffer) {
4508 ResourceAccessRange src_range =
4509 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004510 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004511 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004512 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004513 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004514 }
4515 }
4516}
4517
Jeff Leger178b1e52020-10-05 12:22:23 -04004518void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4519 VkImageLayout dstImageLayout, uint32_t regionCount,
4520 const VkBufferImageCopy *pRegions) {
4521 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004522 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004523}
4524
4525void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4526 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4527 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4528 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4529 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004530 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4531}
4532
4533void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4534 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4535 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4536 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4537 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4538 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004539}
4540
sfricke-samsung71f04e32022-03-16 01:21:21 -05004541template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004542bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004543 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4544 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004545 bool skip = false;
4546 const auto *cb_access_context = GetAccessContext(commandBuffer);
4547 assert(cb_access_context);
4548 if (!cb_access_context) return skip;
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004549 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004550
locke-lunarga19c71d2020-03-02 18:17:04 -07004551 const auto *context = cb_access_context->GetCurrentAccessContext();
4552 assert(context);
4553 if (!context) return skip;
4554
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004555 auto src_image = Get<IMAGE_STATE>(srcImage);
4556 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004557 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004558 for (uint32_t region = 0; region < regionCount; region++) {
4559 const auto &copy_region = pRegions[region];
4560 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004561 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
locke-lunarga19c71d2020-03-02 18:17:04 -07004562 copy_region.imageOffset, copy_region.imageExtent);
4563 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004564 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004565 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004566 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004567 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004568 }
John Zulauf477700e2021-01-06 11:41:49 -07004569 if (dst_mem) {
4570 ResourceAccessRange dst_range =
4571 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004572 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004573 if (hazard.hazard) {
4574 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4575 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
4576 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004577 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004578 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004579 }
4580 }
4581 if (skip) break;
4582 }
4583 return skip;
4584}
4585
Jeff Leger178b1e52020-10-05 12:22:23 -04004586bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4587 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4588 const VkBufferImageCopy *pRegions) const {
4589 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004590 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004591}
4592
4593bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4594 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4595 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4596 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004597 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4598}
4599
4600bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4601 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4602 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4603 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4604 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004605}
4606
sfricke-samsung71f04e32022-03-16 01:21:21 -05004607template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004608void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004609 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004610 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004611 auto *cb_access_context = GetAccessContext(commandBuffer);
4612 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004613
Jeff Leger178b1e52020-10-05 12:22:23 -04004614 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004615 auto *context = cb_access_context->GetCurrentAccessContext();
4616 assert(context);
4617
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004618 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004619 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004620 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004621 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004622
4623 for (uint32_t region = 0; region < regionCount; region++) {
4624 const auto &copy_region = pRegions[region];
4625 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004626 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004627 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004628 if (dst_buffer) {
4629 ResourceAccessRange dst_range =
4630 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004631 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004632 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004633 }
4634 }
4635}
4636
Jeff Leger178b1e52020-10-05 12:22:23 -04004637void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4638 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4639 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004640 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004641}
4642
4643void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4644 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4645 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4646 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4647 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004648 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4649}
4650
4651void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4652 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4653 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4654 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4655 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4656 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004657}
4658
4659template <typename RegionType>
4660bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4661 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4662 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004663 bool skip = false;
4664 const auto *cb_access_context = GetAccessContext(commandBuffer);
4665 assert(cb_access_context);
4666 if (!cb_access_context) return skip;
4667
4668 const auto *context = cb_access_context->GetCurrentAccessContext();
4669 assert(context);
4670 if (!context) return skip;
4671
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004672 auto src_image = Get<IMAGE_STATE>(srcImage);
4673 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004674
4675 for (uint32_t region = 0; region < regionCount; region++) {
4676 const auto &blit_region = pRegions[region];
4677 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004678 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4679 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4680 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4681 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4682 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4683 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004684 auto hazard = context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004685 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004686 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004687 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004688 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004689 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004690 }
4691 }
4692
4693 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004694 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4695 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4696 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4697 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4698 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4699 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004700 auto hazard = context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent);
locke-lunarga19c71d2020-03-02 18:17:04 -07004701 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004702 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004703 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004704 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004705 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004706 }
4707 if (skip) break;
4708 }
4709 }
4710
4711 return skip;
4712}
4713
Jeff Leger178b1e52020-10-05 12:22:23 -04004714bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4715 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4716 const VkImageBlit *pRegions, VkFilter filter) const {
4717 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4718 "vkCmdBlitImage");
4719}
4720
4721bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4722 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4723 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4724 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4725 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4726}
4727
Tony-LunarG542ae912021-11-04 16:06:44 -06004728bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4729 const VkBlitImageInfo2 *pBlitImageInfo) const {
4730 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4731 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4732 pBlitImageInfo->filter, "vkCmdBlitImage2");
4733}
4734
Jeff Leger178b1e52020-10-05 12:22:23 -04004735template <typename RegionType>
4736void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4737 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4738 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004739 auto *cb_access_context = GetAccessContext(commandBuffer);
4740 assert(cb_access_context);
4741 auto *context = cb_access_context->GetCurrentAccessContext();
4742 assert(context);
4743
Jeremy Gebben9f537102021-10-05 16:37:12 -06004744 auto src_image = Get<IMAGE_STATE>(srcImage);
4745 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004746
4747 for (uint32_t region = 0; region < regionCount; region++) {
4748 const auto &blit_region = pRegions[region];
4749 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004750 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4751 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4752 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4753 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4754 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4755 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004756 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004757 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004758 }
4759 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004760 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4761 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4762 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4763 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4764 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4765 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004766 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004767 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004768 }
4769 }
4770}
locke-lunarg36ba2592020-04-03 09:42:04 -06004771
Jeff Leger178b1e52020-10-05 12:22:23 -04004772void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4773 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4774 const VkImageBlit *pRegions, VkFilter filter) {
4775 auto *cb_access_context = GetAccessContext(commandBuffer);
4776 assert(cb_access_context);
4777 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4778 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4779 pRegions, filter);
4780 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4781}
4782
4783void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4784 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4785 auto *cb_access_context = GetAccessContext(commandBuffer);
4786 assert(cb_access_context);
4787 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4788 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4789 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4790 pBlitImageInfo->filter, tag);
4791}
4792
Tony-LunarG542ae912021-11-04 16:06:44 -06004793void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4794 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4795 auto *cb_access_context = GetAccessContext(commandBuffer);
4796 assert(cb_access_context);
4797 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4798 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4799 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4800 pBlitImageInfo->filter, tag);
4801}
4802
John Zulauffaea0ee2021-01-14 14:01:32 -07004803bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4804 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4805 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
4806 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004807 bool skip = false;
4808 if (drawCount == 0) return skip;
4809
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004810 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004811 VkDeviceSize size = struct_size;
4812 if (drawCount == 1 || stride == size) {
4813 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004814 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004815 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4816 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004817 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004818 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004819 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004820 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004821 }
4822 } else {
4823 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004824 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004825 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4826 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004827 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004828 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4829 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004830 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004831 break;
4832 }
4833 }
4834 }
4835 return skip;
4836}
4837
John Zulauf14940722021-04-12 15:19:02 -06004838void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004839 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4840 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004841 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004842 VkDeviceSize size = struct_size;
4843 if (drawCount == 1 || stride == size) {
4844 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004845 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004846 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004847 } else {
4848 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004849 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004850 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4851 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004852 }
4853 }
4854}
4855
John Zulauffaea0ee2021-01-14 14:01:32 -07004856bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4857 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4858 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004859 bool skip = false;
4860
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004861 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004862 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004863 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4864 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004865 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004866 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004867 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004868 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004869 }
4870 return skip;
4871}
4872
John Zulauf14940722021-04-12 15:19:02 -06004873void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
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);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004876 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004877}
4878
locke-lunarg36ba2592020-04-03 09:42:04 -06004879bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004880 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004881 const auto *cb_access_context = GetAccessContext(commandBuffer);
4882 assert(cb_access_context);
4883 if (!cb_access_context) return skip;
4884
locke-lunarg61870c22020-06-09 14:51:50 -06004885 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004886 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004887}
4888
4889void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004890 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004891 auto *cb_access_context = GetAccessContext(commandBuffer);
4892 assert(cb_access_context);
4893 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004894
locke-lunarg61870c22020-06-09 14:51:50 -06004895 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004896}
locke-lunarge1a67022020-04-29 00:15:36 -06004897
4898bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004899 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004900 const auto *cb_access_context = GetAccessContext(commandBuffer);
4901 assert(cb_access_context);
4902 if (!cb_access_context) return skip;
4903
4904 const auto *context = cb_access_context->GetCurrentAccessContext();
4905 assert(context);
4906 if (!context) return skip;
4907
locke-lunarg61870c22020-06-09 14:51:50 -06004908 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004909 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
4910 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004911 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004912}
4913
4914void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004915 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004916 auto *cb_access_context = GetAccessContext(commandBuffer);
4917 assert(cb_access_context);
4918 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4919 auto *context = cb_access_context->GetCurrentAccessContext();
4920 assert(context);
4921
locke-lunarg61870c22020-06-09 14:51:50 -06004922 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4923 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004924}
4925
4926bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4927 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004928 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004929 const auto *cb_access_context = GetAccessContext(commandBuffer);
4930 assert(cb_access_context);
4931 if (!cb_access_context) return skip;
4932
locke-lunarg61870c22020-06-09 14:51:50 -06004933 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4934 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4935 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004936 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004937}
4938
4939void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4940 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004941 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004942 auto *cb_access_context = GetAccessContext(commandBuffer);
4943 assert(cb_access_context);
4944 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004945
locke-lunarg61870c22020-06-09 14:51:50 -06004946 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4947 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4948 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004949}
4950
4951bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4952 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004953 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004954 const auto *cb_access_context = GetAccessContext(commandBuffer);
4955 assert(cb_access_context);
4956 if (!cb_access_context) return skip;
4957
locke-lunarg61870c22020-06-09 14:51:50 -06004958 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4959 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4960 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004961 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004962}
4963
4964void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4965 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004966 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004967 auto *cb_access_context = GetAccessContext(commandBuffer);
4968 assert(cb_access_context);
4969 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004970
locke-lunarg61870c22020-06-09 14:51:50 -06004971 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4972 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4973 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004974}
4975
4976bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4977 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004978 bool skip = false;
4979 if (drawCount == 0) return skip;
4980
locke-lunargff255f92020-05-13 18:53:52 -06004981 const auto *cb_access_context = GetAccessContext(commandBuffer);
4982 assert(cb_access_context);
4983 if (!cb_access_context) return skip;
4984
4985 const auto *context = cb_access_context->GetCurrentAccessContext();
4986 assert(context);
4987 if (!context) return skip;
4988
locke-lunarg61870c22020-06-09 14:51:50 -06004989 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4990 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004991 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4992 drawCount, stride, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004993
4994 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
4995 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
4996 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06004997 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004998 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004999}
5000
5001void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5002 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005003 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005004 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005005 auto *cb_access_context = GetAccessContext(commandBuffer);
5006 assert(cb_access_context);
5007 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5008 auto *context = cb_access_context->GetCurrentAccessContext();
5009 assert(context);
5010
locke-lunarg61870c22020-06-09 14:51:50 -06005011 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5012 cb_access_context->RecordDrawSubpassAttachment(tag);
5013 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005014
5015 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5016 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5017 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005018 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005019}
5020
5021bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5022 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005023 bool skip = false;
5024 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005025 const auto *cb_access_context = GetAccessContext(commandBuffer);
5026 assert(cb_access_context);
5027 if (!cb_access_context) return skip;
5028
5029 const auto *context = cb_access_context->GetCurrentAccessContext();
5030 assert(context);
5031 if (!context) return skip;
5032
locke-lunarg61870c22020-06-09 14:51:50 -06005033 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
5034 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07005035 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
5036 offset, drawCount, stride, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06005037
5038 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5039 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5040 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005041 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06005042 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005043}
5044
5045void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5046 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005047 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005048 auto *cb_access_context = GetAccessContext(commandBuffer);
5049 assert(cb_access_context);
5050 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5051 auto *context = cb_access_context->GetCurrentAccessContext();
5052 assert(context);
5053
locke-lunarg61870c22020-06-09 14:51:50 -06005054 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5055 cb_access_context->RecordDrawSubpassAttachment(tag);
5056 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005057
5058 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5059 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5060 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005061 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005062}
5063
5064bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5065 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5066 uint32_t stride, const char *function) const {
5067 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005068 const auto *cb_access_context = GetAccessContext(commandBuffer);
5069 assert(cb_access_context);
5070 if (!cb_access_context) return skip;
5071
5072 const auto *context = cb_access_context->GetCurrentAccessContext();
5073 assert(context);
5074 if (!context) return skip;
5075
locke-lunarg61870c22020-06-09 14:51:50 -06005076 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
5077 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07005078 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
5079 maxDrawCount, stride, function);
5080 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06005081
5082 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5083 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5084 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005085 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06005086 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005087}
5088
5089bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5090 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5091 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005092 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5093 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06005094}
5095
sfricke-samsung85584a72021-09-30 21:43:38 -07005096void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5097 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5098 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005099 auto *cb_access_context = GetAccessContext(commandBuffer);
5100 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005101 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005102 auto *context = cb_access_context->GetCurrentAccessContext();
5103 assert(context);
5104
locke-lunarg61870c22020-06-09 14:51:50 -06005105 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5106 cb_access_context->RecordDrawSubpassAttachment(tag);
5107 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5108 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005109
5110 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5111 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5112 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005113 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005114}
5115
sfricke-samsung85584a72021-09-30 21:43:38 -07005116void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5117 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5118 uint32_t stride) {
5119 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5120 stride);
5121 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5122 CMD_DRAWINDIRECTCOUNT);
5123}
locke-lunarge1a67022020-04-29 00:15:36 -06005124bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5125 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5126 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005127 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5128 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06005129}
5130
5131void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5132 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5133 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005134 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5135 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005136 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5137 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005138}
5139
5140bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5141 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5142 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005143 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5144 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06005145}
5146
5147void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5148 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5149 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005150 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5151 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005152 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5153 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005154}
5155
5156bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5157 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5158 uint32_t stride, const char *function) const {
5159 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005160 const auto *cb_access_context = GetAccessContext(commandBuffer);
5161 assert(cb_access_context);
5162 if (!cb_access_context) return skip;
5163
5164 const auto *context = cb_access_context->GetCurrentAccessContext();
5165 assert(context);
5166 if (!context) return skip;
5167
locke-lunarg61870c22020-06-09 14:51:50 -06005168 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
5169 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07005170 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
5171 offset, maxDrawCount, stride, function);
5172 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06005173
5174 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5175 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5176 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005177 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06005178 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005179}
5180
5181bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5182 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5183 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005184 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5185 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06005186}
5187
sfricke-samsung85584a72021-09-30 21:43:38 -07005188void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5189 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5190 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005191 auto *cb_access_context = GetAccessContext(commandBuffer);
5192 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005193 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005194 auto *context = cb_access_context->GetCurrentAccessContext();
5195 assert(context);
5196
locke-lunarg61870c22020-06-09 14:51:50 -06005197 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5198 cb_access_context->RecordDrawSubpassAttachment(tag);
5199 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5200 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005201
5202 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5203 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005204 // We will update the index and vertex buffer in SubmitQueue in the future.
5205 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005206}
5207
sfricke-samsung85584a72021-09-30 21:43:38 -07005208void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5209 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5210 uint32_t maxDrawCount, uint32_t stride) {
5211 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5212 maxDrawCount, stride);
5213 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5214 CMD_DRAWINDEXEDINDIRECTCOUNT);
5215}
5216
locke-lunarge1a67022020-04-29 00:15:36 -06005217bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5218 VkDeviceSize offset, VkBuffer countBuffer,
5219 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5220 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005221 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5222 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06005223}
5224
5225void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5226 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5227 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005228 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5229 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005230 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5231 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005232}
5233
5234bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5235 VkDeviceSize offset, VkBuffer countBuffer,
5236 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5237 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005238 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5239 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06005240}
5241
5242void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5243 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5244 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005245 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5246 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005247 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5248 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005249}
5250
5251bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5252 const VkClearColorValue *pColor, uint32_t rangeCount,
5253 const VkImageSubresourceRange *pRanges) const {
5254 bool skip = false;
5255 const auto *cb_access_context = GetAccessContext(commandBuffer);
5256 assert(cb_access_context);
5257 if (!cb_access_context) return skip;
5258
5259 const auto *context = cb_access_context->GetCurrentAccessContext();
5260 assert(context);
5261 if (!context) return skip;
5262
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005263 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005264
5265 for (uint32_t index = 0; index < rangeCount; index++) {
5266 const auto &range = pRanges[index];
5267 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005268 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005269 if (hazard.hazard) {
5270 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005271 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005272 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005273 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005274 }
5275 }
5276 }
5277 return skip;
5278}
5279
5280void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5281 const VkClearColorValue *pColor, uint32_t rangeCount,
5282 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005283 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005284 auto *cb_access_context = GetAccessContext(commandBuffer);
5285 assert(cb_access_context);
5286 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5287 auto *context = cb_access_context->GetCurrentAccessContext();
5288 assert(context);
5289
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005290 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005291
5292 for (uint32_t index = 0; index < rangeCount; index++) {
5293 const auto &range = pRanges[index];
5294 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005295 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005296 }
5297 }
5298}
5299
5300bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5301 VkImageLayout imageLayout,
5302 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5303 const VkImageSubresourceRange *pRanges) const {
5304 bool skip = false;
5305 const auto *cb_access_context = GetAccessContext(commandBuffer);
5306 assert(cb_access_context);
5307 if (!cb_access_context) return skip;
5308
5309 const auto *context = cb_access_context->GetCurrentAccessContext();
5310 assert(context);
5311 if (!context) return skip;
5312
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005313 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005314
5315 for (uint32_t index = 0; index < rangeCount; index++) {
5316 const auto &range = pRanges[index];
5317 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005318 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005319 if (hazard.hazard) {
5320 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005321 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005322 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005323 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005324 }
5325 }
5326 }
5327 return skip;
5328}
5329
5330void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5331 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5332 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005333 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005334 auto *cb_access_context = GetAccessContext(commandBuffer);
5335 assert(cb_access_context);
5336 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5337 auto *context = cb_access_context->GetCurrentAccessContext();
5338 assert(context);
5339
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005340 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005341
5342 for (uint32_t index = 0; index < rangeCount; index++) {
5343 const auto &range = pRanges[index];
5344 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005345 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005346 }
5347 }
5348}
5349
5350bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5351 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5352 VkDeviceSize dstOffset, VkDeviceSize stride,
5353 VkQueryResultFlags flags) const {
5354 bool skip = false;
5355 const auto *cb_access_context = GetAccessContext(commandBuffer);
5356 assert(cb_access_context);
5357 if (!cb_access_context) return skip;
5358
5359 const auto *context = cb_access_context->GetCurrentAccessContext();
5360 assert(context);
5361 if (!context) return skip;
5362
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005363 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005364
5365 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005366 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005367 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005368 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005369 skip |=
5370 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5371 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005372 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005373 }
5374 }
locke-lunargff255f92020-05-13 18:53:52 -06005375
5376 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005377 return skip;
5378}
5379
5380void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5381 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5382 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005383 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5384 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005385 auto *cb_access_context = GetAccessContext(commandBuffer);
5386 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005387 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005388 auto *context = cb_access_context->GetCurrentAccessContext();
5389 assert(context);
5390
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005391 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005392
5393 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005394 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005395 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005396 }
locke-lunargff255f92020-05-13 18:53:52 -06005397
5398 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005399}
5400
5401bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5402 VkDeviceSize size, uint32_t data) const {
5403 bool skip = false;
5404 const auto *cb_access_context = GetAccessContext(commandBuffer);
5405 assert(cb_access_context);
5406 if (!cb_access_context) return skip;
5407
5408 const auto *context = cb_access_context->GetCurrentAccessContext();
5409 assert(context);
5410 if (!context) return skip;
5411
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005412 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005413
5414 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005415 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005416 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005417 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005418 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005419 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005420 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005421 }
5422 }
5423 return skip;
5424}
5425
5426void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5427 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005428 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005429 auto *cb_access_context = GetAccessContext(commandBuffer);
5430 assert(cb_access_context);
5431 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5432 auto *context = cb_access_context->GetCurrentAccessContext();
5433 assert(context);
5434
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005435 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005436
5437 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005438 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005439 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005440 }
5441}
5442
5443bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5444 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5445 const VkImageResolve *pRegions) const {
5446 bool skip = false;
5447 const auto *cb_access_context = GetAccessContext(commandBuffer);
5448 assert(cb_access_context);
5449 if (!cb_access_context) return skip;
5450
5451 const auto *context = cb_access_context->GetCurrentAccessContext();
5452 assert(context);
5453 if (!context) return skip;
5454
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005455 auto src_image = Get<IMAGE_STATE>(srcImage);
5456 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005457
5458 for (uint32_t region = 0; region < regionCount; region++) {
5459 const auto &resolve_region = pRegions[region];
5460 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005461 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
locke-lunarge1a67022020-04-29 00:15:36 -06005462 resolve_region.srcOffset, resolve_region.extent);
5463 if (hazard.hazard) {
5464 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005465 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005466 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005467 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005468 }
5469 }
5470
5471 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005472 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
locke-lunarge1a67022020-04-29 00:15:36 -06005473 resolve_region.dstOffset, resolve_region.extent);
5474 if (hazard.hazard) {
5475 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005476 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005477 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005478 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005479 }
5480 if (skip) break;
5481 }
5482 }
5483
5484 return skip;
5485}
5486
5487void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5488 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5489 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005490 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5491 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005492 auto *cb_access_context = GetAccessContext(commandBuffer);
5493 assert(cb_access_context);
5494 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5495 auto *context = cb_access_context->GetCurrentAccessContext();
5496 assert(context);
5497
Jeremy Gebben9f537102021-10-05 16:37:12 -06005498 auto src_image = Get<IMAGE_STATE>(srcImage);
5499 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005500
5501 for (uint32_t region = 0; region < regionCount; region++) {
5502 const auto &resolve_region = pRegions[region];
5503 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005504 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005505 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005506 }
5507 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005508 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005509 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005510 }
5511 }
5512}
5513
Tony-LunarG562fc102021-11-12 13:58:35 -07005514bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5515 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005516 bool skip = false;
5517 const auto *cb_access_context = GetAccessContext(commandBuffer);
5518 assert(cb_access_context);
5519 if (!cb_access_context) return skip;
5520
5521 const auto *context = cb_access_context->GetCurrentAccessContext();
5522 assert(context);
5523 if (!context) return skip;
5524
Tony-LunarG562fc102021-11-12 13:58:35 -07005525 const char *func_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005526 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5527 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005528
5529 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5530 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5531 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005532 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Jeff Leger178b1e52020-10-05 12:22:23 -04005533 resolve_region.srcOffset, resolve_region.extent);
5534 if (hazard.hazard) {
5535 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
Tony-LunarG562fc102021-11-12 13:58:35 -07005536 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04005537 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005538 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005539 }
5540 }
5541
5542 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005543 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Jeff Leger178b1e52020-10-05 12:22:23 -04005544 resolve_region.dstOffset, resolve_region.extent);
5545 if (hazard.hazard) {
5546 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
Tony-LunarG562fc102021-11-12 13:58:35 -07005547 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04005548 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005549 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005550 }
5551 if (skip) break;
5552 }
5553 }
5554
5555 return skip;
5556}
5557
Tony-LunarG562fc102021-11-12 13:58:35 -07005558bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5559 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5560 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5561}
5562
5563bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5564 const VkResolveImageInfo2 *pResolveImageInfo) const {
5565 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5566}
5567
5568void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5569 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005570 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5571 auto *cb_access_context = GetAccessContext(commandBuffer);
5572 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005573 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005574 auto *context = cb_access_context->GetCurrentAccessContext();
5575 assert(context);
5576
Jeremy Gebben9f537102021-10-05 16:37:12 -06005577 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5578 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005579
5580 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5581 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5582 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005583 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005584 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005585 }
5586 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005587 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005588 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005589 }
5590 }
5591}
5592
Tony-LunarG562fc102021-11-12 13:58:35 -07005593void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5594 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5595 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5596}
5597
5598void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5599 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5600}
5601
locke-lunarge1a67022020-04-29 00:15:36 -06005602bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5603 VkDeviceSize dataSize, const void *pData) const {
5604 bool skip = false;
5605 const auto *cb_access_context = GetAccessContext(commandBuffer);
5606 assert(cb_access_context);
5607 if (!cb_access_context) return skip;
5608
5609 const auto *context = cb_access_context->GetCurrentAccessContext();
5610 assert(context);
5611 if (!context) return skip;
5612
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005613 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005614
5615 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005616 // VK_WHOLE_SIZE not allowed
5617 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005618 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005619 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005620 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005621 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005622 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005623 }
5624 }
5625 return skip;
5626}
5627
5628void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5629 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005630 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005631 auto *cb_access_context = GetAccessContext(commandBuffer);
5632 assert(cb_access_context);
5633 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5634 auto *context = cb_access_context->GetCurrentAccessContext();
5635 assert(context);
5636
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005637 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005638
5639 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005640 // VK_WHOLE_SIZE not allowed
5641 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005642 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005643 }
5644}
locke-lunargff255f92020-05-13 18:53:52 -06005645
5646bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5647 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5648 bool skip = false;
5649 const auto *cb_access_context = GetAccessContext(commandBuffer);
5650 assert(cb_access_context);
5651 if (!cb_access_context) return skip;
5652
5653 const auto *context = cb_access_context->GetCurrentAccessContext();
5654 assert(context);
5655 if (!context) return skip;
5656
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005657 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005658
5659 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005660 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005661 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005662 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005663 skip |=
5664 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5665 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005666 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005667 }
5668 }
5669 return skip;
5670}
5671
5672void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5673 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005674 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005675 auto *cb_access_context = GetAccessContext(commandBuffer);
5676 assert(cb_access_context);
5677 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5678 auto *context = cb_access_context->GetCurrentAccessContext();
5679 assert(context);
5680
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005681 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005682
5683 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005684 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005685 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005686 }
5687}
John Zulauf49beb112020-11-04 16:06:31 -07005688
5689bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5690 bool skip = false;
5691 const auto *cb_context = GetAccessContext(commandBuffer);
5692 assert(cb_context);
5693 if (!cb_context) return skip;
5694
John Zulauf36ef9282021-02-02 11:47:24 -07005695 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005696 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005697}
5698
5699void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5700 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5701 auto *cb_context = GetAccessContext(commandBuffer);
5702 assert(cb_context);
5703 if (!cb_context) return;
John Zulauf1bf30522021-09-03 15:39:06 -06005704 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005705}
5706
John Zulauf4edde622021-02-15 08:54:50 -07005707bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5708 const VkDependencyInfoKHR *pDependencyInfo) const {
5709 bool skip = false;
5710 const auto *cb_context = GetAccessContext(commandBuffer);
5711 assert(cb_context);
5712 if (!cb_context || !pDependencyInfo) return skip;
5713
5714 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5715 return set_event_op.Validate(*cb_context);
5716}
5717
Tony-LunarGc43525f2021-11-15 16:12:38 -07005718bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5719 const VkDependencyInfo *pDependencyInfo) const {
5720 bool skip = false;
5721 const auto *cb_context = GetAccessContext(commandBuffer);
5722 assert(cb_context);
5723 if (!cb_context || !pDependencyInfo) return skip;
5724
5725 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5726 return set_event_op.Validate(*cb_context);
5727}
5728
John Zulauf4edde622021-02-15 08:54:50 -07005729void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5730 const VkDependencyInfoKHR *pDependencyInfo) {
5731 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5732 auto *cb_context = GetAccessContext(commandBuffer);
5733 assert(cb_context);
5734 if (!cb_context || !pDependencyInfo) return;
5735
John Zulauf1bf30522021-09-03 15:39:06 -06005736 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
John Zulauf4edde622021-02-15 08:54:50 -07005737}
5738
Tony-LunarGc43525f2021-11-15 16:12:38 -07005739void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5740 const VkDependencyInfo *pDependencyInfo) {
5741 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5742 auto *cb_context = GetAccessContext(commandBuffer);
5743 assert(cb_context);
5744 if (!cb_context || !pDependencyInfo) return;
5745
5746 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5747}
5748
John Zulauf49beb112020-11-04 16:06:31 -07005749bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5750 VkPipelineStageFlags stageMask) const {
5751 bool skip = false;
5752 const auto *cb_context = GetAccessContext(commandBuffer);
5753 assert(cb_context);
5754 if (!cb_context) return skip;
5755
John Zulauf36ef9282021-02-02 11:47:24 -07005756 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005757 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005758}
5759
5760void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5761 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5762 auto *cb_context = GetAccessContext(commandBuffer);
5763 assert(cb_context);
5764 if (!cb_context) return;
5765
John Zulauf1bf30522021-09-03 15:39:06 -06005766 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005767}
5768
John Zulauf4edde622021-02-15 08:54:50 -07005769bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5770 VkPipelineStageFlags2KHR stageMask) const {
5771 bool skip = false;
5772 const auto *cb_context = GetAccessContext(commandBuffer);
5773 assert(cb_context);
5774 if (!cb_context) return skip;
5775
5776 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5777 return reset_event_op.Validate(*cb_context);
5778}
5779
Tony-LunarGa2662db2021-11-16 07:26:24 -07005780bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5781 VkPipelineStageFlags2 stageMask) const {
5782 bool skip = false;
5783 const auto *cb_context = GetAccessContext(commandBuffer);
5784 assert(cb_context);
5785 if (!cb_context) return skip;
5786
5787 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5788 return reset_event_op.Validate(*cb_context);
5789}
5790
John Zulauf4edde622021-02-15 08:54:50 -07005791void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5792 VkPipelineStageFlags2KHR stageMask) {
5793 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5794 auto *cb_context = GetAccessContext(commandBuffer);
5795 assert(cb_context);
5796 if (!cb_context) return;
5797
John Zulauf1bf30522021-09-03 15:39:06 -06005798 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005799}
5800
Tony-LunarGa2662db2021-11-16 07:26:24 -07005801void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5802 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5803 auto *cb_context = GetAccessContext(commandBuffer);
5804 assert(cb_context);
5805 if (!cb_context) return;
5806
5807 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5808}
5809
John Zulauf49beb112020-11-04 16:06:31 -07005810bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5811 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5812 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5813 uint32_t bufferMemoryBarrierCount,
5814 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5815 uint32_t imageMemoryBarrierCount,
5816 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5817 bool skip = false;
5818 const auto *cb_context = GetAccessContext(commandBuffer);
5819 assert(cb_context);
5820 if (!cb_context) return skip;
5821
John Zulauf36ef9282021-02-02 11:47:24 -07005822 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5823 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5824 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005825 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005826}
5827
5828void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5829 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5830 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5831 uint32_t bufferMemoryBarrierCount,
5832 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5833 uint32_t imageMemoryBarrierCount,
5834 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5835 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5836 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5837 imageMemoryBarrierCount, pImageMemoryBarriers);
5838
5839 auto *cb_context = GetAccessContext(commandBuffer);
5840 assert(cb_context);
5841 if (!cb_context) return;
5842
John Zulauf1bf30522021-09-03 15:39:06 -06005843 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06005844 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06005845 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07005846}
5847
John Zulauf4edde622021-02-15 08:54:50 -07005848bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5849 const VkDependencyInfoKHR *pDependencyInfos) const {
5850 bool skip = false;
5851 const auto *cb_context = GetAccessContext(commandBuffer);
5852 assert(cb_context);
5853 if (!cb_context) return skip;
5854
5855 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5856 skip |= wait_events_op.Validate(*cb_context);
5857 return skip;
5858}
5859
5860void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5861 const VkDependencyInfoKHR *pDependencyInfos) {
5862 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5863
5864 auto *cb_context = GetAccessContext(commandBuffer);
5865 assert(cb_context);
5866 if (!cb_context) return;
5867
John Zulauf1bf30522021-09-03 15:39:06 -06005868 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5869 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07005870}
5871
Tony-LunarG1364cf52021-11-17 16:10:11 -07005872bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5873 const VkDependencyInfo *pDependencyInfos) const {
5874 bool skip = false;
5875 const auto *cb_context = GetAccessContext(commandBuffer);
5876 assert(cb_context);
5877 if (!cb_context) return skip;
5878
5879 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5880 skip |= wait_events_op.Validate(*cb_context);
5881 return skip;
5882}
5883
5884void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5885 const VkDependencyInfo *pDependencyInfos) {
5886 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5887
5888 auto *cb_context = GetAccessContext(commandBuffer);
5889 assert(cb_context);
5890 if (!cb_context) return;
5891
5892 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5893 pDependencyInfos);
5894}
5895
John Zulauf4a6105a2020-11-17 15:11:05 -07005896void SyncEventState::ResetFirstScope() {
5897 for (const auto address_type : kAddressTypes) {
5898 first_scope[static_cast<size_t>(address_type)].clear();
5899 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005900 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06005901 first_scope_set = false;
5902 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07005903}
5904
5905// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
John Zulauf4edde622021-02-15 08:54:50 -07005906SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005907 IgnoreReason reason = NotIgnored;
5908
Tony-LunarG1364cf52021-11-17 16:10:11 -07005909 if ((CMD_WAITEVENTS2KHR == cmd || CMD_WAITEVENTS2 == cmd) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07005910 reason = SetVsWait2;
5911 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
5912 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07005913 } else if (unsynchronized_set) {
5914 reason = SetRace;
John Zulauf78b1f892021-09-20 15:02:09 -06005915 } else if (first_scope_set) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005916 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005917 if (missing_bits) reason = MissingStageBits;
5918 }
5919
5920 return reason;
5921}
5922
Jeremy Gebben40a22942020-12-22 14:22:06 -07005923bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005924 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5925 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5926 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005927}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005928
John Zulaufbb890452021-12-14 11:30:18 -07005929void SyncOpBase::SetReplayContext(uint32_t subpass, ReplayContextPtr &&replay) {
5930 subpass_ = subpass;
5931 replay_context_ = std::move(replay);
5932}
5933
5934const ReplayTrackbackBarriersAction *SyncOpBase::GetReplayTrackback() const {
5935 if (replay_context_) {
5936 assert(subpass_ < replay_context_->subpass_contexts.size());
5937 return &replay_context_->subpass_contexts[subpass_];
5938 }
5939 return nullptr;
5940}
5941
John Zulauf36ef9282021-02-02 11:47:24 -07005942SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
5943 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5944 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07005945 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5946 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5947 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf4edde622021-02-15 08:54:50 -07005948 : SyncOpBase(cmd), barriers_(1) {
5949 auto &barrier_set = barriers_[0];
5950 barrier_set.dependency_flags = dependencyFlags;
5951 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
5952 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005953 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07005954 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
5955 pMemoryBarriers);
5956 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5957 bufferMemoryBarrierCount, pBufferMemoryBarriers);
5958 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5959 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005960}
5961
John Zulauf4edde622021-02-15 08:54:50 -07005962SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
5963 const VkDependencyInfoKHR *dep_infos)
5964 : SyncOpBase(cmd), barriers_(event_count) {
5965 for (uint32_t i = 0; i < event_count; i++) {
5966 const auto &dep_info = dep_infos[i];
5967 auto &barrier_set = barriers_[i];
5968 barrier_set.dependency_flags = dep_info.dependencyFlags;
5969 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
5970 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
5971 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
5972 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5973 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
5974 dep_info.pMemoryBarriers);
5975 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
5976 dep_info.pBufferMemoryBarriers);
5977 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
5978 dep_info.pImageMemoryBarriers);
5979 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005980}
5981
John Zulauf36ef9282021-02-02 11:47:24 -07005982SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07005983 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5984 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5985 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5986 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5987 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf36ef9282021-02-02 11:47:24 -07005988 : SyncOpBarriers(cmd, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
John Zulaufd5115702021-01-18 12:34:33 -07005989 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers) {}
5990
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005991SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
5992 const VkDependencyInfoKHR &dep_info)
John Zulauf4edde622021-02-15 08:54:50 -07005993 : SyncOpBarriers(cmd, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005994
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005995bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
5996 bool skip = false;
5997 const auto *context = cb_context.GetCurrentAccessContext();
5998 assert(context);
5999 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006000 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6001
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006002 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006003 const auto &barrier_set = barriers_[0];
6004 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6005 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6006 const auto *image_state = image_barrier.image.get();
6007 if (!image_state) continue;
6008 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6009 if (hazard.hazard) {
6010 // PHASE1 TODO -- add tag information to log msg when useful.
6011 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006012 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006013 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6014 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6015 string_SyncHazard(hazard.hazard), image_barrier.index,
6016 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006017 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006018 }
6019 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006020 return skip;
6021}
6022
John Zulaufd5115702021-01-18 12:34:33 -07006023struct SyncOpPipelineBarrierFunctorFactory {
6024 using BarrierOpFunctor = PipelineBarrierOp;
6025 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6026 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6027 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6028 using BufferRange = ResourceAccessRange;
6029 using ImageRange = subresource_adapter::ImageRangeGenerator;
6030 using GlobalRange = ResourceAccessRange;
6031
John Zulauf00119522022-05-23 19:07:42 -06006032 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6033 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006034 }
John Zulauf14940722021-04-12 15:19:02 -06006035 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006036 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6037 }
John Zulauf00119522022-05-23 19:07:42 -06006038 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6039 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006040 }
6041
6042 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6043 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6044 const auto base_address = ResourceBaseAddress(buffer);
6045 return (range + base_address);
6046 }
John Zulauf110413c2021-03-20 05:38:38 -06006047 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006048 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006049
6050 const auto base_address = ResourceBaseAddress(image);
John Zulauf110413c2021-03-20 05:38:38 -06006051 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
John Zulaufd5115702021-01-18 12:34:33 -07006052 return range_gen;
6053 }
6054 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6055};
6056
6057template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006058void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6059 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006060 for (const auto &barrier : barriers) {
6061 const auto *state = barrier.GetState();
6062 if (state) {
6063 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006064 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006065 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6066 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6067 }
6068 }
6069}
6070
6071template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006072void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6073 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006074 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6075 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006076 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006077 }
6078 for (const auto address_type : kAddressTypes) {
6079 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6080 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6081 }
6082}
6083
John Zulauf8eda1562021-04-13 17:06:41 -06006084ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006085 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf8eda1562021-04-13 17:06:41 -06006086 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006087 const QueueId queue_id = cb_context->GetQueueId();
John Zulauf36ef9282021-02-02 11:47:24 -07006088 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf00119522022-05-23 19:07:42 -06006089 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006090 return tag;
6091}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006092
John Zulauf00119522022-05-23 19:07:42 -06006093void SyncOpPipelineBarrier::ReplayRecord(QueueId queue_id, const ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006094 SyncEventsContext *events_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006095 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006096 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6097 assert(barriers_.size() == 1);
6098 const auto &barrier_set = barriers_[0];
John Zulauf00119522022-05-23 19:07:42 -06006099 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6100 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6101 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006102 if (barrier_set.single_exec_scope) {
John Zulauf8eda1562021-04-13 17:06:41 -06006103 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006104 } else {
6105 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulauf8eda1562021-04-13 17:06:41 -06006106 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006107 }
6108 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006109}
6110
John Zulauf8eda1562021-04-13 17:06:41 -06006111bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006112 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006113 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6114 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006115 return false;
6116}
6117
John Zulauf4edde622021-02-15 08:54:50 -07006118void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6119 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6120 const VkMemoryBarrier *barriers) {
6121 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006122 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006123 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006124 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006125 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006126 }
6127 if (0 == memory_barrier_count) {
6128 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006129 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006130 }
John Zulauf4edde622021-02-15 08:54:50 -07006131 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006132}
6133
John Zulauf4edde622021-02-15 08:54:50 -07006134void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6135 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6136 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6137 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006138 for (uint32_t index = 0; index < barrier_count; index++) {
6139 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006140 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006141 if (buffer) {
6142 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6143 const auto range = MakeRange(barrier.offset, barrier_size);
6144 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006145 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006146 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006147 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006148 }
6149 }
6150}
6151
John Zulauf4edde622021-02-15 08:54:50 -07006152void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006153 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006154 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006155 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006156 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006157 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6158 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6159 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006160 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006161 }
John Zulauf4edde622021-02-15 08:54:50 -07006162 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006163}
6164
John Zulauf4edde622021-02-15 08:54:50 -07006165void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6166 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006167 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006168 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006169 for (uint32_t index = 0; index < barrier_count; index++) {
6170 const auto &barrier = barriers[index];
6171 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6172 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006173 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006174 if (buffer) {
6175 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6176 const auto range = MakeRange(barrier.offset, barrier_size);
6177 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006178 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006179 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006180 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006181 }
6182 }
6183}
6184
John Zulauf4edde622021-02-15 08:54:50 -07006185void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6186 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6187 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6188 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006189 for (uint32_t index = 0; index < barrier_count; index++) {
6190 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006191 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006192 if (image) {
6193 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6194 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006195 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006196 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006197 image_memory_barriers.emplace_back();
6198 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006199 }
6200 }
6201}
John Zulaufd5115702021-01-18 12:34:33 -07006202
John Zulauf4edde622021-02-15 08:54:50 -07006203void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6204 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006205 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006206 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006207 for (uint32_t index = 0; index < barrier_count; index++) {
6208 const auto &barrier = barriers[index];
6209 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6210 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006211 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006212 if (image) {
6213 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6214 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006215 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006216 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006217 image_memory_barriers.emplace_back();
6218 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006219 }
6220 }
6221}
6222
John Zulauf36ef9282021-02-02 11:47:24 -07006223SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
John Zulaufd5115702021-01-18 12:34:33 -07006224 const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6225 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6226 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6227 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf36ef9282021-02-02 11:47:24 -07006228 : SyncOpBarriers(cmd, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006229 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6230 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006231 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006232}
6233
John Zulauf4edde622021-02-15 08:54:50 -07006234SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
6235 const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6236 : SyncOpBarriers(cmd, sync_state, queue_flags, eventCount, pDependencyInfo) {
6237 MakeEventsList(sync_state, eventCount, pEvents);
6238 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6239}
6240
John Zulauf610e28c2021-08-03 17:46:23 -06006241const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6242
John Zulaufd5115702021-01-18 12:34:33 -07006243bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006244 bool skip = false;
6245 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006246 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006247
John Zulauf610e28c2021-08-03 17:46:23 -06006248 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006249 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6250 const auto &barrier_set = barriers_[barrier_set_index];
6251 if (barrier_set.single_exec_scope) {
6252 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6253 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6254 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6255 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6256 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6257 } else {
6258 const auto &barriers = barrier_set.memory_barriers;
6259 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6260 const auto &barrier = barriers[barrier_index];
6261 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6262 const std::string vuid =
6263 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6264 skip =
6265 sync_state.LogInfo(command_buffer_handle, vuid,
6266 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6267 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6268 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6269 }
6270 }
6271 }
6272 }
John Zulaufd5115702021-01-18 12:34:33 -07006273 }
6274
John Zulauf610e28c2021-08-03 17:46:23 -06006275 // The rest is common to record time and replay time.
6276 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6277 return skip;
6278}
6279
John Zulaufbb890452021-12-14 11:30:18 -07006280bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006281 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006282 const auto &sync_state = exec_context.GetSyncState();
John Zulauf610e28c2021-08-03 17:46:23 -06006283
Jeremy Gebben40a22942020-12-22 14:22:06 -07006284 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006285 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006286 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006287 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006288 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006289 size_t barrier_set_index = 0;
6290 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006291 for (const auto &event : events_) {
6292 const auto *sync_event = events_context->Get(event.get());
6293 const auto &barrier_set = barriers_[barrier_set_index];
6294 if (!sync_event) {
6295 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6296 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6297 // new validation error... wait without previously submitted set event...
6298 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 -07006299 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006300 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006301 }
John Zulauf610e28c2021-08-03 17:46:23 -06006302
6303 // For replay calls, don't revalidate "same command buffer" events
6304 if (sync_event->last_command_tag > base_tag) continue;
6305
John Zulauf78394fc2021-07-12 15:41:40 -06006306 const auto event_handle = sync_event->event->event();
6307 // TODO add "destroyed" checks
6308
John Zulauf78b1f892021-09-20 15:02:09 -06006309 if (sync_event->first_scope_set) {
6310 // Only accumulate barrier and event stages if there is a pending set in the current context
6311 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6312 event_stage_masks |= sync_event->scope.mask_param;
6313 }
6314
John Zulauf78394fc2021-07-12 15:41:40 -06006315 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006316
John Zulauf78394fc2021-07-12 15:41:40 -06006317 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_, src_exec_scope.mask_param);
6318 if (ignore_reason) {
6319 switch (ignore_reason) {
6320 case SyncEventState::ResetWaitRace:
6321 case SyncEventState::Reset2WaitRace: {
6322 // Four permuations of Reset and Wait calls...
6323 const char *vuid =
6324 (cmd_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
6325 if (ignore_reason == SyncEventState::Reset2WaitRace) {
Tony-LunarG279601c2021-11-16 10:50:51 -07006326 vuid = (cmd_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6327 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006328 }
6329 const char *const message =
6330 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6331 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6332 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006333 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006334 break;
6335 }
6336 case SyncEventState::SetRace: {
6337 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6338 // this event
6339 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6340 const char *const message =
6341 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6342 const char *const reason = "First synchronization scope is undefined.";
6343 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6344 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006345 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006346 break;
6347 }
6348 case SyncEventState::MissingStageBits: {
6349 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6350 // Issue error message that event waited for is not in wait events scope
6351 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6352 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6353 ". Bits missing from srcStageMask %s. %s";
6354 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6355 sync_state.report_data->FormatHandle(event_handle).c_str(),
6356 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006357 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006358 break;
6359 }
6360 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006361 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006362 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6363 sync_state.report_data->FormatHandle(event_handle).c_str(),
6364 CommandTypeString(sync_event->last_command));
6365 break;
6366 }
6367 default:
6368 assert(ignore_reason == SyncEventState::NotIgnored);
6369 }
6370 } else if (barrier_set.image_memory_barriers.size()) {
6371 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006372 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006373 assert(context);
6374 for (const auto &image_memory_barrier : image_memory_barriers) {
6375 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6376 const auto *image_state = image_memory_barrier.image.get();
6377 if (!image_state) continue;
6378 const auto &subresource_range = image_memory_barrier.range;
6379 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
6380 const auto hazard =
6381 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
6382 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
6383 if (hazard.hazard) {
6384 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6385 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6386 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6387 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006388 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006389 break;
6390 }
6391 }
6392 }
6393 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6394 // 03839
6395 barrier_set_index += barrier_set_incr;
6396 }
John Zulaufd5115702021-01-18 12:34:33 -07006397
6398 // 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 -07006399 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 -07006400 if (extra_stage_bits) {
6401 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006402 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6403 const char *const vuid =
Tony-LunarG279601c2021-11-16 10:50:51 -07006404 (CMD_WAITEVENTS == cmd_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006405 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006406 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006407 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006408 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006409 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006410 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006411 " vkCmdSetEvent may be in previously submitted command buffer.");
6412 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006413 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006414 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006415 }
6416 }
6417 return skip;
6418}
6419
6420struct SyncOpWaitEventsFunctorFactory {
6421 using BarrierOpFunctor = WaitEventBarrierOp;
6422 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6423 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6424 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6425 using BufferRange = EventSimpleRangeGenerator;
6426 using ImageRange = EventImageRangeGenerator;
6427 using GlobalRange = EventSimpleRangeGenerator;
6428
6429 // Need to restrict to only valid exec and access scope for this event
6430 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6431 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006432 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006433 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6434 return barrier;
6435 }
John Zulauf00119522022-05-23 19:07:42 -06006436 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006437 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006438 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006439 }
John Zulauf14940722021-04-12 15:19:02 -06006440 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006441 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6442 }
John Zulauf00119522022-05-23 19:07:42 -06006443 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006444 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006445 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006446 }
6447
6448 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6449 const AccessAddressType address_type = GetAccessAddressType(buffer);
6450 const auto base_address = ResourceBaseAddress(buffer);
6451 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6452 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6453 return filtered_range_gen;
6454 }
John Zulauf110413c2021-03-20 05:38:38 -06006455 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006456 if (!SimpleBinding(image)) return ImageRange();
6457 const auto address_type = GetAccessAddressType(image);
6458 const auto base_address = ResourceBaseAddress(image);
John Zulauf110413c2021-03-20 05:38:38 -06006459 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address);
John Zulaufd5115702021-01-18 12:34:33 -07006460 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6461
6462 return filtered_range_gen;
6463 }
6464 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6465 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6466 }
6467 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6468 SyncEventState *sync_event;
6469};
6470
John Zulauf8eda1562021-04-13 17:06:41 -06006471ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf36ef9282021-02-02 11:47:24 -07006472 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulaufd5115702021-01-18 12:34:33 -07006473 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006474 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufd5115702021-01-18 12:34:33 -07006475 assert(access_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006476 if (!access_context) return tag;
John Zulauf669dfd52021-01-27 17:15:28 -07006477 auto *events_context = cb_context->GetCurrentEventsContext();
6478 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006479 if (!events_context) return tag;
John Zulaufd5115702021-01-18 12:34:33 -07006480
John Zulauf00119522022-05-23 19:07:42 -06006481 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006482 return tag;
6483}
6484
John Zulauf00119522022-05-23 19:07:42 -06006485void SyncOpWaitEvents::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6486 SyncEventsContext *events_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006487 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6488 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6489 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
6490 access_context->ResolvePreviousAccesses();
6491
John Zulauf4edde622021-02-15 08:54:50 -07006492 size_t barrier_set_index = 0;
6493 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6494 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006495 for (auto &event_shared : events_) {
6496 if (!event_shared.get()) continue;
6497 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006498
John Zulauf4edde622021-02-15 08:54:50 -07006499 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006500 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006501
John Zulauf4edde622021-02-15 08:54:50 -07006502 const auto &barrier_set = barriers_[barrier_set_index];
6503 const auto &dst = barrier_set.dst_exec_scope;
6504 if (!sync_event->IsIgnoredByWait(cmd_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006505 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6506 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6507 // of the barriers is maintained.
6508 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006509 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6510 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6511 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006512
6513 // Apply the global barrier to the event itself (for race condition tracking)
6514 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6515 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6516 sync_event->barriers |= dst.exec_scope;
6517 } else {
6518 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6519 sync_event->barriers = 0U;
6520 }
John Zulauf4edde622021-02-15 08:54:50 -07006521 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006522 }
6523
6524 // Apply the pending barriers
6525 ResolvePendingBarrierFunctor apply_pending_action(tag);
6526 access_context->ApplyToContext(apply_pending_action);
6527}
6528
John Zulauf8eda1562021-04-13 17:06:41 -06006529bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006530 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6531 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006532}
6533
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006534bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6535 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6536 bool skip = false;
6537 const auto *cb_access_context = GetAccessContext(commandBuffer);
6538 assert(cb_access_context);
6539 if (!cb_access_context) return skip;
6540
6541 const auto *context = cb_access_context->GetCurrentAccessContext();
6542 assert(context);
6543 if (!context) return skip;
6544
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006545 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006546
6547 if (dst_buffer) {
6548 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6549 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6550 if (hazard.hazard) {
6551 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6552 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6553 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006554 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006555 }
6556 }
6557 return skip;
6558}
6559
John Zulauf669dfd52021-01-27 17:15:28 -07006560void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006561 events_.reserve(event_count);
6562 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006563 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006564 }
6565}
John Zulauf6ce24372021-01-30 05:56:25 -07006566
John Zulauf36ef9282021-02-02 11:47:24 -07006567SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006568 VkPipelineStageFlags2KHR stageMask)
Jeremy Gebben9f537102021-10-05 16:37:12 -06006569 : SyncOpBase(cmd), event_(sync_state.Get<EVENT_STATE>(event)), exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006570
John Zulauf1bf30522021-09-03 15:39:06 -06006571bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6572 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6573}
6574
John Zulaufbb890452021-12-14 11:30:18 -07006575bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6576 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006577 assert(events_context);
6578 bool skip = false;
6579 if (!events_context) return skip;
6580
John Zulaufbb890452021-12-14 11:30:18 -07006581 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006582 const auto *sync_event = events_context->Get(event_);
6583 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6584
John Zulauf1bf30522021-09-03 15:39:06 -06006585 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6586
John Zulauf6ce24372021-01-30 05:56:25 -07006587 const char *const set_wait =
6588 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6589 "hazards.";
6590 const char *message = set_wait; // Only one message this call.
6591 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6592 const char *vuid = nullptr;
6593 switch (sync_event->last_command) {
6594 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006595 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006596 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006597 // Needs a barrier between set and reset
6598 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6599 break;
John Zulauf4edde622021-02-15 08:54:50 -07006600 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006601 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006602 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006603 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6604 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6605 break;
6606 }
6607 default:
6608 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006609 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6610 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006611 break;
6612 }
6613 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006614 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6615 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006616 CommandTypeString(sync_event->last_command));
6617 }
6618 }
6619 return skip;
6620}
6621
John Zulauf8eda1562021-04-13 17:06:41 -06006622ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) const {
6623 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf6ce24372021-01-30 05:56:25 -07006624 auto *events_context = cb_context->GetCurrentEventsContext();
6625 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006626 if (!events_context) return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006627
6628 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf8eda1562021-04-13 17:06:41 -06006629 if (!sync_event) return tag; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006630
6631 // Update the event state
John Zulauf36ef9282021-02-02 11:47:24 -07006632 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006633 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006634 sync_event->unsynchronized_set = CMD_NONE;
6635 sync_event->ResetFirstScope();
6636 sync_event->barriers = 0U;
John Zulauf8eda1562021-04-13 17:06:41 -06006637
6638 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006639}
6640
John Zulauf8eda1562021-04-13 17:06:41 -06006641bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006642 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6643 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006644}
6645
John Zulauf00119522022-05-23 19:07:42 -06006646void SyncOpResetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6647 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006648
John Zulauf36ef9282021-02-02 11:47:24 -07006649SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006650 VkPipelineStageFlags2KHR stageMask)
John Zulauf36ef9282021-02-02 11:47:24 -07006651 : SyncOpBase(cmd),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006652 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulauf4edde622021-02-15 08:54:50 -07006653 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
6654 dep_info_() {}
6655
6656SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
6657 const VkDependencyInfoKHR &dep_info)
6658 : SyncOpBase(cmd),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006659 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulauf4edde622021-02-15 08:54:50 -07006660 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
Tony-LunarG273f32f2021-09-28 08:56:30 -06006661 dep_info_(new safe_VkDependencyInfo(&dep_info)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006662
6663bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006664 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6665}
6666bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006667 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6668 assert(exec_context);
6669 return DoValidate(*exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006670}
6671
John Zulaufbb890452021-12-14 11:30:18 -07006672bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006673 bool skip = false;
6674
John Zulaufbb890452021-12-14 11:30:18 -07006675 const auto &sync_state = exec_context.GetSyncState();
6676 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006677 assert(events_context);
6678 if (!events_context) return skip;
6679
6680 const auto *sync_event = events_context->Get(event_);
6681 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6682
John Zulauf610e28c2021-08-03 17:46:23 -06006683 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6684
John Zulauf6ce24372021-01-30 05:56:25 -07006685 const char *const reset_set =
6686 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6687 "hazards.";
6688 const char *const wait =
6689 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6690
6691 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006692 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006693 const char *message = nullptr;
6694 switch (sync_event->last_command) {
6695 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006696 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006697 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006698 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006699 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006700 message = reset_set;
6701 break;
6702 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006703 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006704 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006705 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006706 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006707 message = reset_set;
6708 break;
6709 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006710 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006711 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006712 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006713 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006714 message = wait;
6715 break;
6716 default:
6717 // The only other valid last command that wasn't one.
6718 assert(sync_event->last_command == CMD_NONE);
6719 break;
6720 }
John Zulauf4edde622021-02-15 08:54:50 -07006721 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006722 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006723 std::string vuid("SYNC-");
6724 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006725 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6726 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006727 CommandTypeString(sync_event->last_command));
6728 }
6729 }
6730
6731 return skip;
6732}
6733
John Zulauf8eda1562021-04-13 17:06:41 -06006734ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf36ef9282021-02-02 11:47:24 -07006735 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf6ce24372021-01-30 05:56:25 -07006736 auto *events_context = cb_context->GetCurrentEventsContext();
6737 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006738 const QueueId queue_id = cb_context->GetQueueId();
John Zulauf6ce24372021-01-30 05:56:25 -07006739 assert(events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006740 if (access_context && events_context) {
John Zulauf00119522022-05-23 19:07:42 -06006741 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006742 }
6743 return tag;
6744}
John Zulauf6ce24372021-01-30 05:56:25 -07006745
John Zulauf00119522022-05-23 19:07:42 -06006746void SyncOpSetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6747 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006748 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006749 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006750
6751 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6752 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6753 // any issues caused by naive scope setting here.
6754
6755 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6756 // Given:
6757 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6758 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6759
6760 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6761 sync_event->unsynchronized_set = sync_event->last_command;
6762 sync_event->ResetFirstScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006763 } else if (!sync_event->first_scope_set) {
John Zulauf6ce24372021-01-30 05:56:25 -07006764 // We only set the scope if there isn't one
6765 sync_event->scope = src_exec_scope_;
6766
6767 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
6768 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
6769 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
6770 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
6771 }
6772 };
6773 access_context->ForAll(set_scope);
6774 sync_event->unsynchronized_set = CMD_NONE;
John Zulauf78b1f892021-09-20 15:02:09 -06006775 sync_event->first_scope_set = true;
John Zulauf6ce24372021-01-30 05:56:25 -07006776 sync_event->first_scope_tag = tag;
6777 }
John Zulauf4edde622021-02-15 08:54:50 -07006778 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
6779 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006780 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006781 sync_event->barriers = 0U;
6782}
John Zulauf64ffe552021-02-06 10:25:07 -07006783
6784SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd, const SyncValidator &sync_state,
6785 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006786 const VkSubpassBeginInfo *pSubpassBeginInfo)
6787 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006788 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006789 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006790 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006791 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006792 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006793 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006794 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6795 // Note that this a safe to presist as long as shared_attachments is not cleared
6796 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006797 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006798 attachments_.emplace_back(attachment.get());
6799 }
6800 }
6801 if (pSubpassBeginInfo) {
6802 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6803 }
6804 }
6805}
6806
6807bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6808 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6809 bool skip = false;
6810
6811 assert(rp_state_.get());
6812 if (nullptr == rp_state_.get()) return skip;
6813 auto &rp_state = *rp_state_.get();
6814
6815 const uint32_t subpass = 0;
6816
6817 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
6818 // hasn't happened yet)
6819 const std::vector<AccessContext> empty_context_vector;
6820 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
6821 cb_context.GetCurrentAccessContext());
6822
6823 // Validate attachment operations
6824 if (attachments_.size() == 0) return skip;
6825 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07006826
6827 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
6828 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
6829 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
6830 // operations (though it's currently a messy approach)
6831 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
6832 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, CmdName());
John Zulauf64ffe552021-02-06 10:25:07 -07006833
6834 // Validate load operations if there were no layout transition hazards
6835 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06006836 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07006837 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, CmdName());
John Zulauf64ffe552021-02-06 10:25:07 -07006838 }
6839
6840 return skip;
6841}
6842
John Zulauf8eda1562021-04-13 17:06:41 -06006843ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf64ffe552021-02-06 10:25:07 -07006844 // TODO PHASE2 need to have a consistent way to record to either command buffer or queue contexts
6845 assert(rp_state_.get());
John Zulauf41a9c7c2021-12-07 15:59:53 -07006846 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_);
6847 return cb_context->RecordBeginRenderPass(cmd_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
John Zulauf64ffe552021-02-06 10:25:07 -07006848}
6849
John Zulauf8eda1562021-04-13 17:06:41 -06006850bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006851 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006852 return false;
6853}
6854
John Zulauf00119522022-05-23 19:07:42 -06006855void SyncOpBeginRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006856 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006857
John Zulauf64ffe552021-02-06 10:25:07 -07006858SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd, const SyncValidator &sync_state, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07006859 const VkSubpassEndInfo *pSubpassEndInfo)
6860 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006861 if (pSubpassBeginInfo) {
6862 subpass_begin_info_.initialize(pSubpassBeginInfo);
6863 }
6864 if (pSubpassEndInfo) {
6865 subpass_end_info_.initialize(pSubpassEndInfo);
6866 }
6867}
6868
6869bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
6870 bool skip = false;
6871 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6872 if (!renderpass_context) return skip;
6873
6874 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), CmdName());
6875 return skip;
6876}
6877
John Zulauf8eda1562021-04-13 17:06:41 -06006878ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006879 return cb_context->RecordNextSubpass(cmd_);
John Zulauf8eda1562021-04-13 17:06:41 -06006880}
6881
6882bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006883 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006884 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07006885}
6886
sfricke-samsung85584a72021-09-30 21:43:38 -07006887SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd, const SyncValidator &sync_state, const VkSubpassEndInfo *pSubpassEndInfo)
6888 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006889 if (pSubpassEndInfo) {
6890 subpass_end_info_.initialize(pSubpassEndInfo);
6891 }
6892}
6893
John Zulauf00119522022-05-23 19:07:42 -06006894void SyncOpNextSubpass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6895 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006896
John Zulauf64ffe552021-02-06 10:25:07 -07006897bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6898 bool skip = false;
6899 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6900
6901 if (!renderpass_context) return skip;
6902 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), CmdName());
6903 return skip;
6904}
6905
John Zulauf8eda1562021-04-13 17:06:41 -06006906ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006907 return cb_context->RecordEndRenderPass(cmd_);
John Zulauf64ffe552021-02-06 10:25:07 -07006908}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006909
John Zulauf8eda1562021-04-13 17:06:41 -06006910bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006911 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006912 return false;
6913}
6914
John Zulauf00119522022-05-23 19:07:42 -06006915void SyncOpEndRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006916 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006917
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006918void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6919 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
6920 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
6921 auto *cb_access_context = GetAccessContext(commandBuffer);
6922 assert(cb_access_context);
6923 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
6924 auto *context = cb_access_context->GetCurrentAccessContext();
6925 assert(context);
6926
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006927 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006928
6929 if (dst_buffer) {
6930 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6931 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
6932 }
6933}
John Zulaufd05c5842021-03-26 11:32:16 -06006934
John Zulaufae842002021-04-15 18:20:55 -06006935bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6936 const VkCommandBuffer *pCommandBuffers) const {
6937 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
6938 const char *func_name = "vkCmdExecuteCommands";
6939 const auto *cb_context = GetAccessContext(commandBuffer);
6940 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006941
6942 // Heavyweight, but we need a proxy copy of the active command buffer access context
6943 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06006944
6945 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06006946 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006947 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
6948
John Zulaufae842002021-04-15 18:20:55 -06006949 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6950 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06006951
6952 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
6953 assert(recorded_context);
6954 skip |= recorded_cb_context->ValidateFirstUse(&proxy_cb_context, func_name, cb_index);
6955
6956 // The barriers have already been applied in ValidatFirstUse
6957 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06006958 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06006959 }
6960
John Zulaufae842002021-04-15 18:20:55 -06006961 return skip;
6962}
6963
6964void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6965 const VkCommandBuffer *pCommandBuffers) {
6966 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06006967 auto *cb_context = GetAccessContext(commandBuffer);
6968 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006969 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006970 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06006971 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6972 if (!recorded_cb_context) continue;
6973 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context, CMD_EXECUTECOMMANDS);
6974 }
John Zulaufae842002021-04-15 18:20:55 -06006975}
6976
John Zulauf1d5f9c12022-05-13 14:51:08 -06006977void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
6978 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
6979 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
6980
6981 const auto queue_state = GetQueueSyncStateShared(queue);
6982 if (!queue_state) return; // Invalid queue
6983 QueueId waited_queue = queue_state->GetQueueId();
6984
6985 // We need to go through every queue batch context and clear all accesses this wait synchronizes
6986 // As usual -- two groups, the "last batch" and the signaled semaphores
6987 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
6988 // QueueBatchContext, track which we've done to avoid duplicate traversals
6989 QueueBatchContext::BatchSet waited;
6990 for (auto &queue : queue_sync_states_) {
6991 auto batch = queue.second->LastBatch();
6992 if (batch) {
6993 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
6994 waited.emplace(batch);
6995 }
6996 }
6997
6998 for (const auto &signaled : signaled_semaphores_) {
6999 auto &sem_sig = signaled.second;
7000 if (sem_sig && sem_sig->batch && (waited.find(sem_sig->batch) == waited.end())) {
7001 sem_sig->batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
7002 waited.emplace(sem_sig->batch);
7003 }
7004 }
7005 // TODO: Update Events and Fences affected by Wait
7006}
7007
7008void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7009 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
7010 for (auto &queue : queue_sync_states_) {
7011 auto batch = queue.second->LastBatch();
7012 if (batch) {
7013 batch->ApplyDeviceWait();
7014 }
7015 }
7016
7017 auto wait_no_list = [](std::shared_ptr<QueueBatchContext> &batch) {
7018 batch->ApplyDeviceWait();
7019 return false;
7020 };
7021
7022 GetQueueLastBatchSnapshot(wait_no_list);
7023
7024 // TODO: Update Events and Fences affected by Wait
7025}
7026
John Zulauf697c0e12022-04-19 16:31:12 -06007027struct QueueSubmitCmdState {
7028 std::shared_ptr<const QueueSyncState> queue;
7029 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007030 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007031 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007032 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7033 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007034};
7035
7036template <>
7037thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7038
John Zulaufbbda4572022-04-19 16:20:45 -06007039bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7040 VkFence fence) const {
7041 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007042
7043 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007044 if (!enabled[sync_validation_queue_submit]) return skip;
7045
John Zulauf00119522022-05-23 19:07:42 -06007046 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007047 const auto fence_state = Get<FENCE_STATE>(fence);
7048 cmd_state->queue = GetQueueSyncStateShared(queue);
7049 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007050
John Zulauf697c0e12022-04-19 16:31:12 -06007051 const char *func_name = "vkQueueSubmit";
7052
7053 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7054 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7055
7056 // verify each submit batch
7057 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7058 // most recently created batch
7059 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7060 std::shared_ptr<QueueBatchContext> batch;
7061 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7062 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007063 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7064 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007065 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
7066
7067 // For each submit in the batch...
7068 for (const auto &cb : *batch) {
7069 skip |= cb.cb->ValidateFirstUse(batch.get(), func_name, cb.index);
7070
7071 // The barriers have already been applied in ValidatFirstUse
7072 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007073 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
John Zulauf697c0e12022-04-19 16:31:12 -06007074 }
7075
John Zulauf697c0e12022-04-19 16:31:12 -06007076 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7077 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007078 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007079 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007080 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7081 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7082 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007083 }
7084 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7085 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7086 last_batch = batch;
7087 }
7088 // The most recently created batch will become the queue's "last batch" in the record phase
7089 if (batch) {
7090 cmd_state->last_batch = std::move(batch);
7091 }
7092
7093 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007094 return skip;
7095}
7096
7097void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7098 VkResult result) {
7099 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007100
John Zulaufcb7e1672022-05-04 13:46:08 -06007101 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007102 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7103
John Zulaufcb7e1672022-05-04 13:46:08 -06007104 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7105 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007106 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007107
7108 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007109 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7110
John Zulauf697c0e12022-04-19 16:31:12 -06007111 // Don't need to look up the queue state again, but we need a non-const version
7112 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007113
John Zulaufcb7e1672022-05-04 13:46:08 -06007114 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7115 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7116 // QBC's are those referenced by unwaited signals and the last batch.
7117 for (auto &sig_sem : cmd_state->signaled) {
7118 if (sig_sem.second && sig_sem.second->batch) {
7119 sig_sem.second->batch->ResetAccessLog();
7120 }
7121 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007122 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007123 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007124
John Zulaufcb7e1672022-05-04 13:46:08 -06007125 // Update the queue to point to the last batch from the submit
7126 if (cmd_state->last_batch) {
7127 cmd_state->last_batch->ResetAccessLog();
7128 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007129 }
7130
7131 // Update the global access log from the one built during validation
7132 global_access_log_.MergeMove(std::move(cmd_state->logger));
7133
John Zulauf697c0e12022-04-19 16:31:12 -06007134
7135 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007136}
7137
7138bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7139 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007140 bool skip = false;
7141 if (!enabled[sync_validation_queue_submit]) return skip;
7142
John Zulauf697c0e12022-04-19 16:31:12 -06007143 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007144 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007145}
7146
7147void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7148 VkFence fence, VkResult result) {
7149 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007150 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7151
7152 if (!enabled[sync_validation_queue_submit]) return;
7153
John Zulauf697c0e12022-04-19 16:31:12 -06007154 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007155}
7156
John Zulaufd0ec59f2021-03-13 14:25:08 -07007157AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7158 : view_(view), view_mask_(), gen_store_() {
7159 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7160 const IMAGE_STATE &image_state = *view_->image_state.get();
7161 const auto base_address = ResourceBaseAddress(image_state);
7162 const auto *encoder = image_state.fragment_encoder.get();
7163 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007164 // Get offset and extent for the view, accounting for possible depth slicing
7165 const VkOffset3D zero_offset = view->GetOffset();
7166 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007167 // Intentional copy
7168 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7169 view_mask_ = subres_range.aspectMask;
7170 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address);
7171 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address);
7172
7173 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7174 if (depth && (depth != view_mask_)) {
7175 subres_range.aspectMask = depth;
7176 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address);
7177 }
7178 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7179 if (stencil && (stencil != view_mask_)) {
7180 subres_range.aspectMask = stencil;
7181 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address);
7182 }
7183}
7184
7185const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7186 const ImageRangeGen *got = nullptr;
7187 switch (gen_type) {
7188 case kViewSubresource:
7189 got = &gen_store_[kViewSubresource];
7190 break;
7191 case kRenderArea:
7192 got = &gen_store_[kRenderArea];
7193 break;
7194 case kDepthOnlyRenderArea:
7195 got =
7196 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7197 break;
7198 case kStencilOnlyRenderArea:
7199 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7200 : &gen_store_[Gen::kStencilOnlyRenderArea];
7201 break;
7202 default:
7203 assert(got);
7204 }
7205 return got;
7206}
7207
7208AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7209 assert(IsValid());
7210 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7211 if (depth_op) {
7212 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7213 if (stencil_op) {
7214 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7215 return kRenderArea;
7216 }
7217 return kDepthOnlyRenderArea;
7218 }
7219 if (stencil_op) {
7220 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7221 return kStencilOnlyRenderArea;
7222 }
7223
7224 assert(depth_op || stencil_op);
7225 return kRenderArea;
7226}
7227
7228AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007229
7230void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
7231 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7232 for (auto &event_pair : map_) {
7233 assert(event_pair.second); // Shouldn't be storing empty
7234 auto &sync_event = *event_pair.second;
7235 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
7236 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
7237 sync_event.barriers |= dst.exec_scope;
7238 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7239 }
7240 }
7241}
John Zulaufbb890452021-12-14 11:30:18 -07007242
7243ReplayTrackbackBarriersAction::ReplayTrackbackBarriersAction(VkQueueFlags queue_flags,
7244 const SubpassDependencyGraphNode &subpass_dep,
7245 const std::vector<ReplayTrackbackBarriersAction> &replay_contexts) {
7246 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
7247 trackback_barriers.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
7248 for (const auto &prev_dep : subpass_dep.prev) {
7249 const auto prev_pass = prev_dep.first->pass;
7250 const auto &prev_barriers = prev_dep.second;
7251 trackback_barriers.emplace_back(&replay_contexts[prev_pass], queue_flags, prev_barriers);
7252 }
7253 if (has_barrier_from_external) {
7254 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
7255 trackback_barriers.emplace_back(nullptr, queue_flags, subpass_dep.barrier_from_external);
7256 }
7257}
7258
7259void ReplayTrackbackBarriersAction::operator()(ResourceAccessState *access) const {
7260 if (trackback_barriers.size() == 1) {
7261 trackback_barriers[0](access);
7262 } else {
7263 ResourceAccessState resolved;
7264 for (const auto &trackback : trackback_barriers) {
7265 ResourceAccessState access_copy = *access;
7266 trackback(&access_copy);
7267 resolved.Resolve(access_copy);
7268 }
7269 *access = resolved;
7270 }
7271}
7272
7273ReplayTrackbackBarriersAction::TrackbackBarriers::TrackbackBarriers(
7274 const ReplayTrackbackBarriersAction *source_subpass_, VkQueueFlags queue_flags_,
7275 const std::vector<const VkSubpassDependency2 *> &subpass_dependencies_)
7276 : Base(source_subpass_, queue_flags_, subpass_dependencies_) {}
7277
7278void ReplayTrackbackBarriersAction::TrackbackBarriers::operator()(ResourceAccessState *access) const {
7279 if (source_subpass) {
7280 (*source_subpass)(access);
7281 }
7282 access->ApplyBarriersImmediate(barriers);
7283}
John Zulauf697c0e12022-04-19 16:31:12 -06007284
John Zulaufcb7e1672022-05-04 13:46:08 -06007285QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
7286 : CommandExecutionContext(&sync_state), queue_state_(&queue_state), tag_range_(0, 0), batch_log_(nullptr) {}
7287
John Zulauf697c0e12022-04-19 16:31:12 -06007288template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007289void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7290 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007291 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007292 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007293}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007294void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
7295 QueueId queue_id = queue_state_->GetQueueId();
7296 auto tag_queue_op = [offset, queue_id](ResourceAccessState *access) {
7297 access->OffsetTag(offset);
7298 access->SetQueueId(queue_id);
7299 };
7300 GetCurrentAccessContext()->ResolveFromContext(tag_queue_op, recorded_context);
7301}
John Zulauf697c0e12022-04-19 16:31:12 -06007302
7303VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7304
John Zulauf1d5f9c12022-05-13 14:51:08 -06007305void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7306 QueueWaitWorm wait_worm(queue_id);
7307 access_context_.ForAll(wait_worm);
7308 if (wait_worm.erase_all) {
7309 access_context_.Reset();
7310 } else {
7311 // TODO: Profiling will tell us if we need a more efficient clean up.
7312 for (const auto &address : wait_worm.erase_list) {
7313 access_context_.DeleteAccess(address);
7314 }
7315 }
7316}
7317
7318// Clear all accesses
7319void QueueBatchContext::ApplyDeviceWait() { access_context_.Reset(); }
7320
John Zulaufcb7e1672022-05-04 13:46:08 -06007321void QueueBatchContext::WaitOneSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask, WaitBatchMap &batch_trackbacks,
7322 SignaledSemaphores &signaled) {
7323 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
7324 if (!sem_state) return; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007325
John Zulaufcb7e1672022-05-04 13:46:08 -06007326 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7327 auto signal_state = signaled.Unsignal(sem);
7328 if (!signal_state) return; // Invalid signal, skip it.
7329
7330 const auto &sem_batch = signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007331 assert(sem_batch);
7332
7333 const AccessContext *sem_context = sem_batch->GetCurrentAccessContext();
7334
7335 using TrackBackPtr = AccessContext::TrackBack *;
John Zulaufcb7e1672022-05-04 13:46:08 -06007336 const auto trackback_insert = batch_trackbacks.emplace(sem_batch.get(), TrackBackPtr());
John Zulauf697c0e12022-04-19 16:31:12 -06007337 const bool inserted = trackback_insert.second;
7338 const auto trackback_it = trackback_insert.first;
7339
John Zulaufcb7e1672022-05-04 13:46:08 -06007340 const SyncExecScope &sem_scope = signal_state->exec_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007341 const auto queue_flags = queue_state_->GetQueueFlags();
7342 SyncExecScope dst_mask = SyncExecScope::MakeDst(queue_flags, wait_mask);
7343 const SyncBarrier sem_barrier(sem_scope, sem_scope.valid_accesses, dst_mask, SyncStageAccessFlags());
7344 if (inserted) {
7345 // If this is the first time we referenced this QueueBatchContext
7346 trackback_it->second = access_context_.AddTrackBack(sem_context, sem_barrier);
7347 }
7348 assert(trackback_it->second);
7349 trackback_it->second->barriers.emplace_back(sem_barrier);
7350}
7351
7352// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7353template <>
7354class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7355 public:
7356 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7357 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7358 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7359 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7360 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7361 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7362
7363 private:
7364 const VkSubmitInfo &info_;
7365};
7366template <typename BatchInfo, typename Fn>
7367void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7368 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7369 Accessor batch(batch_info);
7370 const uint32_t wait_count = batch.WaitSemaphoreCount();
7371 for (uint32_t i = 0; i < wait_count; ++i) {
7372 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7373 }
7374}
7375
7376template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007377void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7378 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007379 // Create trackbacks for the access context for this batch based on the semaphores and the previous batch in this
7380 // queue.
7381 WaitBatchMap batch_trackbacks;
John Zulaufcb7e1672022-05-04 13:46:08 -06007382 ForEachWaitSemaphore(batch_info, [this, &batch_trackbacks, &signaled](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7383 WaitOneSemaphore(sem, wait_mask, batch_trackbacks, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007384 });
7385
John Zulauf78cb2082022-04-20 16:37:48 -06007386 // If there are no semaphores to the previous batch, make sure a "submit order" empty trackback is added
7387 if (prev && (batch_trackbacks.find(prev.get()) == batch_trackbacks.end())) {
7388 access_context_.AddTrackBack(prev->GetCurrentAccessContext(), SyncBarrier());
7389 }
7390
John Zulauf697c0e12022-04-19 16:31:12 -06007391 // Flatten all previous contexts into the current one (for dependency chaining reasons)
7392 access_context_.ResolvePreviousAccesses();
7393 access_context_.ClearTrackBacks();
7394
7395 // Gather async context information for hazard checks and conserve the QBC's for the async batches
7396 const auto end_it = batch_trackbacks.end();
John Zulauf78cb2082022-04-20 16:37:48 -06007397 async_batches_ = sync_state_->GetQueueLastBatchSnapshot(
7398 [&batch_trackbacks, end_it, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
John Zulauf697c0e12022-04-19 16:31:12 -06007399 const auto found_it = batch_trackbacks.find(batch.get());
John Zulauf78cb2082022-04-20 16:37:48 -06007400 return found_it == end_it && (batch != prev);
John Zulauf697c0e12022-04-19 16:31:12 -06007401 });
7402 for (const auto &async_batch : async_batches_) {
7403 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7404 }
7405}
7406
7407template <typename BatchInfo>
7408void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7409 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7410 Accessor batch(batch_info);
7411
7412 // Create the list of command buffers to submit
7413 const uint32_t cb_count = batch.CommandBufferCount();
7414 command_buffers_.reserve(cb_count);
7415 for (uint32_t index = 0; index < cb_count; ++index) {
7416 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7417 if (cb_context) {
7418 tag_range_.end += cb_context->GetTagLimit();
7419 command_buffers_.emplace_back(index, std::move(cb_context));
7420 }
7421 }
7422}
7423
7424// Look up the usage informaiton from the local or global logger
7425std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7426 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7427 std::stringstream out;
7428 AccessLogger::AccessRecord access = use_logger[tag];
7429 if (access.IsValid()) {
7430 const AccessLogger::BatchRecord &batch = *access.batch;
7431 const ResourceUsageRecord &record = *access.record;
7432 // Queue and Batch information
7433 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7434 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7435
7436 // Commandbuffer Usages Information
7437 out << record;
7438 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7439 out << ", reset_no: " << std::to_string(record.reset_count);
7440 }
7441 return out.str();
7442}
7443
7444VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7445
John Zulauf00119522022-05-23 19:07:42 -06007446QueueId QueueBatchContext::GetQueueId() const {
7447 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7448 return id;
7449}
7450
John Zulauf697c0e12022-04-19 16:31:12 -06007451void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7452 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7453 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7454 SetTagBias(global_tags.begin);
7455 // Add an access log for the batches range and point the batch at it.
7456 logger_ = &logger;
7457 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7458}
7459
7460void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7461 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7462 batch_log_->Append(submitted_cb.GetAccessLog());
7463}
7464
7465void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7466 const auto size = tag_range_.size();
7467 tag_range_.begin = bias;
7468 tag_range_.end = bias + size;
7469 access_context_.SetStartTag(bias);
7470}
7471
John Zulauf1d5f9c12022-05-13 14:51:08 -06007472QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7473
7474void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7475 bool erased = access.second.ApplyQueueTagWait(predicate);
7476 if (erased) {
7477 erase_list.emplace_back(address_type, access.first);
7478 } else {
7479 erase_all = false;
7480 }
7481}
7482
John Zulauf697c0e12022-04-19 16:31:12 -06007483AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7484 const ResourceUsageRange &range) {
7485 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7486 assert(inserted.second);
7487 return &inserted.first->second;
7488}
7489
7490void AccessLogger::MergeMove(AccessLogger &&child) {
7491 for (auto &range : child.access_log_map_) {
7492 BatchLog &child_batch = range.second;
7493 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7494 insert_pair.first->second = std::move(child_batch);
7495 assert(insert_pair.second);
7496 }
7497 child.Reset();
7498}
7499
7500void AccessLogger::Reset() {
7501 prev_ = nullptr;
7502 access_log_map_.clear();
7503}
7504
7505// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7506// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7507// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7508// the contexts Resolve all history from previous all contexts when created
7509void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7510 last_batch_ = std::move(last);
7511 last_batch_->ResetAccessLog();
7512}
7513
7514// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7515// scope state.
7516// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7517// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7518uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7519
7520void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7521 log_.insert(log_.end(), other.cbegin(), other.cend());
7522 for (const auto &record : other) {
7523 assert(record.cb_state);
7524 cbs_referenced_.insert(record.cb_state->shared_from_this());
7525 }
7526}
7527
7528AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7529 assert(index < log_.size());
7530 return AccessRecord{&batch_, &log_[index]};
7531}
7532
7533AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7534 AccessRecord access_record = {nullptr, nullptr};
7535
7536 auto found_range = access_log_map_.find(tag);
7537 if (found_range != access_log_map_.cend()) {
7538 const ResourceUsageTag bias = found_range->first.begin;
7539 assert(tag >= bias);
7540 access_record = found_range->second[tag - bias];
7541 } else if (prev_) {
7542 access_record = (*prev_)[tag];
7543 }
7544
7545 return access_record;
7546}
John Zulaufcb7e1672022-05-04 13:46:08 -06007547
7548std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
7549 std::shared_ptr<Signal> prev_state;
7550 if (prev_) {
7551 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7552 }
7553 return prev_state;
7554}