blob: 3335058f18fa5937a80cf9b6d62628eec4428a65 [file] [log] [blame]
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001/* Copyright (c) 2019-2022 The Khronos Group Inc.
2 * Copyright (c) 2019-2022 Valve Corporation
3 * Copyright (c) 2019-2022 LunarG, Inc.
John Zulauf9cb530d2019-09-30 14:14:10 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: John Zulauf <jzulauf@lunarg.com>
John Zulaufab7756b2020-12-29 16:10:16 -070018 * Author: Locke Lin <locke@lunarg.com>
19 * Author: Jeremy Gebben <jeremyg@lunarg.com>
John Zulauf9cb530d2019-09-30 14:14:10 -060020 */
21
22#include <limits>
23#include <vector>
locke-lunarg296a3c92020-03-25 01:04:29 -060024#include <memory>
25#include <bitset>
John Zulauf9cb530d2019-09-30 14:14:10 -060026#include "synchronization_validation.h"
Jeremy Gebben5f585ae2021-02-02 09:03:06 -070027#include "sync_utils.h"
John Zulauf9cb530d2019-09-30 14:14:10 -060028
John Zulaufea943c52022-02-22 11:05:17 -070029// Utilities to DRY up Get... calls
30template <typename Map, typename Key = typename Map::key_type, typename RetVal = layer_data::optional<typename Map::mapped_type>>
31RetVal GetMappedOptional(const Map &map, const Key &key) {
32 RetVal ret_val;
33 auto it = map.find(key);
34 if (it != map.cend()) {
35 ret_val.emplace(it->second);
36 }
37 return ret_val;
38}
39template <typename Map, typename Fn>
40typename Map::mapped_type GetMapped(const Map &map, const typename Map::key_type &key, Fn &&default_factory) {
41 auto value = GetMappedOptional(map, key);
42 return (value) ? *value : default_factory();
43}
44
45template <typename Map, typename Fn>
John Zulauf397e68b2022-04-19 11:44:07 -060046typename Map::mapped_type GetMappedInsert(Map &map, const typename Map::key_type &key, Fn &&emplace_factory) {
John Zulaufea943c52022-02-22 11:05:17 -070047 auto value = GetMappedOptional(map, key);
48 if (value) {
49 return *value;
50 }
John Zulauf397e68b2022-04-19 11:44:07 -060051 auto insert_it = map.emplace(std::make_pair(key, emplace_factory()));
John Zulaufea943c52022-02-22 11:05:17 -070052 assert(insert_it.second);
53
54 return insert_it.first->second;
55}
56
57template <typename Map, typename Key = typename Map::key_type, typename Mapped = typename Map::mapped_type,
58 typename Value = typename Mapped::element_type>
59Value *GetMappedPlainFromShared(const Map &map, const Key &key) {
60 auto value = GetMappedOptional<Map, Key>(map, key);
61 if (value) return value->get();
62 return nullptr;
63}
64
Jeremy Gebben6fbf8242021-06-21 09:14:46 -060065static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.Binding(); }
John Zulauf264cce02021-02-05 14:40:47 -070066
John Zulauf29d00532021-03-04 13:28:54 -070067static bool SimpleBinding(const IMAGE_STATE &image_state) {
Jeremy Gebben62c3bf42021-07-21 15:38:24 -060068 bool simple =
Jeremy Gebben82e11d52021-07-26 09:19:37 -060069 SimpleBinding(static_cast<const BINDABLE &>(image_state)) || image_state.IsSwapchainImage() || image_state.bind_swapchain;
John Zulauf29d00532021-03-04 13:28:54 -070070
71 // If it's not simple we must have an encoder.
72 assert(!simple || image_state.fragment_encoder.get());
73 return simple;
74}
75
John Zulauf4fa68462021-04-26 21:04:22 -060076static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
77static const std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
John Zulauf43cc7462020-12-03 12:33:12 -070078 AccessAddressType::kLinear, AccessAddressType::kIdealized};
79
John Zulaufd5115702021-01-18 12:34:33 -070080static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
John Zulauf264cce02021-02-05 14:40:47 -070081static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) {
82 return SimpleBinding(image) ? AccessContext::ImageAddressType(image) : AccessAddressType::kIdealized;
83}
John Zulaufd5115702021-01-18 12:34:33 -070084
John Zulauf9cb530d2019-09-30 14:14:10 -060085static const char *string_SyncHazardVUID(SyncHazard hazard) {
86 switch (hazard) {
87 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070088 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060089 break;
90 case SyncHazard::READ_AFTER_WRITE:
91 return "SYNC-HAZARD-READ_AFTER_WRITE";
92 break;
93 case SyncHazard::WRITE_AFTER_READ:
94 return "SYNC-HAZARD-WRITE_AFTER_READ";
95 break;
96 case SyncHazard::WRITE_AFTER_WRITE:
97 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
98 break;
John Zulauf2f952d22020-02-10 11:34:51 -070099 case SyncHazard::READ_RACING_WRITE:
100 return "SYNC-HAZARD-READ-RACING-WRITE";
101 break;
102 case SyncHazard::WRITE_RACING_WRITE:
103 return "SYNC-HAZARD-WRITE-RACING-WRITE";
104 break;
105 case SyncHazard::WRITE_RACING_READ:
106 return "SYNC-HAZARD-WRITE-RACING-READ";
107 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600108 default:
109 assert(0);
110 }
111 return "SYNC-HAZARD-INVALID";
112}
113
John Zulauf59e25072020-07-17 10:55:21 -0600114static bool IsHazardVsRead(SyncHazard hazard) {
115 switch (hazard) {
116 case SyncHazard::NONE:
117 return false;
118 break;
119 case SyncHazard::READ_AFTER_WRITE:
120 return false;
121 break;
122 case SyncHazard::WRITE_AFTER_READ:
123 return true;
124 break;
125 case SyncHazard::WRITE_AFTER_WRITE:
126 return false;
127 break;
128 case SyncHazard::READ_RACING_WRITE:
129 return false;
130 break;
131 case SyncHazard::WRITE_RACING_WRITE:
132 return false;
133 break;
134 case SyncHazard::WRITE_RACING_READ:
135 return true;
136 break;
137 default:
138 assert(0);
139 }
140 return false;
141}
142
John Zulauf9cb530d2019-09-30 14:14:10 -0600143static const char *string_SyncHazard(SyncHazard hazard) {
144 switch (hazard) {
145 case SyncHazard::NONE:
146 return "NONR";
147 break;
148 case SyncHazard::READ_AFTER_WRITE:
149 return "READ_AFTER_WRITE";
150 break;
151 case SyncHazard::WRITE_AFTER_READ:
152 return "WRITE_AFTER_READ";
153 break;
154 case SyncHazard::WRITE_AFTER_WRITE:
155 return "WRITE_AFTER_WRITE";
156 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700157 case SyncHazard::READ_RACING_WRITE:
158 return "READ_RACING_WRITE";
159 break;
160 case SyncHazard::WRITE_RACING_WRITE:
161 return "WRITE_RACING_WRITE";
162 break;
163 case SyncHazard::WRITE_RACING_READ:
164 return "WRITE_RACING_READ";
165 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600166 default:
167 assert(0);
168 }
169 return "INVALID HAZARD";
170}
171
John Zulauf37ceaed2020-07-03 16:18:15 -0600172static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
173 // Return the info for the first bit found
174 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700175 for (size_t i = 0; i < flags.size(); i++) {
176 if (flags.test(i)) {
177 info = &syncStageAccessInfoByStageAccessIndex[i];
178 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600179 }
180 }
181 return info;
182}
183
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700184static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600185 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700186 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600187 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700188 } else {
189 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
190 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
191 if ((flags & info.stage_access_bit).any()) {
192 if (!out_str.empty()) {
193 out_str.append(sep);
194 }
195 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600196 }
John Zulauf59e25072020-07-17 10:55:21 -0600197 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700198 if (out_str.length() == 0) {
199 out_str.append("Unhandled SyncStageAccess");
200 }
John Zulauf59e25072020-07-17 10:55:21 -0600201 }
202 return out_str;
203}
204
John Zulauf397e68b2022-04-19 11:44:07 -0600205std::ostream &operator<<(std::ostream &out, const ResourceUsageRecord &record) {
206 out << "command: " << CommandTypeString(record.command);
207 out << ", seq_no: " << record.seq_num;
208 if (record.sub_command != 0) {
209 out << ", subcmd: " << record.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700210 }
John Zulauf397e68b2022-04-19 11:44:07 -0600211 return out;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700212}
John Zulauf397e68b2022-04-19 11:44:07 -0600213
John Zulauf4fa68462021-04-26 21:04:22 -0600214static std::string string_UsageIndex(SyncStageAccessIndex usage_index) {
215 const char *stage_access_name = "INVALID_STAGE_ACCESS";
216 if (usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size())) {
217 stage_access_name = syncStageAccessInfoByStageAccessIndex[usage_index].name;
218 }
219 return std::string(stage_access_name);
220}
221
John Zulauf397e68b2022-04-19 11:44:07 -0600222struct SyncNodeFormatter {
223 const debug_report_data *report_data;
224 const BASE_NODE *node;
225 const char *label;
226
227 SyncNodeFormatter(const SyncValidator &sync_state, const CMD_BUFFER_STATE *cb_state)
228 : report_data(sync_state.report_data), node(cb_state), label("command_buffer") {}
229 SyncNodeFormatter(const SyncValidator &sync_state, const QUEUE_STATE *q_state)
230 : report_data(sync_state.report_data), node(q_state), label("queue") {}
231};
232
233std::ostream &operator<<(std::ostream &out, const SyncNodeFormatter &formater) {
234 if (formater.node) {
235 out << ", " << formater.label << ": " << formater.report_data->FormatHandle(formater.node->Handle()).c_str();
236 if (formater.node->Destroyed()) {
237 out << " (destroyed)";
238 }
239 } else {
240 out << ", " << formater.label << ": null handle";
241 }
242 return out;
243}
244
245std::ostream &operator<<(std::ostream &out, const HazardResult &hazard) {
246 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
247 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
248 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
249 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
250 out << "(";
251 if (!hazard.recorded_access.get()) {
252 // if we have a recorded usage the usage is reported from the recorded contexts point of view
253 out << "usage: " << usage_info.name << ", ";
254 }
255 out << "prior_usage: " << stage_access_name;
256 if (IsHazardVsRead(hazard.hazard)) {
257 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
258 out << ", read_barriers: " << string_VkPipelineStageFlags2KHR(barriers);
259 } else {
260 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
261 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
262 }
263 return out;
264}
265
John Zulauf4fa68462021-04-26 21:04:22 -0600266struct NoopBarrierAction {
267 explicit NoopBarrierAction() {}
268 void operator()(ResourceAccessState *access) const {}
John Zulauf5c628d02021-05-04 15:46:36 -0600269 const bool layout_transition = false;
John Zulauf4fa68462021-04-26 21:04:22 -0600270};
271
272// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
273CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
274 : CommandBufferAccessContext(from.sync_state_) {
275 // Copy only the needed fields out of from for a temporary, proxy command buffer context
276 cb_state_ = from.cb_state_;
277 queue_flags_ = from.queue_flags_;
278 destroyed_ = from.destroyed_;
279 access_log_ = from.access_log_; // potentially large, but no choice given tagging lookup.
280 command_number_ = from.command_number_;
281 subcommand_number_ = from.subcommand_number_;
282 reset_count_ = from.reset_count_;
283
284 const auto *from_context = from.GetCurrentAccessContext();
285 assert(from_context);
286
287 // Construct a fully resolved single access context out of from
288 const NoopBarrierAction noop_barrier;
289 for (AccessAddressType address_type : kAddressTypes) {
290 from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
291 &cb_access_context_.GetAccessStateMap(address_type), nullptr);
292 }
293 // The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
294 cb_access_context_.ImportAsyncContexts(*from_context);
295
296 events_context_ = from.events_context_;
297
298 // We don't want to copy the full render_pass_context_ history just for the proxy.
299}
300
301std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
John Zulauf397e68b2022-04-19 11:44:07 -0600302 if (tag >= access_log_.size()) return std::string();
303
John Zulauf4fa68462021-04-26 21:04:22 -0600304 std::stringstream out;
305 assert(tag < access_log_.size());
306 const auto &record = access_log_[tag];
John Zulauf397e68b2022-04-19 11:44:07 -0600307 out << record;
308 if (cb_state_.get() != record.cb_state) {
309 out << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf4fa68462021-04-26 21:04:22 -0600310 }
John Zulaufd142c9a2022-04-12 14:22:44 -0600311 out << ", reset_no: " << std::to_string(record.reset_count);
John Zulauf4fa68462021-04-26 21:04:22 -0600312 return out.str();
313}
John Zulauf397e68b2022-04-19 11:44:07 -0600314
John Zulauf4fa68462021-04-26 21:04:22 -0600315std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
316 std::stringstream out;
317 out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
318 out << ", " << FormatUsage(access.tag) << ")";
319 return out.str();
320}
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700321
John Zulauf397e68b2022-04-19 11:44:07 -0600322std::string CommandExecutionContext::FormatHazard(const HazardResult &hazard) const {
John Zulauf1dae9192020-06-16 15:46:44 -0600323 std::stringstream out;
John Zulauf397e68b2022-04-19 11:44:07 -0600324 out << hazard;
325 out << ", " << FormatUsage(hazard.tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600326 return out.str();
327}
328
John Zulaufd14743a2020-07-03 09:42:39 -0600329// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
330// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
331// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700332static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700333static const SyncStageAccessFlags kColorAttachmentAccessScope =
334 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
335 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
336 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
337 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700338static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
339 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700340static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
341 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
342 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
343 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700344static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700345static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600346
John Zulauf8e3c3e92021-01-06 11:19:36 -0700347ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700348 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700349 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
350 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
351 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
352
John Zulaufee984022022-04-13 16:39:50 -0600353// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
354static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600355
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600356static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600357
John Zulaufcb7e1672022-05-04 13:46:08 -0600358VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600359 if (size == VK_WHOLE_SIZE) {
360 return (whole_size - offset);
361 }
362 return size;
363}
364
John Zulauf3e86bf02020-09-12 10:47:57 -0600365static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
366 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
367}
368
John Zulauf16adfc92020-04-08 10:28:33 -0600369template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600370static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600371 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
372}
373
John Zulauf355e49b2020-04-24 15:11:15 -0600374static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600375
John Zulauf3e86bf02020-09-12 10:47:57 -0600376static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
377 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
378}
379
380static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
381 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
382}
383
John Zulauf4a6105a2020-11-17 15:11:05 -0700384// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
385//
John Zulauf10f1f522020-12-18 12:00:35 -0700386// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
387//
John Zulauf4a6105a2020-11-17 15:11:05 -0700388// Usage:
389// Constructor() -- initializes the generator to point to the begin of the space declared.
390// * -- the current range of the generator empty signfies end
391// ++ -- advance to the next non-empty range (or end)
392
393// A wrapper for a single range with the same semantics as the actual generators below
394template <typename KeyType>
395class SingleRangeGenerator {
396 public:
397 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700398 const KeyType &operator*() const { return current_; }
399 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700400 SingleRangeGenerator &operator++() {
401 current_ = KeyType(); // just one real range
402 return *this;
403 }
404
405 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
406
407 private:
408 SingleRangeGenerator() = default;
409 const KeyType range_;
410 KeyType current_;
411};
412
John Zulaufae842002021-04-15 18:20:55 -0600413// Generate the ranges that are the intersection of range and the entries in the RangeMap
414template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
415class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700416 public:
John Zulaufd5115702021-01-18 12:34:33 -0700417 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600418 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700419 // Default construction for KeyType *must* be empty range
420 assert(current_.empty());
421 }
John Zulaufae842002021-04-15 18:20:55 -0600422 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700423 SeekBegin();
424 }
John Zulaufae842002021-04-15 18:20:55 -0600425 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700426
John Zulauf4a6105a2020-11-17 15:11:05 -0700427 const KeyType &operator*() const { return current_; }
428 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600429 MapRangesRangeGenerator &operator++() {
430 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700431 UpdateCurrent();
432 return *this;
433 }
434
John Zulaufae842002021-04-15 18:20:55 -0600435 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700436
John Zulaufae842002021-04-15 18:20:55 -0600437 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700438 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600439 if (map_pos_ != map_->cend()) {
440 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700441 } else {
442 current_ = KeyType();
443 }
444 }
445 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600446 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700447 UpdateCurrent();
448 }
John Zulaufae842002021-04-15 18:20:55 -0600449
450 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
451 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
452 template <typename Pred>
453 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
454 do {
455 ++map_pos_;
456 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
457 UpdateCurrent();
458 return *this;
459 }
460
John Zulauf4a6105a2020-11-17 15:11:05 -0700461 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600462 const RangeMap *map_;
463 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700464 KeyType current_;
465};
John Zulaufd5115702021-01-18 12:34:33 -0700466using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600467using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700468
John Zulaufae842002021-04-15 18:20:55 -0600469// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
470template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
471class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
472 public:
473 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
474 // Default constructed is safe to dereference for "empty" test, but for no other operation.
475 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
476 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
477 : Base(filter, range), pred_(pred) {}
478 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
479
480 PredicatedMapRangesRangeGenerator &operator++() {
481 Base::PredicatedIncrement(pred_);
482 return *this;
483 }
484
485 protected:
486 Predicate pred_;
487};
John Zulauf4a6105a2020-11-17 15:11:05 -0700488
489// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600490// Templated to allow for different Range generators or map sources...
491template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700492class FilteredGeneratorGenerator {
493 public:
John Zulaufd5115702021-01-18 12:34:33 -0700494 // Default constructed is safe to dereference for "empty" test, but for no other operation.
495 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
496 // Default construction for KeyType *must* be empty range
497 assert(current_.empty());
498 }
John Zulaufae842002021-04-15 18:20:55 -0600499 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700500 SeekBegin();
501 }
John Zulaufd5115702021-01-18 12:34:33 -0700502 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700503 const KeyType &operator*() const { return current_; }
504 const KeyType *operator->() const { return &current_; }
505 FilteredGeneratorGenerator &operator++() {
506 KeyType gen_range = GenRange();
507 KeyType filter_range = FilterRange();
508 current_ = KeyType();
509 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
510 if (gen_range.end > filter_range.end) {
511 // if the generated range is beyond the filter_range, advance the filter range
512 filter_range = AdvanceFilter();
513 } else {
514 gen_range = AdvanceGen();
515 }
516 current_ = gen_range & filter_range;
517 }
518 return *this;
519 }
520
521 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
522
523 private:
524 KeyType AdvanceFilter() {
525 ++filter_pos_;
526 auto filter_range = FilterRange();
527 if (filter_range.valid()) {
528 FastForwardGen(filter_range);
529 }
530 return filter_range;
531 }
532 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700533 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700534 auto gen_range = GenRange();
535 if (gen_range.valid()) {
536 FastForwardFilter(gen_range);
537 }
538 return gen_range;
539 }
540
541 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700542 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700543
544 KeyType FastForwardFilter(const KeyType &range) {
545 auto filter_range = FilterRange();
546 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700547 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700548 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
549 if (retry_count < kRetryLimit) {
550 ++filter_pos_;
551 filter_range = FilterRange();
552 retry_count++;
553 } else {
554 // Okay we've tried walking, do a seek.
555 filter_pos_ = filter_->lower_bound(range);
556 break;
557 }
558 }
559 return FilterRange();
560 }
561
562 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
563 // faster.
564 KeyType FastForwardGen(const KeyType &range) {
565 auto gen_range = GenRange();
566 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700567 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700568 gen_range = GenRange();
569 }
570 return gen_range;
571 }
572
573 void SeekBegin() {
574 auto gen_range = GenRange();
575 if (gen_range.empty()) {
576 current_ = KeyType();
577 filter_pos_ = filter_->cend();
578 } else {
579 filter_pos_ = filter_->lower_bound(gen_range);
580 current_ = gen_range & FilterRange();
581 }
582 }
583
John Zulaufae842002021-04-15 18:20:55 -0600584 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700585 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600586 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700587 KeyType current_;
588};
589
590using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
591
John Zulauf5c5e88d2019-12-26 11:22:02 -0700592
John Zulauf3e86bf02020-09-12 10:47:57 -0600593ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
594 VkDeviceSize stride) {
595 VkDeviceSize range_start = offset + first_index * stride;
596 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600597 if (count == UINT32_MAX) {
598 range_size = buf_whole_size - range_start;
599 } else {
600 range_size = count * stride;
601 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600602 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600603}
604
locke-lunarg654e3692020-06-04 17:19:15 -0600605SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
606 VkShaderStageFlagBits stage_flag) {
607 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
608 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
609 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
610 }
611 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
612 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
613 assert(0);
614 }
615 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
616 return stage_access->second.uniform_read;
617 }
618
619 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
620 // Because if write hazard happens, read hazard might or might not happen.
621 // But if write hazard doesn't happen, read hazard is impossible to happen.
622 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700623 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600624 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700625 // TODO: sampled_read
626 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600627}
628
locke-lunarg37047832020-06-12 13:44:45 -0600629bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
630 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
631 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
632 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
633 ? true
634 : false;
635}
636
637bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
638 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
639 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
640 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
641 ? true
642 : false;
643}
644
John Zulauf355e49b2020-04-24 15:11:15 -0600645// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600646template <typename Action>
647static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
648 Action &action) {
649 // At this point the "apply over range" logic only supports a single memory binding
650 if (!SimpleBinding(image_state)) return;
651 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600652 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700653 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
Aitor Camachoe67f2c72022-06-08 14:41:58 +0200654 image_state.createInfo.extent, base_address, false);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600655 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700656 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600657 }
658}
659
John Zulauf7635de32020-05-29 17:14:15 -0600660// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
661// Used by both validation and record operations
662//
663// The signature for Action() reflect the needs of both uses.
664template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700665void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
666 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600667 const auto &rp_ci = rp_state.createInfo;
668 const auto *attachment_ci = rp_ci.pAttachments;
669 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
670
671 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
672 const auto *color_attachments = subpass_ci.pColorAttachments;
673 const auto *color_resolve = subpass_ci.pResolveAttachments;
674 if (color_resolve && color_attachments) {
675 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
676 const auto &color_attach = color_attachments[i].attachment;
677 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
678 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
679 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700680 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
681 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600682 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700683 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
684 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600685 }
686 }
687 }
688
689 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700690 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600691 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
692 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
693 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
694 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
695 const auto src_ci = attachment_ci[src_at];
696 // The formats are required to match so we can pick either
697 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
698 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
699 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600700
701 // Figure out which aspects are actually touched during resolve operations
702 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700703 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600704 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600705 aspect_string = "depth/stencil";
706 } else if (resolve_depth) {
707 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700708 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600709 aspect_string = "depth";
710 } else if (resolve_stencil) {
711 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700712 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600713 aspect_string = "stencil";
714 }
715
John Zulaufd0ec59f2021-03-13 14:25:08 -0700716 if (aspect_string) {
717 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
718 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
719 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
720 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600721 }
722 }
723}
724
725// Action for validating resolve operations
726class ValidateResolveAction {
727 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700728 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
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,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001385 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001386 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,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001389 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001390 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,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001399 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1400 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001401 if (!SimpleBinding(image)) return HazardResult();
1402 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001403 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1404 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001405 const auto address_type = ImageAddressType(image);
1406 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001407 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1408 if (hazard.hazard) return hazard;
1409 }
1410 return HazardResult();
1411}
John Zulauf69133422020-05-20 14:55:53 -06001412
John Zulauf540266b2020-04-06 18:54:53 -06001413HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1414 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001415 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001416 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1417 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001418 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001419 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001420}
1421
1422HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001423 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001424 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001425 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001426}
1427
John Zulaufd0ec59f2021-03-13 14:25:08 -07001428HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1429 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1430 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1431 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1432}
1433
John Zulauf69133422020-05-20 14:55:53 -06001434HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001435 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001436 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001437 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001438 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001439}
1440
John Zulauf3d84f1b2020-03-09 13:33:25 -06001441class BarrierHazardDetector {
1442 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001443 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001444 SyncStageAccessFlags src_access_scope)
1445 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1446
John Zulauf5f13a792020-03-10 07:31:21 -06001447 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1448 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001449 }
John Zulauf14940722021-04-12 15:19:02 -06001450 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001451 // 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 -07001452 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001453 }
1454
1455 private:
1456 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001457 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001458 SyncStageAccessFlags src_access_scope_;
1459};
1460
John Zulauf4a6105a2020-11-17 15:11:05 -07001461class EventBarrierHazardDetector {
1462 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001463 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001464 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope,
John Zulauf14940722021-04-12 15:19:02 -06001465 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001466 : usage_index_(usage_index),
1467 src_exec_scope_(src_exec_scope),
1468 src_access_scope_(src_access_scope),
1469 event_scope_(event_scope),
1470 scope_pos_(event_scope.cbegin()),
1471 scope_end_(event_scope.cend()),
1472 scope_tag_(scope_tag) {}
1473
1474 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
1475 // TODO NOTE: This is almost the slowest way to do this... need to intelligently walk this...
1476 // Need to find a more efficient sync, since we know pos->first is strictly increasing call to call
1477 // NOTE: "cached_lower_bound_impl" with upgrades could do this.
1478 if (scope_pos_ == scope_end_) return HazardResult();
1479 if (!scope_pos_->first.intersects(pos->first)) {
1480 event_scope_.lower_bound(pos->first);
1481 if ((scope_pos_ == scope_end_) || !scope_pos_->first.intersects(pos->first)) return HazardResult();
1482 }
1483
1484 // Some portion of this pos is in the event_scope, so check for a barrier hazard
1485 return pos->second.DetectBarrierHazard(usage_index_, src_exec_scope_, src_access_scope_, scope_tag_);
1486 }
John Zulauf14940722021-04-12 15:19:02 -06001487 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001488 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1489 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1490 }
1491
1492 private:
1493 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001494 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001495 SyncStageAccessFlags src_access_scope_;
1496 const SyncEventState::ScopeMap &event_scope_;
1497 SyncEventState::ScopeMap::const_iterator scope_pos_;
1498 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf14940722021-04-12 15:19:02 -06001499 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001500};
1501
Jeremy Gebben40a22942020-12-22 14:22:06 -07001502HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07001503 const SyncStageAccessFlags &src_access_scope,
1504 const VkImageSubresourceRange &subresource_range,
1505 const SyncEventState &sync_event, DetectOptions options) const {
1506 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1507 // first access scope map to use, and there's no easy way to plumb it in below.
1508 const auto address_type = ImageAddressType(image);
1509 const auto &event_scope = sync_event.FirstScope(address_type);
1510
1511 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
1512 event_scope, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001513 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001514}
1515
John Zulaufd0ec59f2021-03-13 14:25:08 -07001516HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1517 DetectOptions options) const {
1518 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1519 barrier.src_access_scope);
1520 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1521}
1522
Jeremy Gebben40a22942020-12-22 14:22:06 -07001523HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001524 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001525 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001526 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001527 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001528 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001529}
1530
Jeremy Gebben40a22942020-12-22 14:22:06 -07001531HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001532 const SyncStageAccessFlags &src_stage_accesses,
John Zulauf355e49b2020-04-24 15:11:15 -06001533 const VkImageMemoryBarrier &barrier) const {
1534 auto subresource_range = NormalizeSubresourceRange(image.createInfo, barrier.subresourceRange);
1535 const auto src_access_scope = SyncStageAccess::AccessScope(src_stage_accesses, barrier.srcAccessMask);
1536 return DetectImageBarrierHazard(image, src_exec_scope, src_access_scope, subresource_range, kDetectAll);
1537}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001538HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001539 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001540 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001541}
John Zulauf355e49b2020-04-24 15:11:15 -06001542
John Zulauf9cb530d2019-09-30 14:14:10 -06001543template <typename Flags, typename Map>
1544SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1545 SyncStageAccessFlags scope = 0;
1546 for (const auto &bit_scope : map) {
1547 if (flag_mask < bit_scope.first) break;
1548
1549 if (flag_mask & bit_scope.first) {
1550 scope |= bit_scope.second;
1551 }
1552 }
1553 return scope;
1554}
1555
Jeremy Gebben40a22942020-12-22 14:22:06 -07001556SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001557 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1558}
1559
Jeremy Gebben40a22942020-12-22 14:22:06 -07001560SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1561 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001562}
1563
Jeremy Gebben40a22942020-12-22 14:22:06 -07001564// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1565SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001566 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1567 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1568 // 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 -06001569 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1570}
1571
1572template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001573void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001574 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1575 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001576 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001577 auto pos = accesses->lower_bound(range);
1578 if (pos == accesses->end() || !pos->first.intersects(range)) {
1579 // The range is empty, fill it with a default value.
1580 pos = action.Infill(accesses, pos, range);
1581 } else if (range.begin < pos->first.begin) {
1582 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001583 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001584 } else if (pos->first.begin < range.begin) {
1585 // Trim the beginning if needed
1586 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1587 ++pos;
1588 }
1589
1590 const auto the_end = accesses->end();
1591 while ((pos != the_end) && pos->first.intersects(range)) {
1592 if (pos->first.end > range.end) {
1593 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1594 }
1595
1596 pos = action(accesses, pos);
1597 if (pos == the_end) break;
1598
1599 auto next = pos;
1600 ++next;
1601 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1602 // Need to infill if next is disjoint
1603 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001604 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001605 next = action.Infill(accesses, next, new_range);
1606 }
1607 pos = next;
1608 }
1609}
John Zulaufd5115702021-01-18 12:34:33 -07001610
1611// Give a comparable interface for range generators and ranges
1612template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001613void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001614 assert(range);
1615 UpdateMemoryAccessState(accesses, *range, action);
1616}
1617
John Zulauf4a6105a2020-11-17 15:11:05 -07001618template <typename Action, typename RangeGen>
1619void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1620 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001621 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 -07001622 for (; range_gen->non_empty(); ++range_gen) {
1623 UpdateMemoryAccessState(accesses, *range_gen, action);
1624 }
1625}
John Zulauf9cb530d2019-09-30 14:14:10 -06001626
John Zulaufd0ec59f2021-03-13 14:25:08 -07001627template <typename Action, typename RangeGen>
1628void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1629 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1630 for (; range_gen->non_empty(); ++range_gen) {
1631 UpdateMemoryAccessState(accesses, *range_gen, action);
1632 }
1633}
John Zulauf9cb530d2019-09-30 14:14:10 -06001634struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001635 using Iterator = ResourceAccessRangeMap::iterator;
1636 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001637 // this is only called on gaps, and never returns a gap.
1638 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001639 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001640 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001641 }
John Zulauf5f13a792020-03-10 07:31:21 -06001642
John Zulauf5c5e88d2019-12-26 11:22:02 -07001643 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001644 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001645 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001646 return pos;
1647 }
1648
John Zulauf43cc7462020-12-03 12:33:12 -07001649 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001650 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001651 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001652 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001653 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001654 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001655 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001656 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001657};
1658
John Zulauf4a6105a2020-11-17 15:11:05 -07001659// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001660struct PipelineBarrierOp {
1661 SyncBarrier barrier;
1662 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001663 ResourceAccessState::QueueScopeOps scope;
1664 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1665 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001666 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001667 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001668};
John Zulauf00119522022-05-23 19:07:42 -06001669
John Zulauf4a6105a2020-11-17 15:11:05 -07001670// The barrier operation for wait events
1671struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001672 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001673 SyncBarrier barrier;
1674 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001675 // WIP Integrate Queue scoping into event scope operations
1676 WaitEventBarrierOp(const QueueId scope_queue, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
1677 bool layout_transition_)
John Zulaufb7578302022-05-19 13:50:18 -06001678 : scope_ops(scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
1679 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001680};
John Zulauf1e331ec2020-12-04 18:29:38 -07001681
John Zulauf4a6105a2020-11-17 15:11:05 -07001682// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1683// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1684// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001685template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001686class ApplyBarrierOpsFunctor {
1687 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001688 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001689 // Only called with a gap, and pos at the lower_bound(range)
1690 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1691 if (!infill_default_) {
1692 return pos;
1693 }
1694 ResourceAccessState default_state;
1695 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1696 return inserted;
1697 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001698
John Zulauf5c628d02021-05-04 15:46:36 -06001699 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001700 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001701 for (const auto &op : barrier_ops_) {
1702 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001703 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001704
John Zulauf89311b42020-09-29 16:28:47 -06001705 if (resolve_) {
1706 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1707 // another walk
1708 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001709 }
1710 return pos;
1711 }
1712
John Zulauf89311b42020-09-29 16:28:47 -06001713 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001714 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1715 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001716 barrier_ops_.reserve(size_hint);
1717 }
John Zulauf5c628d02021-05-04 15:46:36 -06001718 void EmplaceBack(const BarrierOp &op) {
1719 barrier_ops_.emplace_back(op);
1720 infill_default_ |= op.layout_transition;
1721 }
John Zulauf89311b42020-09-29 16:28:47 -06001722
1723 private:
1724 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001725 bool infill_default_;
1726 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001727 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001728};
1729
John Zulauf4a6105a2020-11-17 15:11:05 -07001730// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1731// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1732template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001733class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1734 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1735
John Zulauf4a6105a2020-11-17 15:11:05 -07001736 public:
John Zulaufee984022022-04-13 16:39:50 -06001737 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001738};
1739
John Zulauf1e331ec2020-12-04 18:29:38 -07001740// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001741class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1742 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1743
John Zulauf1e331ec2020-12-04 18:29:38 -07001744 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001745 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001746};
1747
John Zulauf8e3c3e92021-01-06 11:19:36 -07001748void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001749 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001750 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001751 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001752}
1753
John Zulauf8e3c3e92021-01-06 11:19:36 -07001754void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001755 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001756 if (!SimpleBinding(buffer)) return;
1757 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001758 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001759}
John Zulauf355e49b2020-04-24 15:11:15 -06001760
John Zulauf8e3c3e92021-01-06 11:19:36 -07001761void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001762 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1763 if (!SimpleBinding(image)) return;
1764 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001765 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001766 const auto address_type = ImageAddressType(image);
1767 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1768 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1769}
1770void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001771 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001772 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001773 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001774 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001775 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001776 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001777 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001778 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001779 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001780}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001781
1782void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001783 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001784 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1785 if (!gen) return;
1786 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1787 const auto address_type = view_gen.GetAddressType();
1788 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1789 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001790}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001791
John Zulauf8e3c3e92021-01-06 11:19:36 -07001792void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001793 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001794 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001795 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1796 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001797 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001798}
1799
John Zulaufd0ec59f2021-03-13 14:25:08 -07001800template <typename Action, typename RangeGen>
1801void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1802 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1803 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001804}
1805
1806template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001807void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1808 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1809 if (!gen) return;
1810 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001811}
1812
John Zulaufd0ec59f2021-03-13 14:25:08 -07001813void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1814 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001815 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001816 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001817 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001818}
1819
John Zulaufd0ec59f2021-03-13 14:25:08 -07001820void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001821 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001822 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001823
1824 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1825 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001826 const auto &view_gen = attachment_views[i];
1827 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001828
1829 const auto &ci = attachment_ci[i];
1830 const bool has_depth = FormatHasDepth(ci.format);
1831 const bool has_stencil = FormatHasStencil(ci.format);
1832 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001833 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001834
1835 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001836 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1837 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001838 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001839 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001840 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1841 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001842 }
John Zulauf57261402021-08-13 11:32:06 -06001843 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001844 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001845 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1846 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001847 }
1848 }
1849 }
1850 }
1851}
1852
John Zulauf540266b2020-04-06 18:54:53 -06001853template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001854void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001855 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001856 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001857 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001858 }
1859}
1860
1861void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001862 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1863 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001864 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001865 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001866 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001867 }
1868 }
1869}
1870
John Zulauf4fa68462021-04-26 21:04:22 -06001871// Caller must ensure that lifespan of this is less than from
1872void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1873
John Zulauf355e49b2020-04-24 15:11:15 -06001874// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001875HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1876 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001877
John Zulauf355e49b2020-04-24 15:11:15 -06001878 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001879 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001880
1881 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001882 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1883 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001884 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001885 if (!hazard.hazard) {
1886 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001887 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001888 }
John Zulaufa0a98292020-09-18 09:30:10 -06001889
John Zulauf355e49b2020-04-24 15:11:15 -06001890 return hazard;
1891}
1892
John Zulaufb02c1eb2020-10-06 16:33:36 -06001893void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001894 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001895 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001896 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001897 for (const auto &transition : transitions) {
1898 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001899 const auto &view_gen = attachment_views[transition.attachment];
1900 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001901
1902 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1903 assert(trackback);
1904
1905 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001906 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001907 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001908 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001909 auto &target_map = GetAccessStateMap(address_type);
1910 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001911 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1912 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001913 }
1914
John Zulauf86356ca2020-10-19 11:46:41 -06001915 // If there were no transitions skip this global map walk
1916 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001917 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001918 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001919 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001920}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001921
locke-lunarg61870c22020-06-09 14:51:50 -06001922bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
1923 const char *func_name) const {
1924 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001925 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001926 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001927 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001928 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001929 return skip;
1930 }
1931
1932 using DescriptorClass = cvdescriptorset::DescriptorClass;
1933 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1934 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06001935 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1936
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001937 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001938 const auto raster_state = pipe->RasterizationState();
1939 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001940 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001941 }
locke-lunarg61870c22020-06-09 14:51:50 -06001942 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001943 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06001944 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06001945 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06001946 const auto descriptor_type = binding_it.GetType();
1947 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
1948 auto array_idx = 0;
1949
1950 if (binding_it.IsVariableDescriptorCount()) {
1951 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
1952 }
1953 SyncStageAccessIndex sync_index =
1954 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
1955
1956 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
1957 uint32_t index = i - index_range.start;
1958 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
1959 switch (descriptor->GetClass()) {
1960 case DescriptorClass::ImageSampler:
1961 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07001962 if (descriptor->Invalid()) {
1963 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06001964 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07001965
1966 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
1967 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
1968 const auto *img_view_state = image_descriptor->GetImageViewState();
1969 VkImageLayout image_layout = image_descriptor->GetImageLayout();
1970
John Zulauf361fb532020-07-22 10:45:39 -06001971 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06001972 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
1973 // Descriptors, so we do not have to worry about depth slicing here.
1974 // See: VUID 00343
1975 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06001976 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06001977 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06001978
1979 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
1980 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
1981 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06001982 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001983 hazard =
1984 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
1985 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06001986 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001987 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
1988 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06001989 }
John Zulauf110413c2021-03-20 05:38:38 -06001990
John Zulauf33fc1d52020-07-17 11:01:10 -06001991 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06001992 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001993 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06001994 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
1995 ", index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06001996 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001997 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
1998 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
1999 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002000 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2001 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002002 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002003 }
2004 break;
2005 }
2006 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002007 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2008 if (texel_descriptor->Invalid()) {
2009 continue;
2010 }
2011 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2012 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002013 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002014 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002015 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002016 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002017 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002018 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
2019 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002020 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2021 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2022 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002023 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002024 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002025 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002026 }
2027 break;
2028 }
2029 case DescriptorClass::GeneralBuffer: {
2030 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002031 if (buffer_descriptor->Invalid()) {
2032 continue;
2033 }
2034 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002035 const ResourceAccessRange range =
2036 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002037 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002038 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002039 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002040 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002041 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
2042 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002043 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2044 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2045 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002046 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002047 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002048 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002049 }
2050 break;
2051 }
2052 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2053 default:
2054 break;
2055 }
2056 }
2057 }
2058 }
2059 return skip;
2060}
2061
2062void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002063 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002064 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002065 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002066 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002067 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002068 return;
2069 }
2070
2071 using DescriptorClass = cvdescriptorset::DescriptorClass;
2072 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2073 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002074 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2075
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002076 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002077 const auto raster_state = pipe->RasterizationState();
2078 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002079 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002080 }
locke-lunarg61870c22020-06-09 14:51:50 -06002081 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002082 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002083 cvdescriptorset::DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002084 set_binding.first.binding);
locke-lunarg61870c22020-06-09 14:51:50 -06002085 const auto descriptor_type = binding_it.GetType();
2086 cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange();
2087 auto array_idx = 0;
2088
2089 if (binding_it.IsVariableDescriptorCount()) {
2090 index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount();
2091 }
2092 SyncStageAccessIndex sync_index =
2093 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2094
2095 for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
2096 const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i);
2097 switch (descriptor->GetClass()) {
2098 case DescriptorClass::ImageSampler:
2099 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002100 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2101 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2102 if (image_descriptor->Invalid()) {
2103 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002104 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002105 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002106 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2107 // Descriptors, so we do not have to worry about depth slicing here.
2108 // See: VUID 00343
2109 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002110 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002111 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002112 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2113 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2114 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2115 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002116 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002117 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2118 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002119 }
locke-lunarg61870c22020-06-09 14:51:50 -06002120 break;
2121 }
2122 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002123 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2124 if (texel_descriptor->Invalid()) {
2125 continue;
2126 }
2127 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2128 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002129 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002130 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002131 break;
2132 }
2133 case DescriptorClass::GeneralBuffer: {
2134 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002135 if (buffer_descriptor->Invalid()) {
2136 continue;
2137 }
2138 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002139 const ResourceAccessRange range =
2140 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002141 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002142 break;
2143 }
2144 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2145 default:
2146 break;
2147 }
2148 }
2149 }
2150 }
2151}
2152
2153bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const char *func_name) const {
2154 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002155 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002156 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002157 return skip;
2158 }
2159
2160 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2161 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002162 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002163
2164 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002165 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002166 if (binding_description.binding < binding_buffers_size) {
2167 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002168 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002169
locke-lunarg1ae57d62020-11-18 10:49:19 -07002170 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002171 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2172 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002173 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002174 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002175 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002176 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 -06002177 func_name, string_SyncHazard(hazard.hazard),
2178 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2179 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002180 }
2181 }
2182 }
2183 return skip;
2184}
2185
John Zulauf14940722021-04-12 15:19:02 -06002186void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002187 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002188 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002189 return;
2190 }
2191 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2192 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002193 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002194
2195 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002196 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002197 if (binding_description.binding < binding_buffers_size) {
2198 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002199 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002200
locke-lunarg1ae57d62020-11-18 10:49:19 -07002201 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002202 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2203 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002204 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2205 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002206 }
2207 }
2208}
2209
2210bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const char *func_name) const {
2211 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002212 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002213 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002214 }
locke-lunarg61870c22020-06-09 14:51:50 -06002215
locke-lunarg1ae57d62020-11-18 10:49:19 -07002216 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002217 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002218 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2219 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002220 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002221 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002222 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002223 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
2224 func_name, string_SyncHazard(hazard.hazard), sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002225 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002226 }
2227
2228 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2229 // We will detect more accurate range in the future.
2230 skip |= ValidateDrawVertex(UINT32_MAX, 0, func_name);
2231 return skip;
2232}
2233
John Zulauf14940722021-04-12 15:19:02 -06002234void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002235 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 -06002236
locke-lunarg1ae57d62020-11-18 10:49:19 -07002237 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002238 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002239 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2240 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002241 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002242
2243 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2244 // We will detect more accurate range in the future.
2245 RecordDrawVertex(UINT32_MAX, 0, tag);
2246}
2247
2248bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(const char *func_name) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002249 bool skip = false;
2250 if (!current_renderpass_context_) return skip;
John Zulauf64ffe552021-02-06 10:25:07 -07002251 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), func_name);
locke-lunarg7077d502020-06-18 21:37:26 -06002252 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002253}
2254
John Zulauf14940722021-04-12 15:19:02 -06002255void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002256 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002257 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002258 }
locke-lunarg61870c22020-06-09 14:51:50 -06002259}
2260
John Zulauf00119522022-05-23 19:07:42 -06002261QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2262
John Zulauf41a9c7c2021-12-07 15:59:53 -07002263ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd, const RENDER_PASS_STATE &rp_state,
2264 const VkRect2D &render_area,
2265 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002266 // Create an access context the current renderpass.
John Zulauf41a9c7c2021-12-07 15:59:53 -07002267 const auto barrier_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2268 const auto load_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002269 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002270 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002271 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002272 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002273 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002274}
2275
John Zulauf41a9c7c2021-12-07 15:59:53 -07002276ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd) {
John Zulauf16adfc92020-04-08 10:28:33 -06002277 assert(current_renderpass_context_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002278 if (!current_renderpass_context_) return NextCommandTag(cmd);
2279
2280 auto store_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kStoreOp);
2281 auto barrier_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2282 auto load_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kLoadOp);
2283
2284 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002285 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002286 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002287}
2288
John Zulauf41a9c7c2021-12-07 15:59:53 -07002289ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd) {
John Zulauf16adfc92020-04-08 10:28:33 -06002290 assert(current_renderpass_context_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002291 if (!current_renderpass_context_) return NextCommandTag(cmd);
John Zulauf16adfc92020-04-08 10:28:33 -06002292
John Zulauf41a9c7c2021-12-07 15:59:53 -07002293 auto store_tag = NextCommandTag(cmd, ResourceUsageRecord::SubcommandType::kStoreOp);
2294 auto barrier_tag = NextSubcommandTag(cmd, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2295
2296 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002297 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002298 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002299 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002300}
2301
John Zulauf4a6105a2020-11-17 15:11:05 -07002302void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2303 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002304 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002305 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002306 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002307 }
2308}
2309
John Zulaufae842002021-04-15 18:20:55 -06002310// The is the recorded cb context
John Zulaufbb890452021-12-14 11:30:18 -07002311bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext *proxy_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002312 uint32_t index) const {
2313 assert(proxy_context);
John Zulauf00119522022-05-23 19:07:42 -06002314 SyncEventsContext *const events_context = proxy_context->GetCurrentEventsContext();
2315 AccessContext *const access_context = proxy_context->GetCurrentAccessContext();
2316 const QueueId queue_id = proxy_context->GetQueueId();
John Zulauf4fa68462021-04-26 21:04:22 -06002317 const ResourceUsageTag base_tag = proxy_context->GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002318 bool skip = false;
2319 ResourceUsageRange tag_range = {0, 0};
2320 const AccessContext *recorded_context = GetCurrentAccessContext();
2321 assert(recorded_context);
2322 HazardResult hazard;
John Zulaufbb890452021-12-14 11:30:18 -07002323 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002324 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002325 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002326 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002327 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002328 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002329 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2330 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002331 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002332 };
John Zulaufbb890452021-12-14 11:30:18 -07002333 const ReplayTrackbackBarriersAction *replay_context = nullptr;
John Zulaufae842002021-04-15 18:20:55 -06002334 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002335 // we update the range to any include layout transition first use writes,
2336 // as they are stored along with the source scope (as effective barrier) when recorded
2337 tag_range.end = sync_op.tag + 1;
John Zulauf610e28c2021-08-03 17:46:23 -06002338 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, proxy_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002339
John Zulaufbb890452021-12-14 11:30:18 -07002340 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002341 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002342 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002343 }
2344 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002345 // Record the barrier into the proxy context.
John Zulauf00119522022-05-23 19:07:42 -06002346 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulaufbb890452021-12-14 11:30:18 -07002347 replay_context = sync_op.sync_op->GetReplayTrackback();
John Zulauf4fa68462021-04-26 21:04:22 -06002348 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002349 }
2350
John Zulaufbb890452021-12-14 11:30:18 -07002351 // Renderpasses may not cross command buffer boundaries
2352 assert(replay_context == nullptr);
2353
John Zulaufae842002021-04-15 18:20:55 -06002354 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002355 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulaufbb890452021-12-14 11:30:18 -07002356 hazard = recorded_context->DetectFirstUseHazard(tag_range, *access_context, replay_context);
John Zulaufae842002021-04-15 18:20:55 -06002357 if (hazard.hazard) {
John Zulauf4fa68462021-04-26 21:04:22 -06002358 skip |= log_msg(hazard, *proxy_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002359 }
2360
2361 return skip;
2362}
2363
John Zulauf1d5f9c12022-05-13 14:51:08 -06002364void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context, CMD_TYPE cmd) {
John Zulauf00119522022-05-23 19:07:42 -06002365 SyncEventsContext *const events_context = GetCurrentEventsContext();
2366 AccessContext *const access_context = GetCurrentAccessContext();
2367 const QueueId queue_id = GetQueueId();
2368
John Zulauf4fa68462021-04-26 21:04:22 -06002369 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2370 assert(recorded_context);
2371
2372 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2373 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002374 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002375 // we update the range to any include layout transition first use writes,
2376 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf00119522022-05-23 19:07:42 -06002377 sync_op.sync_op->ReplayRecord(queue_id, base_tag + sync_op.tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002378 }
2379
2380 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2381 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002382 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002383}
2384
John Zulauf1d5f9c12022-05-13 14:51:08 -06002385void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002386 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002387 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002388}
2389
John Zulauf3c788ef2022-02-22 12:12:30 -07002390ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002391 // The execution references ensure lifespan for the referenced child CB's...
2392 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002393 InsertRecordedAccessLogEntries(recorded_context);
2394 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002395 return tag_range;
2396}
2397
John Zulauf3c788ef2022-02-22 12:12:30 -07002398void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2399 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2400 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2401}
2402
John Zulauf41a9c7c2021-12-07 15:59:53 -07002403ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2404 ResourceUsageTag next = access_log_.size();
2405 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2406 return next;
2407}
2408
2409ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2410 command_number_++;
2411 subcommand_number_ = 0;
2412 ResourceUsageTag next = access_log_.size();
2413 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2414 return next;
2415}
2416
2417ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2418 if (index == 0) {
2419 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2420 }
2421 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2422}
2423
John Zulaufbb890452021-12-14 11:30:18 -07002424void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2425 auto tag = sync_op->Record(this);
2426 // As renderpass operations can have side effects on the command buffer access context,
2427 // update the sync operation to record these if any.
2428 if (current_renderpass_context_) {
2429 const auto &rpc = *current_renderpass_context_;
2430 sync_op->SetReplayContext(rpc.GetCurrentSubpass(), rpc.GetReplayContext());
2431 }
2432 sync_ops_.emplace_back(tag, std::move(sync_op));
2433}
2434
John Zulaufae842002021-04-15 18:20:55 -06002435class HazardDetectFirstUse {
2436 public:
John Zulaufbb890452021-12-14 11:30:18 -07002437 HazardDetectFirstUse(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
2438 const ReplayTrackbackBarriersAction *replay_barrier)
2439 : recorded_use_(recorded_use), tag_range_(tag_range), replay_barrier_(replay_barrier) {}
John Zulaufae842002021-04-15 18:20:55 -06002440 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufbb890452021-12-14 11:30:18 -07002441 if (replay_barrier_) {
2442 // Intentional copy to apply the replay barrier
2443 auto access = pos->second;
2444 (*replay_barrier_)(&access);
2445 return access.DetectHazard(recorded_use_, tag_range_);
2446 }
John Zulaufae842002021-04-15 18:20:55 -06002447 return pos->second.DetectHazard(recorded_use_, tag_range_);
2448 }
2449 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2450 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2451 }
2452
2453 private:
2454 const ResourceAccessState &recorded_use_;
2455 const ResourceUsageRange &tag_range_;
John Zulaufbb890452021-12-14 11:30:18 -07002456 const ReplayTrackbackBarriersAction *replay_barrier_;
John Zulaufae842002021-04-15 18:20:55 -06002457};
2458
2459// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2460// hazards will be detected
John Zulaufbb890452021-12-14 11:30:18 -07002461HazardResult AccessContext::DetectFirstUseHazard(const ResourceUsageRange &tag_range, const AccessContext &access_context,
2462 const ReplayTrackbackBarriersAction *replay_barrier) const {
John Zulaufae842002021-04-15 18:20:55 -06002463 HazardResult hazard;
2464 for (const auto address_type : kAddressTypes) {
2465 const auto &recorded_access_map = GetAccessStateMap(address_type);
2466 for (const auto &recorded_access : recorded_access_map) {
2467 // Cull any entries not in the current tag range
2468 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulaufbb890452021-12-14 11:30:18 -07002469 HazardDetectFirstUse detector(recorded_access.second, tag_range, replay_barrier);
John Zulaufae842002021-04-15 18:20:55 -06002470 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2471 if (hazard.hazard) break;
2472 }
2473 }
2474
2475 return hazard;
2476}
2477
John Zulaufbb890452021-12-14 11:30:18 -07002478bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
2479 const CMD_BUFFER_STATE &cmd, const char *func_name) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002480 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002481 const auto &sync_state = exec_context.GetSyncState();
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002482 const auto *pipe = cmd.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002483 if (!pipe) {
2484 return skip;
2485 }
2486
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002487 const auto raster_state = pipe->RasterizationState();
2488 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002489 return skip;
2490 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002491 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002492 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002493
John Zulauf1a224292020-06-30 14:52:13 -06002494 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002495 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002496 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2497 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002498 if (location >= subpass.colorAttachmentCount ||
2499 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002500 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002501 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002502 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2503 if (!view_gen.IsValid()) continue;
2504 HazardResult hazard =
2505 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2506 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002507 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002508 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002509 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002510 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002511 func_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002512 sync_state.report_data->FormatHandle(view_handle).c_str(),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002513 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002514 location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002515 }
2516 }
2517 }
locke-lunarg37047832020-06-12 13:44:45 -06002518
2519 // PHASE1 TODO: Add layout based read/vs. write selection.
2520 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002521 const auto ds_state = pipe->DepthStencilState();
2522 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002523
2524 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2525 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2526 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002527 bool depth_write = false, stencil_write = false;
2528
2529 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002530 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002531 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2532 depth_write = true;
2533 }
2534 // PHASE1 TODO: It needs to check if stencil is writable.
2535 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2536 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2537 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002538 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002539 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2540 stencil_write = true;
2541 }
2542
2543 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2544 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002545 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2546 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2547 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002548 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002549 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002550 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002551 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002552 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002553 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
2554 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002555 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002556 }
2557 }
2558 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002559 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2560 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2561 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002562 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002563 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002564 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002565 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06002566 func_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002567 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
2568 sync_state.report_data->FormatHandle(cmd.commandBuffer()).c_str(), cmd.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002569 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002570 }
locke-lunarg61870c22020-06-09 14:51:50 -06002571 }
2572 }
2573 return skip;
2574}
2575
John Zulauf14940722021-04-12 15:19:02 -06002576void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002577 const auto *pipe = cmd.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002578 if (!pipe) {
2579 return;
2580 }
2581
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002582 const auto *raster_state = pipe->RasterizationState();
2583 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002584 return;
2585 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002586 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002587 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002588
John Zulauf1a224292020-06-30 14:52:13 -06002589 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002590 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002591 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2592 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002593 if (location >= subpass.colorAttachmentCount ||
2594 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002595 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002596 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002597 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2598 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2599 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2600 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002601 }
2602 }
locke-lunarg37047832020-06-12 13:44:45 -06002603
2604 // PHASE1 TODO: Add layout based read/vs. write selection.
2605 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002606 const auto *ds_state = pipe->DepthStencilState();
2607 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002608 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2609 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2610 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002611 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002612 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2613 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002614
2615 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002616 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2617 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002618 depth_write = true;
2619 }
2620 // PHASE1 TODO: It needs to check if stencil is writable.
2621 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2622 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2623 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002624 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002625 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2626 stencil_write = true;
2627 }
2628
John Zulaufd0ec59f2021-03-13 14:25:08 -07002629 if (depth_write || stencil_write) {
2630 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2631 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2632 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2633 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002634 }
locke-lunarg61870c22020-06-09 14:51:50 -06002635 }
2636}
2637
John Zulaufbb890452021-12-14 11:30:18 -07002638bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002639 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002640 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002641 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, func_name,
John Zulaufb027cdb2020-05-21 14:25:22 -06002642 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002643 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
John Zulaufaff20662020-06-01 14:07:58 -06002644 func_name);
2645
John Zulauf355e49b2020-04-24 15:11:15 -06002646 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002647 if (next_subpass >= subpass_contexts_.size()) {
2648 return skip;
2649 }
John Zulauf1507ee42020-05-18 11:33:09 -06002650 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002651 skip |=
John Zulaufbb890452021-12-14 11:30:18 -07002652 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002653 if (!skip) {
2654 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2655 // on a copy of the (empty) next context.
2656 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2657 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002658 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002659 skip |=
John Zulaufbb890452021-12-14 11:30:18 -07002660 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, func_name);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002661 }
John Zulauf7635de32020-05-29 17:14:15 -06002662 return skip;
2663}
John Zulaufbb890452021-12-14 11:30:18 -07002664bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, const char *func_name) const {
John Zulaufaff20662020-06-01 14:07:58 -06002665 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002666 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002667 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, func_name,
John Zulauf7635de32020-05-29 17:14:15 -06002668 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002669 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_,
John Zulaufd0ec59f2021-03-13 14:25:08 -07002670
2671 attachment_views_, func_name);
John Zulaufbb890452021-12-14 11:30:18 -07002672 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, func_name);
John Zulauf355e49b2020-04-24 15:11:15 -06002673 return skip;
2674}
2675
John Zulauf64ffe552021-02-06 10:25:07 -07002676AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002677 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002678}
2679
John Zulaufbb890452021-12-14 11:30:18 -07002680bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
John Zulauf64ffe552021-02-06 10:25:07 -07002681 const char *func_name) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002682 bool skip = false;
2683
John Zulauf7635de32020-05-29 17:14:15 -06002684 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2685 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2686 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2687 // to apply and only copy then, if this proves a hot spot.
2688 std::unique_ptr<AccessContext> proxy_for_current;
2689
John Zulauf355e49b2020-04-24 15:11:15 -06002690 // Validate the "finalLayout" transitions to external
2691 // Get them from where there we're hidding in the extra entry.
2692 const auto &final_transitions = rp_state_->subpass_transitions.back();
2693 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002694 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002695 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002696 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2697 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002698
2699 if (transition.prev_pass == current_subpass_) {
2700 if (!proxy_for_current) {
2701 // 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 -07002702 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002703 }
2704 context = proxy_for_current.get();
2705 }
2706
John Zulaufa0a98292020-09-18 09:30:10 -06002707 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2708 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002709 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002710 if (hazard.hazard) {
John Zulaufee984022022-04-13 16:39:50 -06002711 if (hazard.tag == kInvalidTag) {
2712 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002713 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002714 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2715 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2716 " final image layout transition (old_layout: %s, new_layout: %s).",
2717 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2718 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2719 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002720 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002721 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2722 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2723 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2724 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2725 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002726 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002727 }
John Zulauf355e49b2020-04-24 15:11:15 -06002728 }
2729 }
2730 return skip;
2731}
2732
John Zulauf14940722021-04-12 15:19:02 -06002733void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002734 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002735 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002736}
2737
John Zulauf14940722021-04-12 15:19:02 -06002738void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002739 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2740 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002741
2742 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2743 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002744 const AttachmentViewGen &view_gen = attachment_views_[i];
2745 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002746
2747 const auto &ci = attachment_ci[i];
2748 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002749 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002750 const bool is_color = !(has_depth || has_stencil);
2751
2752 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002753 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2754 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2755 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2756 SyncOrdering::kColorAttachment, tag);
2757 }
John Zulauf1507ee42020-05-18 11:33:09 -06002758 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002759 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002760 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2761 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2762 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2763 SyncOrdering::kDepthStencilAttachment, tag);
2764 }
John Zulauf1507ee42020-05-18 11:33:09 -06002765 }
2766 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002767 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2768 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2769 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2770 SyncOrdering::kDepthStencilAttachment, tag);
2771 }
John Zulauf1507ee42020-05-18 11:33:09 -06002772 }
2773 }
2774 }
2775 }
2776}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002777AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2778 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2779 AttachmentViewGenVector view_gens;
2780 VkExtent3D extent = CastTo3D(render_area.extent);
2781 VkOffset3D offset = CastTo3D(render_area.offset);
2782 view_gens.reserve(attachment_views.size());
2783 for (const auto *view : attachment_views) {
2784 view_gens.emplace_back(view, offset, extent);
2785 }
2786 return view_gens;
2787}
John Zulauf64ffe552021-02-06 10:25:07 -07002788RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2789 VkQueueFlags queue_flags,
2790 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2791 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002792 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulauf355e49b2020-04-24 15:11:15 -06002793 // Add this for all subpasses here so that they exsist during next subpass validation
John Zulauf64ffe552021-02-06 10:25:07 -07002794 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
John Zulaufbb890452021-12-14 11:30:18 -07002795 replay_context_ = std::make_shared<ReplayRenderpassContext>();
2796 auto &replay_subpass_contexts = replay_context_->subpass_contexts;
2797 replay_subpass_contexts.reserve(rp_state_->createInfo.subpassCount);
John Zulauf355e49b2020-04-24 15:11:15 -06002798 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002799 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulaufbb890452021-12-14 11:30:18 -07002800 replay_subpass_contexts.emplace_back(queue_flags, rp_state_->subpass_dependencies[pass], replay_subpass_contexts);
John Zulauf355e49b2020-04-24 15:11:15 -06002801 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002802 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002803}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002804void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002805 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002806 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2807 RecordLayoutTransitions(barrier_tag);
2808 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002809}
John Zulauf1507ee42020-05-18 11:33:09 -06002810
John Zulauf41a9c7c2021-12-07 15:59:53 -07002811void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2812 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002813 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002814 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2815 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002816
ziga-lunarg31a3e772022-03-22 11:48:46 +01002817 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2818 return;
2819 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002820 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2821 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002822 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002823 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2824 RecordLayoutTransitions(barrier_tag);
2825 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002826}
2827
John Zulauf41a9c7c2021-12-07 15:59:53 -07002828void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2829 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002830 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002831 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2832 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002833
John Zulauf355e49b2020-04-24 15:11:15 -06002834 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002835 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002836
2837 // Add the "finalLayout" transitions to external
2838 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002839 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2840 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2841 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002842 const auto &final_transitions = rp_state_->subpass_transitions.back();
2843 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002844 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002845 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002846 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002847 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002848 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002849 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002850 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002851 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002852 }
2853}
2854
John Zulauf06f6f1e2022-04-19 15:28:11 -06002855SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2856 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002857 SyncExecScope result;
2858 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002859 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002860 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002861 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2862 return result;
2863}
2864
Jeremy Gebben40a22942020-12-22 14:22:06 -07002865SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002866 SyncExecScope result;
2867 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002868 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2869 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002870 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.exec_scope);
2871 return result;
2872}
2873
2874SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
John Zulaufc523bf62021-02-16 08:20:34 -07002875 src_exec_scope = src;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002876 src_access_scope = 0;
John Zulaufc523bf62021-02-16 08:20:34 -07002877 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002878 dst_access_scope = 0;
2879}
2880
2881template <typename Barrier>
2882SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst) {
John Zulaufc523bf62021-02-16 08:20:34 -07002883 src_exec_scope = src;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002884 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002885 dst_exec_scope = dst;
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002886 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
2887}
2888
2889SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002890 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2891 if (barrier) {
2892 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002893 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002894 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002895
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002896 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002897 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002898 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2899
2900 } else {
2901 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002902 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002903 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2904
2905 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002906 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002907 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2908 }
2909}
2910
2911template <typename Barrier>
2912SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2913 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2914 src_exec_scope = src.exec_scope;
2915 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2916
2917 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002918 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002919 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002920}
2921
John Zulaufb02c1eb2020-10-06 16:33:36 -06002922// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2923void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002924 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002925 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002926 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002927 }
2928}
2929
John Zulauf89311b42020-09-29 16:28:47 -06002930// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2931// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2932// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002933void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002934 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002935 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002936 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002937 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002938 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002939 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002940 }
John Zulaufbb890452021-12-14 11:30:18 -07002941 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002942}
John Zulauf9cb530d2019-09-30 14:14:10 -06002943HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2944 HazardResult hazard;
2945 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002946 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002947 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002948 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002949 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002950 }
2951 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002952 // Write operation:
2953 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2954 // If reads exists -- test only against them because either:
2955 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2956 // * 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
2957 // the current write happens after the reads, so just test the write against the reades
2958 // Otherwise test against last_write
2959 //
2960 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002961 if (last_reads.size()) {
2962 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002963 if (IsReadHazard(usage_stage, read_access)) {
2964 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2965 break;
2966 }
2967 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002968 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002969 // Write-After-Write check -- if we have a previous write to test against
2970 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002971 }
2972 }
2973 return hazard;
2974}
2975
John Zulauf4fa68462021-04-26 21:04:22 -06002976HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002977 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulauf4fa68462021-04-26 21:04:22 -06002978 return DetectHazard(usage_index, ordering);
2979}
2980
2981HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering) const {
John Zulauf69133422020-05-20 14:55:53 -06002982 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
2983 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06002984 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002985 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002986 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
2987 const bool last_write_is_ordered = (last_write & ordering.access_scope).any();
John Zulauf4285ee92020-09-23 10:20:52 -06002988 if (IsRead(usage_bit)) {
2989 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
2990 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
2991 if (is_raw_hazard) {
2992 // NOTE: we know last_write is non-zero
2993 // See if the ordering rules save us from the simple RAW check above
2994 // First check to see if the current usage is covered by the ordering rules
2995 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
2996 const bool usage_is_ordered =
2997 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
2998 if (usage_is_ordered) {
2999 // Now see of the most recent write (or a subsequent read) are ordered
3000 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(ordering));
3001 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003002 }
3003 }
John Zulauf4285ee92020-09-23 10:20:52 -06003004 if (is_raw_hazard) {
3005 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3006 }
John Zulauf5c628d02021-05-04 15:46:36 -06003007 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3008 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
3009 return DetectBarrierHazard(usage_index, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003010 } else {
3011 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003012 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003013 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003014 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003015 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003016 if (usage_write_is_ordered) {
3017 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
3018 ordered_stages = GetOrderedStages(ordering);
3019 }
3020 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3021 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003022 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003023 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3024 if (IsReadHazard(usage_stage, read_access)) {
3025 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3026 break;
3027 }
John Zulaufd14743a2020-07-03 09:42:39 -06003028 }
3029 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003030 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3031 bool ilt_ilt_hazard = false;
3032 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3033 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3034 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3035 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3036 }
3037 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003038 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003039 }
John Zulauf69133422020-05-20 14:55:53 -06003040 }
3041 }
3042 return hazard;
3043}
3044
John Zulaufae842002021-04-15 18:20:55 -06003045HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range) const {
3046 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003047 using Size = FirstAccesses::size_type;
3048 const auto &recorded_accesses = recorded_use.first_accesses_;
3049 Size count = recorded_accesses.size();
3050 if (count) {
3051 const auto &last_access = recorded_accesses.back();
3052 bool do_write_last = IsWrite(last_access.usage_index);
3053 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003054
John Zulauf4fa68462021-04-26 21:04:22 -06003055 for (Size i = 0; i < count; ++count) {
3056 const auto &first = recorded_accesses[i];
3057 // Skip and quit logic
3058 if (first.tag < tag_range.begin) continue;
3059 if (first.tag >= tag_range.end) {
3060 do_write_last = false; // ignore last since we know it can't be in tag_range
3061 break;
3062 }
3063
3064 hazard = DetectHazard(first.usage_index, first.ordering_rule);
3065 if (hazard.hazard) {
3066 hazard.AddRecordedAccess(first);
3067 break;
3068 }
3069 }
3070
3071 if (do_write_last && tag_range.includes(last_access.tag)) {
3072 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3073 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3074 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3075 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3076 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3077 // the barrier that applies them
3078 barrier |= recorded_use.first_write_layout_ordering_;
3079 }
3080 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3081 // the active context
3082 if (recorded_use.first_read_stages_) {
3083 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3084 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3085 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3086 // active context.
3087 barrier.exec_scope |= recorded_use.first_read_stages_;
3088 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3089 barrier.access_scope |= FlagBit(last_access.usage_index);
3090 }
3091 hazard = DetectHazard(last_access.usage_index, barrier);
3092 if (hazard.hazard) {
3093 hazard.AddRecordedAccess(last_access);
3094 }
3095 }
John Zulaufae842002021-04-15 18:20:55 -06003096 }
3097 return hazard;
3098}
3099
John Zulauf2f952d22020-02-10 11:34:51 -07003100// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003101HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003102 HazardResult hazard;
3103 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003104 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3105 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3106 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003107 if (IsRead(usage)) {
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, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003110 }
3111 } else {
John Zulauf14940722021-04-12 15:19:02 -06003112 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003113 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003114 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003115 // 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 -07003116 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003117 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003118 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003119 break;
3120 }
3121 }
John Zulauf2f952d22020-02-10 11:34:51 -07003122 }
3123 }
3124 return hazard;
3125}
3126
John Zulaufae842002021-04-15 18:20:55 -06003127HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3128 ResourceUsageTag start_tag) const {
3129 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003130 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003131 // Skip and quit logic
3132 if (first.tag < tag_range.begin) continue;
3133 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003134
3135 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003136 if (hazard.hazard) {
3137 hazard.AddRecordedAccess(first);
3138 break;
3139 }
John Zulaufae842002021-04-15 18:20:55 -06003140 }
3141 return hazard;
3142}
3143
Jeremy Gebben40a22942020-12-22 14:22:06 -07003144HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003145 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003146 // Only supporting image layout transitions for now
3147 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3148 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003149 // only test for WAW if there no intervening read operations.
3150 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003151 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003152 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003153 for (const auto &read_access : last_reads) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003154 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003155 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003156 break;
3157 }
3158 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003159 } else if (last_write.any() && IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3160 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3161 }
3162
3163 return hazard;
3164}
3165
Jeremy Gebben40a22942020-12-22 14:22:06 -07003166HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf4a6105a2020-11-17 15:11:05 -07003167 const SyncStageAccessFlags &src_access_scope,
John Zulauf14940722021-04-12 15:19:02 -06003168 const ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003169 // Only supporting image layout transitions for now
3170 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3171 HazardResult hazard;
3172 // only test for WAW if there no intervening read operations.
3173 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3174
John Zulaufab7756b2020-12-29 16:10:16 -07003175 if (last_reads.size()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003176 // Look at the reads if any... if reads exist, they are either the resaon the access is in the event
3177 // first scope, or they are a hazard.
John Zulaufab7756b2020-12-29 16:10:16 -07003178 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003179 if (read_access.tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003180 // The read is in the events first synchronization scope, so we use a barrier hazard check
3181 // If the read stage is not in the src sync scope
3182 // *AND* not execution chained with an existing sync barrier (that's the or)
3183 // then the barrier access is unsafe (R/W after R)
3184 if (read_access.IsReadBarrierHazard(src_exec_scope)) {
3185 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3186 break;
3187 }
3188 } else {
3189 // The read not in the event first sync scope and so is a hazard vs. the layout transition
3190 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3191 }
3192 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003193 } else if (last_write.any()) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003194 // 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 -06003195 if (write_tag < event_tag) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003196 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3197 // So do a normal barrier hazard check
3198 if (IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3199 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3200 }
3201 } else {
3202 // The write isn't in scope, and is thus a hazard to the layout transistion for wait
John Zulauf361fb532020-07-22 10:45:39 -06003203 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3204 }
John Zulaufd14743a2020-07-03 09:42:39 -06003205 }
John Zulauf361fb532020-07-22 10:45:39 -06003206
John Zulauf0cb5be22020-01-23 12:18:22 -07003207 return hazard;
3208}
3209
John Zulauf5f13a792020-03-10 07:31:21 -06003210// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3211// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3212// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3213void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003214 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003215 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3216 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003217 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003218 } else if (other.write_tag == write_tag) {
3219 // 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 -06003220 // dependency chaining logic or any stage expansion)
3221 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003222 pending_write_barriers |= other.pending_write_barriers;
3223 pending_layout_transition |= other.pending_layout_transition;
3224 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003225 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003226
John Zulaufd14743a2020-07-03 09:42:39 -06003227 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003228 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003229 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003230 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003231 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003232 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003233 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003234 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3235 // but we should wait on profiling data for that.
3236 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003237 auto &my_read = last_reads[my_read_index];
3238 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003239 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003240 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003241 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003242 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003243 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003244 my_read.pending_dep_chain = other_read.pending_dep_chain;
3245 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3246 // May require tracking more than one access per stage.
3247 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003248 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003249 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003250 // Since I'm overwriting the fragement stage read, also update the input attachment info
3251 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003252 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003253 }
John Zulauf14940722021-04-12 15:19:02 -06003254 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003255 // The read tags match so merge the barriers
3256 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003257 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003258 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003259 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003260
John Zulauf5f13a792020-03-10 07:31:21 -06003261 break;
3262 }
3263 }
3264 } else {
3265 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003266 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003267 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003268 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003269 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003270 }
John Zulauf5f13a792020-03-10 07:31:21 -06003271 }
3272 }
John Zulauf361fb532020-07-22 10:45:39 -06003273 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003274 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3275 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003276
3277 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3278 // of the copy and other into this using the update first logic.
3279 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3280 // of the other first_accesses... )
3281 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3282 FirstAccesses firsts(std::move(first_accesses_));
3283 first_accesses_.clear();
3284 first_read_stages_ = 0U;
3285 auto a = firsts.begin();
3286 auto a_end = firsts.end();
3287 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003288 // TODO: Determine whether some tag offset will be needed for PHASE II
3289 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003290 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3291 ++a;
3292 }
3293 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3294 }
3295 for (; a != a_end; ++a) {
3296 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3297 }
3298 }
John Zulauf5f13a792020-03-10 07:31:21 -06003299}
3300
John Zulauf14940722021-04-12 15:19:02 -06003301void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003302 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3303 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003304 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003305 // Mulitple outstanding reads may be of interest and do dependency chains independently
3306 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3307 const auto usage_stage = PipelineStageBit(usage_index);
3308 if (usage_stage & last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003309 for (auto &read_access : last_reads) {
3310 if (read_access.stage == usage_stage) {
3311 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003312 } else if (read_access.barriers & usage_stage) {
3313 read_access.sync_stages |= usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003314 }
3315 }
3316 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003317 for (auto &read_access : last_reads) {
3318 if (read_access.barriers & usage_stage) {
3319 read_access.sync_stages |= usage_stage;
3320 }
3321 }
John Zulaufab7756b2020-12-29 16:10:16 -07003322 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003323 last_read_stages |= usage_stage;
3324 }
John Zulauf4285ee92020-09-23 10:20:52 -06003325
3326 // 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 -07003327 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003328 // TODO Revisit re: multiple reads for a given stage
3329 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003330 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003331 } else {
3332 // Assume write
3333 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003334 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003335 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003336 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003337}
John Zulauf5f13a792020-03-10 07:31:21 -06003338
John Zulauf89311b42020-09-29 16:28:47 -06003339// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3340// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3341// We can overwrite them as *this* write is now after them.
3342//
3343// 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 -06003344void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003345 ClearRead();
3346 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003347 write_tag = tag;
3348 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003349}
3350
John Zulauf1d5f9c12022-05-13 14:51:08 -06003351void ResourceAccessState::ClearWrite() {
3352 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3353 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3354 write_barriers.reset();
3355 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3356 last_write.reset();
3357
3358 write_tag = 0;
3359 write_queue = QueueSyncState::kQueueIdInvalid;
3360}
3361
3362void ResourceAccessState::ClearRead() {
3363 last_reads.clear();
3364 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3365}
3366
John Zulauf89311b42020-09-29 16:28:47 -06003367// Apply the memory barrier without updating the existing barriers. The execution barrier
3368// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3369// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3370// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003371template <typename ScopeOps>
3372void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003373 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3374 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003375 // 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 -06003376 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003377 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3378 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003379 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003380 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003381 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003382 if (layout_transition) {
3383 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3384 }
John Zulaufa0a98292020-09-18 09:30:10 -06003385 }
John Zulauf89311b42020-09-29 16:28:47 -06003386 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3387 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003388
John Zulauf89311b42020-09-29 16:28:47 -06003389 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003390 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3391 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003392 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3393
John Zulaufab7756b2020-12-29 16:10:16 -07003394 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003395 // 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 -06003396 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003397 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3398 stages_in_scope |= read_access.stage;
3399 }
3400 }
3401
3402 for (auto &read_access : last_reads) {
3403 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3404 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3405 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3406 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003407 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003408 }
3409 }
John Zulaufa0a98292020-09-18 09:30:10 -06003410 }
John Zulaufa0a98292020-09-18 09:30:10 -06003411}
3412
John Zulauf14940722021-04-12 15:19:02 -06003413void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003414 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003415 // 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 -06003416 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003417 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003418 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3419 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003420 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003421 }
John Zulauf89311b42020-09-29 16:28:47 -06003422
3423 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003424 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003425 for (auto &read_access : last_reads) {
3426 read_access.barriers |= read_access.pending_dep_chain;
3427 read_execution_barriers |= read_access.barriers;
3428 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003429 }
3430
3431 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3432 write_dependency_chain |= pending_write_dep_chain;
3433 write_barriers |= pending_write_barriers;
3434 pending_write_dep_chain = 0;
3435 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003436}
3437
John Zulauf1d5f9c12022-05-13 14:51:08 -06003438bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3439 return (queue == usage_queue) && (tag <= usage_tag);
3440}
3441
3442bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3443
3444bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3445
3446// Return if the resulting state is "empty"
3447template <typename Pred>
3448bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3449 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3450
3451 // Use the predicate to build a mask of the read stages we are synchronizing
3452 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003453 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003454 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003455 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3456 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003457 }
3458 }
3459
John Zulauf434c4e62022-05-19 16:03:56 -06003460 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3461 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3462 uint32_t unsync_count = 0;
3463 for (auto &read_access : last_reads) {
3464 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3465 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3466 sync_reads |= read_access.stage;
3467 } else {
3468 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003469 }
3470 }
3471
3472 if (unsync_count) {
3473 if (sync_reads) {
3474 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3475 ReadStates unsync_reads;
3476 unsync_reads.reserve(unsync_count);
3477 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3478 for (auto &read_access : last_reads) {
3479 if (0 == (read_access.stage & sync_reads)) {
3480 unsync_reads.emplace_back(read_access);
3481 unsync_read_stages |= read_access.stage;
3482 }
3483 }
3484 last_read_stages = unsync_read_stages;
3485 last_reads = std::move(unsync_reads);
3486 }
3487 } else {
3488 // Nothing remains (or it was empty to begin with)
3489 ClearRead();
3490 }
3491
3492 bool all_clear = last_reads.size() == 0;
3493 if (last_write.any()) {
3494 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3495 // Clear any predicated write, or any the write from any any access with synchronized reads.
3496 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3497 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3498 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3499 ClearWrite();
3500 } else {
3501 all_clear = false;
3502 }
3503 }
3504 return all_clear;
3505}
3506
John Zulaufae842002021-04-15 18:20:55 -06003507bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3508 if (!first_accesses_.size()) return false;
3509 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3510 return tag_range.intersects(first_access_range);
3511}
3512
John Zulauf1d5f9c12022-05-13 14:51:08 -06003513void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3514 if (last_write.any()) write_tag += offset;
3515 for (auto &read_access : last_reads) {
3516 read_access.tag += offset;
3517 }
3518 for (auto &first : first_accesses_) {
3519 first.tag += offset;
3520 }
3521}
3522
3523ResourceAccessState::ResourceAccessState()
3524 : write_barriers(~SyncStageAccessFlags(0)),
3525 write_dependency_chain(0),
3526 write_tag(),
3527 write_queue(QueueSyncState::kQueueIdInvalid),
3528 last_write(0),
3529 input_attachment_read(false),
3530 last_read_stages(0),
3531 read_execution_barriers(0),
3532 pending_write_dep_chain(0),
3533 pending_layout_transition(false),
3534 pending_write_barriers(0),
3535 pending_layout_ordering_(),
3536 first_accesses_(),
3537 first_read_stages_(0U),
3538 first_write_layout_ordering_() {}
3539
John Zulauf59e25072020-07-17 10:55:21 -06003540// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003541VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3542 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003543
John Zulaufab7756b2020-12-29 16:10:16 -07003544 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003545 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003546 barriers = read_access.barriers;
3547 break;
John Zulauf59e25072020-07-17 10:55:21 -06003548 }
3549 }
John Zulauf4285ee92020-09-23 10:20:52 -06003550
John Zulauf59e25072020-07-17 10:55:21 -06003551 return barriers;
3552}
3553
John Zulauf1d5f9c12022-05-13 14:51:08 -06003554void ResourceAccessState::SetQueueId(QueueId id) {
3555 for (auto &read_access : last_reads) {
3556 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3557 read_access.queue = id;
3558 }
3559 }
3560 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3561 write_queue = id;
3562 }
3563}
3564
John Zulauf00119522022-05-23 19:07:42 -06003565bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3566 return 0 != (write_dependency_chain & src_exec_scope);
3567}
3568
3569bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3570 return (src_access_scope & last_write).any();
3571}
3572
John Zulaufb7578302022-05-19 13:50:18 -06003573bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3574 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003575 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3576}
3577
3578bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3579 SyncStageAccessFlags src_access_scope) const {
3580 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003581}
3582
3583bool ResourceAccessState::WriteInEventScope(const SyncStageAccessFlags &src_access_scope, ResourceUsageTag scope_tag) const {
3584 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3585 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3586 // in order to know if it's in the excecution scope
John Zulauf00119522022-05-23 19:07:42 -06003587 return (write_tag < scope_tag) && WriteInScope(src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003588}
3589
John Zulaufcb7e1672022-05-04 13:46:08 -06003590bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003591 assert(IsRead(usage));
3592 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3593 // * the previous reads are not hazards, and thus last_write must be visible and available to
3594 // any reads that happen after.
3595 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3596 // 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 -07003597 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003598}
3599
Jeremy Gebben40a22942020-12-22 14:22:06 -07003600VkPipelineStageFlags2KHR ResourceAccessState::GetOrderedStages(const OrderingBarrier &ordering) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003601 // Whether the stage are in the ordering scope only matters if the current write is ordered
Jeremy Gebben40a22942020-12-22 14:22:06 -07003602 VkPipelineStageFlags2KHR ordered_stages = last_read_stages & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003603 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003604 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003605 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003606 // 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 -07003607 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003608 }
3609
3610 return ordered_stages;
3611}
3612
John Zulauf14940722021-04-12 15:19:02 -06003613void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003614 // Only record until we record a write.
3615 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003616 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003617 if (0 == (usage_stage & first_read_stages_)) {
3618 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003619 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003620 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003621 if (0 == (read_execution_barriers & usage_stage)) {
3622 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3623 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3624 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003625 }
3626 }
3627}
3628
John Zulauf4fa68462021-04-26 21:04:22 -06003629void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3630 // Only call this after recording an image layout transition
3631 assert(first_accesses_.size());
3632 if (first_accesses_.back().tag == tag) {
3633 // 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 +02003634 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003635 first_write_layout_ordering_ = layout_ordering;
3636 }
3637}
3638
John Zulauf1d5f9c12022-05-13 14:51:08 -06003639ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3640 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3641 : stage(stage_),
3642 access(access_),
3643 barriers(barriers_),
3644 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3645 tag(tag_),
3646 queue(QueueSyncState::kQueueIdInvalid),
3647 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3648
John Zulaufee984022022-04-13 16:39:50 -06003649void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3650 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3651 stage = stage_;
3652 access = access_;
3653 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003654 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003655 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003656 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 -06003657}
3658
John Zulauf00119522022-05-23 19:07:42 -06003659// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3660// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3661// that have bee applied (via semaphore) to those accesses can be chained off of.
3662bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3663 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3664 return (exec_scope & effective_stages) != 0;
3665}
3666
John Zulauf697c0e12022-04-19 16:31:12 -06003667ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3668 ResourceUsageRange reserve;
3669 reserve.begin = tag_limit_.fetch_add(tag_count);
3670 reserve.end = reserve.begin + tag_count;
3671 return reserve;
3672}
3673
John Zulaufbbda4572022-04-19 16:20:45 -06003674const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3675 return GetMappedPlainFromShared(queue_sync_states_, queue);
3676}
3677
3678QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3679
3680std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3681 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3682}
3683
3684std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3685 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3686}
3687
John Zulauf1d5f9c12022-05-13 14:51:08 -06003688template <typename BatchSet, typename Predicate>
3689static BatchSet GetQueueLastBatchSnapshotImpl(const SyncValidator::QueueSyncStatesMap &queues, Predicate &&pred) {
3690 BatchSet snapshot;
3691 for (auto &queue : queues) {
John Zulauf697c0e12022-04-19 16:31:12 -06003692 auto batch = queue.second->LastBatch();
John Zulauf1d5f9c12022-05-13 14:51:08 -06003693 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003694 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003695 return snapshot;
3696}
3697
3698template <typename Predicate>
3699QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
3700 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::ConstBatchSet, Predicate>(queue_sync_states_,
3701 std::forward<Predicate>(pred));
3702}
3703
3704template <typename Predicate>
3705QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
3706 return GetQueueLastBatchSnapshotImpl<QueueBatchContext::BatchSet, Predicate>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf697c0e12022-04-19 16:31:12 -06003707}
3708
John Zulaufcb7e1672022-05-04 13:46:08 -06003709bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3710 const std::shared_ptr<QueueBatchContext> &batch,
3711 const VkSemaphoreSubmitInfo &signal_info) {
3712 const SyncExecScope exec_scope =
3713 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3714 const VkSemaphore sem = sem_state->semaphore();
3715 auto signal_it = signaled_.find(sem);
3716 std::shared_ptr<Signal> insert_signal;
3717 if (signal_it == signaled_.end()) {
3718 if (prev_) {
3719 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3720 if (prev_sig) {
3721 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3722 insert_signal = std::make_shared<Signal>(*prev_sig);
3723 }
3724 }
3725 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3726 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003727 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003728
3729 bool success = false;
3730 if (!signal_it->second) {
3731 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3732 success = true;
3733 }
3734
3735 return success;
3736}
3737
3738std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3739 std::shared_ptr<Signal> unsignaled;
3740 const auto found_it = signaled_.find(sem);
3741 if (found_it != signaled_.end()) {
3742 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3743 // a bit.
3744 unsignaled = std::move(found_it->second);
3745 if (!prev_) {
3746 // No parent, not need to keep the entry
3747 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3748 signaled_.erase(found_it);
3749 }
3750 } else if (prev_) {
3751 // We can't unsignal prev_ because it's const * by design.
3752 // We put in an empty placeholder
3753 signaled_.emplace(sem, std::shared_ptr<Signal>());
3754 unsignaled = GetPrev(sem);
3755 }
3756 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3757 // but CoreChecks should have reported it
3758
3759 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003760 return unsignaled;
3761}
3762
John Zulaufcb7e1672022-05-04 13:46:08 -06003763void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3764 // Overwrite the s tate with the last state from this
3765 if (from) {
3766 assert(sem == from->sem_state->semaphore());
3767 signaled_[sem] = std::move(from);
3768 } else {
3769 signaled_.erase(sem);
3770 }
3771}
3772
3773void SignaledSemaphores::Reset() {
3774 signaled_.clear();
3775 prev_ = nullptr;
3776}
3777
John Zulaufea943c52022-02-22 11:05:17 -07003778std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3779 // If we don't have one, make it.
3780 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3781 assert(cb_state.get());
3782 auto queue_flags = cb_state->GetQueueFlags();
3783 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3784}
3785
John Zulaufcb7e1672022-05-04 13:46:08 -06003786std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003787 return GetMappedInsert(cb_access_state, command_buffer,
3788 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3789}
3790
3791std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3792 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3793}
3794
3795const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3796 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3797}
3798
3799CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3800 return GetAccessContextShared(command_buffer).get();
3801}
3802
3803CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3804 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3805}
3806
John Zulaufd1f85d42020-04-15 12:23:15 -06003807void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003808 auto *access_context = GetAccessContextNoInsert(command_buffer);
3809 if (access_context) {
3810 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003811 }
3812}
3813
John Zulaufd1f85d42020-04-15 12:23:15 -06003814void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3815 auto access_found = cb_access_state.find(command_buffer);
3816 if (access_found != cb_access_state.end()) {
3817 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003818 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003819 cb_access_state.erase(access_found);
3820 }
3821}
3822
John Zulauf9cb530d2019-09-30 14:14:10 -06003823bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3824 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3825 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003826 const auto *cb_context = GetAccessContext(commandBuffer);
3827 assert(cb_context);
3828 if (!cb_context) return skip;
3829 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003830
John Zulauf3d84f1b2020-03-09 13:33:25 -06003831 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003832 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3833 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003834
3835 for (uint32_t region = 0; region < regionCount; region++) {
3836 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003837 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003838 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003839 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003840 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003841 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003842 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003843 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003844 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003845 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003846 }
John Zulauf16adfc92020-04-08 10:28:33 -06003847 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003848 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003849 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003850 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003851 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003852 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003853 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003854 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003855 }
3856 }
3857 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003858 }
3859 return skip;
3860}
3861
3862void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3863 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003864 auto *cb_context = GetAccessContext(commandBuffer);
3865 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003866 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003867 auto *context = cb_context->GetCurrentAccessContext();
3868
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003869 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3870 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003871
3872 for (uint32_t region = 0; region < regionCount; region++) {
3873 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003874 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003875 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003876 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003877 }
John Zulauf16adfc92020-04-08 10:28:33 -06003878 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003879 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003880 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003881 }
3882 }
3883}
3884
John Zulauf4a6105a2020-11-17 15:11:05 -07003885void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
3886 // Clear out events from the command buffer contexts
3887 for (auto &cb_context : cb_access_state) {
3888 cb_context.second->RecordDestroyEvent(event);
3889 }
3890}
3891
Tony-LunarGef035472021-11-02 10:23:33 -06003892bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
3893 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04003894 bool skip = false;
3895 const auto *cb_context = GetAccessContext(commandBuffer);
3896 assert(cb_context);
3897 if (!cb_context) return skip;
3898 const auto *context = cb_context->GetCurrentAccessContext();
Tony-LunarGef035472021-11-02 10:23:33 -06003899 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04003900
3901 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003902 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3903 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003904
3905 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3906 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3907 if (src_buffer) {
3908 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003909 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003910 if (hazard.hazard) {
3911 // TODO -- add tag information to log msg when useful.
3912 skip |= LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
Tony-LunarGef035472021-11-02 10:23:33 -06003913 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04003914 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06003915 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003916 }
3917 }
3918 if (dst_buffer && !skip) {
3919 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003920 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04003921 if (hazard.hazard) {
3922 skip |= LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
Tony-LunarGef035472021-11-02 10:23:33 -06003923 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04003924 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06003925 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04003926 }
3927 }
3928 if (skip) break;
3929 }
3930 return skip;
3931}
3932
Tony-LunarGef035472021-11-02 10:23:33 -06003933bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
3934 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
3935 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3936}
3937
3938bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
3939 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3940}
3941
3942void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04003943 auto *cb_context = GetAccessContext(commandBuffer);
3944 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06003945 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04003946 auto *context = cb_context->GetCurrentAccessContext();
3947
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003948 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
3949 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04003950
3951 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
3952 const auto &copy_region = pCopyBufferInfos->pRegions[region];
3953 if (src_buffer) {
3954 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003955 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003956 }
3957 if (dst_buffer) {
3958 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003959 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04003960 }
3961 }
3962}
3963
Tony-LunarGef035472021-11-02 10:23:33 -06003964void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
3965 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
3966}
3967
3968void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
3969 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
3970}
3971
John Zulauf5c5e88d2019-12-26 11:22:02 -07003972bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
3973 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
3974 const VkImageCopy *pRegions) const {
3975 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003976 const auto *cb_access_context = GetAccessContext(commandBuffer);
3977 assert(cb_access_context);
3978 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07003979
John Zulauf3d84f1b2020-03-09 13:33:25 -06003980 const auto *context = cb_access_context->GetCurrentAccessContext();
3981 assert(context);
3982 if (!context) return skip;
3983
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003984 auto src_image = Get<IMAGE_STATE>(srcImage);
3985 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003986 for (uint32_t region = 0; region < regionCount; region++) {
3987 const auto &copy_region = pRegions[region];
3988 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003989 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02003990 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003991 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003992 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003993 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003994 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003995 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07003996 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06003997 }
3998
3999 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004000 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004001 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004002 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004003 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004004 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004005 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004006 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004007 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004008 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004009 }
4010 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004011
John Zulauf5c5e88d2019-12-26 11:22:02 -07004012 return skip;
4013}
4014
4015void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4016 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4017 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004018 auto *cb_access_context = GetAccessContext(commandBuffer);
4019 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004020 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004021 auto *context = cb_access_context->GetCurrentAccessContext();
4022 assert(context);
4023
Jeremy Gebben9f537102021-10-05 16:37:12 -06004024 auto src_image = Get<IMAGE_STATE>(srcImage);
4025 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004026
4027 for (uint32_t region = 0; region < regionCount; region++) {
4028 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004029 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004030 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004031 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004032 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004033 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004034 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004035 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004036 }
4037 }
4038}
4039
Tony-LunarGb61514a2021-11-02 12:36:51 -06004040bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4041 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004042 bool skip = false;
4043 const auto *cb_access_context = GetAccessContext(commandBuffer);
4044 assert(cb_access_context);
4045 if (!cb_access_context) return skip;
4046
4047 const auto *context = cb_access_context->GetCurrentAccessContext();
4048 assert(context);
4049 if (!context) return skip;
4050
Tony-LunarGb61514a2021-11-02 12:36:51 -06004051 const char *func_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004052 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4053 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004054
Jeff Leger178b1e52020-10-05 12:22:23 -04004055 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4056 const auto &copy_region = pCopyImageInfo->pRegions[region];
4057 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004058 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004059 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004060 if (hazard.hazard) {
4061 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sfricke-samsung71f04e32022-03-16 01:21:21 -05004062 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04004063 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004064 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004065 }
4066 }
4067
4068 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004069 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004070 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004071 if (hazard.hazard) {
4072 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sfricke-samsung71f04e32022-03-16 01:21:21 -05004073 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04004074 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004075 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004076 }
4077 if (skip) break;
4078 }
4079 }
4080
4081 return skip;
4082}
4083
Tony-LunarGb61514a2021-11-02 12:36:51 -06004084bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4085 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4086 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4087}
4088
4089bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4090 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4091}
4092
4093void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004094 auto *cb_access_context = GetAccessContext(commandBuffer);
4095 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004096 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004097 auto *context = cb_access_context->GetCurrentAccessContext();
4098 assert(context);
4099
Jeremy Gebben9f537102021-10-05 16:37:12 -06004100 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4101 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004102
4103 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4104 const auto &copy_region = pCopyImageInfo->pRegions[region];
4105 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004106 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004107 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004108 }
4109 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004110 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004111 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004112 }
4113 }
4114}
4115
Tony-LunarGb61514a2021-11-02 12:36:51 -06004116void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4117 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4118}
4119
4120void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4121 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4122}
4123
John Zulauf9cb530d2019-09-30 14:14:10 -06004124bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4125 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4126 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4127 uint32_t bufferMemoryBarrierCount,
4128 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4129 uint32_t imageMemoryBarrierCount,
4130 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4131 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004132 const auto *cb_access_context = GetAccessContext(commandBuffer);
4133 assert(cb_access_context);
4134 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004135
John Zulauf36ef9282021-02-02 11:47:24 -07004136 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4137 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4138 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4139 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004140 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004141 return skip;
4142}
4143
4144void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4145 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4146 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4147 uint32_t bufferMemoryBarrierCount,
4148 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4149 uint32_t imageMemoryBarrierCount,
4150 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004151 auto *cb_access_context = GetAccessContext(commandBuffer);
4152 assert(cb_access_context);
4153 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004154
John Zulauf1bf30522021-09-03 15:39:06 -06004155 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4156 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4157 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4158 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004159}
4160
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004161bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4162 const VkDependencyInfoKHR *pDependencyInfo) const {
4163 bool skip = false;
4164 const auto *cb_access_context = GetAccessContext(commandBuffer);
4165 assert(cb_access_context);
4166 if (!cb_access_context) return skip;
4167
4168 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4169 skip = pipeline_barrier.Validate(*cb_access_context);
4170 return skip;
4171}
4172
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004173bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4174 const VkDependencyInfo *pDependencyInfo) const {
4175 bool skip = false;
4176 const auto *cb_access_context = GetAccessContext(commandBuffer);
4177 assert(cb_access_context);
4178 if (!cb_access_context) return skip;
4179
4180 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4181 skip = pipeline_barrier.Validate(*cb_access_context);
4182 return skip;
4183}
4184
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004185void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4186 auto *cb_access_context = GetAccessContext(commandBuffer);
4187 assert(cb_access_context);
4188 if (!cb_access_context) return;
4189
John Zulauf1bf30522021-09-03 15:39:06 -06004190 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4191 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004192}
4193
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004194void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4195 auto *cb_access_context = GetAccessContext(commandBuffer);
4196 assert(cb_access_context);
4197 if (!cb_access_context) return;
4198
4199 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4200 *pDependencyInfo);
4201}
4202
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004203void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004204 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004205 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004206
John Zulauf5f13a792020-03-10 07:31:21 -06004207 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4208 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004209 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004210 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4211 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004212
John Zulauf1d5f9c12022-05-13 14:51:08 -06004213 QueueId queue_id = QueueSyncState::kQueueIdBase;
4214 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004215 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004216 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004217 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4218 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004219}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004220
John Zulauf355e49b2020-04-24 15:11:15 -06004221bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07004222 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004223 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004224 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004225 if (cb_context) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004226 SyncOpBeginRenderPass sync_op(cmd, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004227 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004228 }
John Zulauf355e49b2020-04-24 15:11:15 -06004229 return skip;
4230}
4231
4232bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4233 VkSubpassContents contents) const {
4234 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004235 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004236 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004237 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004238 return skip;
4239}
4240
4241bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004242 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004243 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004244 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004245 return skip;
4246}
4247
4248bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4249 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004250 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004251 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004252 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004253 return skip;
4254}
4255
John Zulauf3d84f1b2020-03-09 13:33:25 -06004256void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4257 VkResult result) {
4258 // The state tracker sets up the command buffer state
4259 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4260
4261 // Create/initialize the structure that trackers accesses at the command buffer scope.
4262 auto cb_access_context = GetAccessContext(commandBuffer);
4263 assert(cb_access_context);
4264 cb_access_context->Reset();
4265}
4266
4267void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07004268 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004269 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004270 if (cb_context) {
John Zulaufbb890452021-12-14 11:30:18 -07004271 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004272 }
4273}
4274
4275void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4276 VkSubpassContents contents) {
4277 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004278 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004279 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004280 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004281}
4282
4283void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4284 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4285 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004286 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004287}
4288
4289void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4290 const VkRenderPassBeginInfo *pRenderPassBegin,
4291 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4292 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004293 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004294}
4295
Mike Schuchardt2df08912020-12-15 16:28:09 -08004296bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07004297 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004298 bool skip = false;
4299
4300 auto cb_context = GetAccessContext(commandBuffer);
4301 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004302 if (!cb_context) return skip;
sfricke-samsung85584a72021-09-30 21:43:38 -07004303 SyncOpNextSubpass sync_op(cmd, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004304 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004305}
4306
4307bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4308 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004309 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004310 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004311 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004312 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4313 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004314 return skip;
4315}
4316
Mike Schuchardt2df08912020-12-15 16:28:09 -08004317bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4318 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004319 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004320 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004321 return skip;
4322}
4323
4324bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4325 const VkSubpassEndInfo *pSubpassEndInfo) const {
4326 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004327 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004328 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004329}
4330
4331void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07004332 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004333 auto cb_context = GetAccessContext(commandBuffer);
4334 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004335 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004336
John Zulaufbb890452021-12-14 11:30:18 -07004337 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004338}
4339
4340void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4341 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004342 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004343 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004344 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004345}
4346
4347void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4348 const VkSubpassEndInfo *pSubpassEndInfo) {
4349 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004350 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004351}
4352
4353void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4354 const VkSubpassEndInfo *pSubpassEndInfo) {
4355 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004356 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004357}
4358
sfricke-samsung85584a72021-09-30 21:43:38 -07004359bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4360 CMD_TYPE cmd) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004361 bool skip = false;
4362
4363 auto cb_context = GetAccessContext(commandBuffer);
4364 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004365 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004366
sfricke-samsung85584a72021-09-30 21:43:38 -07004367 SyncOpEndRenderPass sync_op(cmd, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004368 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004369 return skip;
4370}
4371
4372bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4373 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004374 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004375 return skip;
4376}
4377
Mike Schuchardt2df08912020-12-15 16:28:09 -08004378bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004379 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004380 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004381 return skip;
4382}
4383
4384bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004385 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004386 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004387 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004388 return skip;
4389}
4390
sfricke-samsung85584a72021-09-30 21:43:38 -07004391void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004392 // Resolve the all subpass contexts to the command buffer contexts
4393 auto cb_context = GetAccessContext(commandBuffer);
4394 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004395 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004396
John Zulaufbb890452021-12-14 11:30:18 -07004397 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004398}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004399
John Zulauf33fc1d52020-07-17 11:01:10 -06004400// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4401// updates to a resource which do not conflict at the byte level.
4402// TODO: Revisit this rule to see if it needs to be tighter or looser
4403// TODO: Add programatic control over suppression heuristics
4404bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4405 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4406}
4407
John Zulauf3d84f1b2020-03-09 13:33:25 -06004408void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004409 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004410 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004411}
4412
4413void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004414 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004415 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004416}
4417
4418void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004419 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004420 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004421}
locke-lunarga19c71d2020-03-02 18:17:04 -07004422
sfricke-samsung71f04e32022-03-16 01:21:21 -05004423template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004424bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004425 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4426 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004427 bool skip = false;
4428 const auto *cb_access_context = GetAccessContext(commandBuffer);
4429 assert(cb_access_context);
4430 if (!cb_access_context) return skip;
4431
Tony Barbour845d29b2021-11-09 11:43:14 -07004432 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004433
locke-lunarga19c71d2020-03-02 18:17:04 -07004434 const auto *context = cb_access_context->GetCurrentAccessContext();
4435 assert(context);
4436 if (!context) return skip;
4437
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004438 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4439 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004440
4441 for (uint32_t region = 0; region < regionCount; region++) {
4442 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004443 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004444 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004445 if (src_buffer) {
4446 ResourceAccessRange src_range =
4447 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004448 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004449 if (hazard.hazard) {
4450 // PHASE1 TODO -- add tag information to log msg when useful.
4451 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4452 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
4453 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004454 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004455 }
4456 }
4457
Jeremy Gebben40a22942020-12-22 14:22:06 -07004458 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004459 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004460 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004461 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004462 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004463 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004464 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004465 }
4466 if (skip) break;
4467 }
4468 if (skip) break;
4469 }
4470 return skip;
4471}
4472
Jeff Leger178b1e52020-10-05 12:22:23 -04004473bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4474 VkImageLayout dstImageLayout, uint32_t regionCount,
4475 const VkBufferImageCopy *pRegions) const {
4476 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004477 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004478}
4479
4480bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4481 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4482 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4483 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004484 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4485}
4486
4487bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4488 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4489 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4490 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4491 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004492}
4493
sfricke-samsung71f04e32022-03-16 01:21:21 -05004494template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004495void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004496 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4497 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004498 auto *cb_access_context = GetAccessContext(commandBuffer);
4499 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004500
Jeff Leger178b1e52020-10-05 12:22:23 -04004501 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004502 auto *context = cb_access_context->GetCurrentAccessContext();
4503 assert(context);
4504
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004505 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4506 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004507
4508 for (uint32_t region = 0; region < regionCount; region++) {
4509 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004510 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004511 if (src_buffer) {
4512 ResourceAccessRange src_range =
4513 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004514 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004515 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004516 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004517 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004518 }
4519 }
4520}
4521
Jeff Leger178b1e52020-10-05 12:22:23 -04004522void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4523 VkImageLayout dstImageLayout, uint32_t regionCount,
4524 const VkBufferImageCopy *pRegions) {
4525 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004526 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004527}
4528
4529void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4530 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4531 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4532 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4533 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004534 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4535}
4536
4537void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4538 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4539 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4540 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4541 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4542 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004543}
4544
sfricke-samsung71f04e32022-03-16 01:21:21 -05004545template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004546bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004547 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4548 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004549 bool skip = false;
4550 const auto *cb_access_context = GetAccessContext(commandBuffer);
4551 assert(cb_access_context);
4552 if (!cb_access_context) return skip;
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004553 const char *func_name = CommandTypeString(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004554
locke-lunarga19c71d2020-03-02 18:17:04 -07004555 const auto *context = cb_access_context->GetCurrentAccessContext();
4556 assert(context);
4557 if (!context) return skip;
4558
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004559 auto src_image = Get<IMAGE_STATE>(srcImage);
4560 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004561 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004562 for (uint32_t region = 0; region < regionCount; region++) {
4563 const auto &copy_region = pRegions[region];
4564 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004565 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004566 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004567 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004568 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004569 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004570 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004571 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004572 }
John Zulauf477700e2021-01-06 11:41:49 -07004573 if (dst_mem) {
4574 ResourceAccessRange dst_range =
4575 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004576 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004577 if (hazard.hazard) {
4578 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4579 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", func_name,
4580 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004581 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004582 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004583 }
4584 }
4585 if (skip) break;
4586 }
4587 return skip;
4588}
4589
Jeff Leger178b1e52020-10-05 12:22:23 -04004590bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4591 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4592 const VkBufferImageCopy *pRegions) const {
4593 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004594 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004595}
4596
4597bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4598 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4599 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4600 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004601 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4602}
4603
4604bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4605 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4606 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4607 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4608 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004609}
4610
sfricke-samsung71f04e32022-03-16 01:21:21 -05004611template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004612void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004613 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004614 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004615 auto *cb_access_context = GetAccessContext(commandBuffer);
4616 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004617
Jeff Leger178b1e52020-10-05 12:22:23 -04004618 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004619 auto *context = cb_access_context->GetCurrentAccessContext();
4620 assert(context);
4621
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004622 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004623 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004624 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004625 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004626
4627 for (uint32_t region = 0; region < regionCount; region++) {
4628 const auto &copy_region = pRegions[region];
4629 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004630 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004631 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004632 if (dst_buffer) {
4633 ResourceAccessRange dst_range =
4634 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004635 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004636 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004637 }
4638 }
4639}
4640
Jeff Leger178b1e52020-10-05 12:22:23 -04004641void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4642 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4643 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004644 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004645}
4646
4647void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4648 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4649 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4650 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4651 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004652 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4653}
4654
4655void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4656 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4657 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4658 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4659 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4660 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004661}
4662
4663template <typename RegionType>
4664bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4665 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4666 const RegionType *pRegions, VkFilter filter, const char *apiName) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004667 bool skip = false;
4668 const auto *cb_access_context = GetAccessContext(commandBuffer);
4669 assert(cb_access_context);
4670 if (!cb_access_context) return skip;
4671
4672 const auto *context = cb_access_context->GetCurrentAccessContext();
4673 assert(context);
4674 if (!context) return skip;
4675
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004676 auto src_image = Get<IMAGE_STATE>(srcImage);
4677 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004678
4679 for (uint32_t region = 0; region < regionCount; region++) {
4680 const auto &blit_region = pRegions[region];
4681 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004682 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4683 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4684 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4685 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4686 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4687 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004688 auto hazard =
4689 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004690 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004691 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004692 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004693 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004694 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004695 }
4696 }
4697
4698 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004699 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4700 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4701 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4702 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4703 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4704 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004705 auto hazard =
4706 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004707 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004708 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
Jeff Leger178b1e52020-10-05 12:22:23 -04004709 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", apiName,
John Zulauf1dae9192020-06-16 15:46:44 -06004710 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004711 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004712 }
4713 if (skip) break;
4714 }
4715 }
4716
4717 return skip;
4718}
4719
Jeff Leger178b1e52020-10-05 12:22:23 -04004720bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4721 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4722 const VkImageBlit *pRegions, VkFilter filter) const {
4723 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
4724 "vkCmdBlitImage");
4725}
4726
4727bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4728 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4729 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4730 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4731 pBlitImageInfo->filter, "vkCmdBlitImage2KHR");
4732}
4733
Tony-LunarG542ae912021-11-04 16:06:44 -06004734bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4735 const VkBlitImageInfo2 *pBlitImageInfo) const {
4736 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4737 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4738 pBlitImageInfo->filter, "vkCmdBlitImage2");
4739}
4740
Jeff Leger178b1e52020-10-05 12:22:23 -04004741template <typename RegionType>
4742void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4743 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4744 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004745 auto *cb_access_context = GetAccessContext(commandBuffer);
4746 assert(cb_access_context);
4747 auto *context = cb_access_context->GetCurrentAccessContext();
4748 assert(context);
4749
Jeremy Gebben9f537102021-10-05 16:37:12 -06004750 auto src_image = Get<IMAGE_STATE>(srcImage);
4751 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004752
4753 for (uint32_t region = 0; region < regionCount; region++) {
4754 const auto &blit_region = pRegions[region];
4755 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004756 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4757 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4758 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4759 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4760 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4761 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004762 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004763 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004764 }
4765 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004766 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4767 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4768 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4769 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4770 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4771 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004772 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004773 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004774 }
4775 }
4776}
locke-lunarg36ba2592020-04-03 09:42:04 -06004777
Jeff Leger178b1e52020-10-05 12:22:23 -04004778void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4779 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4780 const VkImageBlit *pRegions, VkFilter filter) {
4781 auto *cb_access_context = GetAccessContext(commandBuffer);
4782 assert(cb_access_context);
4783 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4784 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4785 pRegions, filter);
4786 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4787}
4788
4789void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4790 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4791 auto *cb_access_context = GetAccessContext(commandBuffer);
4792 assert(cb_access_context);
4793 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4794 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4795 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4796 pBlitImageInfo->filter, tag);
4797}
4798
Tony-LunarG542ae912021-11-04 16:06:44 -06004799void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4800 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4801 auto *cb_access_context = GetAccessContext(commandBuffer);
4802 assert(cb_access_context);
4803 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4804 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4805 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4806 pBlitImageInfo->filter, tag);
4807}
4808
John Zulauffaea0ee2021-01-14 14:01:32 -07004809bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4810 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4811 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
4812 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004813 bool skip = false;
4814 if (drawCount == 0) return skip;
4815
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004816 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004817 VkDeviceSize size = struct_size;
4818 if (drawCount == 1 || stride == size) {
4819 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004820 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004821 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4822 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004823 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004824 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004825 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004826 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004827 }
4828 } else {
4829 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004830 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004831 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4832 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004833 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004834 "%s: Hazard %s for indirect %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
4835 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004836 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004837 break;
4838 }
4839 }
4840 }
4841 return skip;
4842}
4843
John Zulauf14940722021-04-12 15:19:02 -06004844void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004845 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4846 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004847 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004848 VkDeviceSize size = struct_size;
4849 if (drawCount == 1 || stride == size) {
4850 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004851 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004852 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004853 } else {
4854 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004855 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004856 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4857 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004858 }
4859 }
4860}
4861
John Zulauffaea0ee2021-01-14 14:01:32 -07004862bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4863 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4864 const char *function) const {
locke-lunargff255f92020-05-13 18:53:52 -06004865 bool skip = false;
4866
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004867 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004868 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004869 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4870 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004871 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004872 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", function, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004873 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004874 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004875 }
4876 return skip;
4877}
4878
John Zulauf14940722021-04-12 15:19:02 -06004879void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004880 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004881 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004882 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004883}
4884
locke-lunarg36ba2592020-04-03 09:42:04 -06004885bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06004886 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004887 const auto *cb_access_context = GetAccessContext(commandBuffer);
4888 assert(cb_access_context);
4889 if (!cb_access_context) return skip;
4890
locke-lunarg61870c22020-06-09 14:51:50 -06004891 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatch");
locke-lunargff255f92020-05-13 18:53:52 -06004892 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06004893}
4894
4895void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004896 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06004897 auto *cb_access_context = GetAccessContext(commandBuffer);
4898 assert(cb_access_context);
4899 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06004900
locke-lunarg61870c22020-06-09 14:51:50 -06004901 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06004902}
locke-lunarge1a67022020-04-29 00:15:36 -06004903
4904bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06004905 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004906 const auto *cb_access_context = GetAccessContext(commandBuffer);
4907 assert(cb_access_context);
4908 if (!cb_access_context) return skip;
4909
4910 const auto *context = cb_access_context->GetCurrentAccessContext();
4911 assert(context);
4912 if (!context) return skip;
4913
locke-lunarg61870c22020-06-09 14:51:50 -06004914 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, "vkCmdDispatchIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004915 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
4916 1, sizeof(VkDispatchIndirectCommand), "vkCmdDispatchIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004917 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004918}
4919
4920void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004921 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06004922 auto *cb_access_context = GetAccessContext(commandBuffer);
4923 assert(cb_access_context);
4924 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
4925 auto *context = cb_access_context->GetCurrentAccessContext();
4926 assert(context);
4927
locke-lunarg61870c22020-06-09 14:51:50 -06004928 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
4929 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06004930}
4931
4932bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4933 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004934 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004935 const auto *cb_access_context = GetAccessContext(commandBuffer);
4936 assert(cb_access_context);
4937 if (!cb_access_context) return skip;
4938
locke-lunarg61870c22020-06-09 14:51:50 -06004939 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDraw");
4940 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, "vkCmdDraw");
4941 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDraw");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004942 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004943}
4944
4945void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
4946 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004947 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004948 auto *cb_access_context = GetAccessContext(commandBuffer);
4949 assert(cb_access_context);
4950 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06004951
locke-lunarg61870c22020-06-09 14:51:50 -06004952 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4953 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
4954 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004955}
4956
4957bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4958 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06004959 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06004960 const auto *cb_access_context = GetAccessContext(commandBuffer);
4961 assert(cb_access_context);
4962 if (!cb_access_context) return skip;
4963
locke-lunarg61870c22020-06-09 14:51:50 -06004964 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexed");
4965 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, "vkCmdDrawIndexed");
4966 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexed");
locke-lunarga4d39ea2020-05-22 14:17:29 -06004967 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06004968}
4969
4970void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
4971 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06004972 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06004973 auto *cb_access_context = GetAccessContext(commandBuffer);
4974 assert(cb_access_context);
4975 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06004976
locke-lunarg61870c22020-06-09 14:51:50 -06004977 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
4978 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
4979 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06004980}
4981
4982bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
4983 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06004984 bool skip = false;
4985 if (drawCount == 0) return skip;
4986
locke-lunargff255f92020-05-13 18:53:52 -06004987 const auto *cb_access_context = GetAccessContext(commandBuffer);
4988 assert(cb_access_context);
4989 if (!cb_access_context) return skip;
4990
4991 const auto *context = cb_access_context->GetCurrentAccessContext();
4992 assert(context);
4993 if (!context) return skip;
4994
locke-lunarg61870c22020-06-09 14:51:50 -06004995 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndirect");
4996 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07004997 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
4998 drawCount, stride, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06004999
5000 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5001 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5002 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005003 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, "vkCmdDrawIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06005004 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005005}
5006
5007void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5008 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005009 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005010 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005011 auto *cb_access_context = GetAccessContext(commandBuffer);
5012 assert(cb_access_context);
5013 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5014 auto *context = cb_access_context->GetCurrentAccessContext();
5015 assert(context);
5016
locke-lunarg61870c22020-06-09 14:51:50 -06005017 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5018 cb_access_context->RecordDrawSubpassAttachment(tag);
5019 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005020
5021 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5022 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5023 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005024 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005025}
5026
5027bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5028 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005029 bool skip = false;
5030 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005031 const auto *cb_access_context = GetAccessContext(commandBuffer);
5032 assert(cb_access_context);
5033 if (!cb_access_context) return skip;
5034
5035 const auto *context = cb_access_context->GetCurrentAccessContext();
5036 assert(context);
5037 if (!context) return skip;
5038
locke-lunarg61870c22020-06-09 14:51:50 -06005039 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, "vkCmdDrawIndexedIndirect");
5040 skip |= cb_access_context->ValidateDrawSubpassAttachment("vkCmdDrawIndexedIndirect");
John Zulauffaea0ee2021-01-14 14:01:32 -07005041 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
5042 offset, drawCount, stride, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06005043
5044 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5045 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5046 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005047 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, "vkCmdDrawIndexedIndirect");
locke-lunargff255f92020-05-13 18:53:52 -06005048 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005049}
5050
5051void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5052 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005053 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005054 auto *cb_access_context = GetAccessContext(commandBuffer);
5055 assert(cb_access_context);
5056 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5057 auto *context = cb_access_context->GetCurrentAccessContext();
5058 assert(context);
5059
locke-lunarg61870c22020-06-09 14:51:50 -06005060 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5061 cb_access_context->RecordDrawSubpassAttachment(tag);
5062 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005063
5064 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5065 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5066 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005067 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005068}
5069
5070bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5071 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5072 uint32_t stride, const char *function) const {
5073 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005074 const auto *cb_access_context = GetAccessContext(commandBuffer);
5075 assert(cb_access_context);
5076 if (!cb_access_context) return skip;
5077
5078 const auto *context = cb_access_context->GetCurrentAccessContext();
5079 assert(context);
5080 if (!context) return skip;
5081
locke-lunarg61870c22020-06-09 14:51:50 -06005082 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
5083 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07005084 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
5085 maxDrawCount, stride, function);
5086 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06005087
5088 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5089 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5090 // We will validate the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005091 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06005092 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005093}
5094
5095bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5096 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5097 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005098 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5099 "vkCmdDrawIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06005100}
5101
sfricke-samsung85584a72021-09-30 21:43:38 -07005102void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5103 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5104 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005105 auto *cb_access_context = GetAccessContext(commandBuffer);
5106 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005107 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005108 auto *context = cb_access_context->GetCurrentAccessContext();
5109 assert(context);
5110
locke-lunarg61870c22020-06-09 14:51:50 -06005111 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5112 cb_access_context->RecordDrawSubpassAttachment(tag);
5113 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5114 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005115
5116 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5117 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5118 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005119 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005120}
5121
sfricke-samsung85584a72021-09-30 21:43:38 -07005122void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5123 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5124 uint32_t stride) {
5125 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5126 stride);
5127 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5128 CMD_DRAWINDIRECTCOUNT);
5129}
locke-lunarge1a67022020-04-29 00:15:36 -06005130bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5131 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5132 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005133 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5134 "vkCmdDrawIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06005135}
5136
5137void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5138 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5139 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005140 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5141 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005142 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5143 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005144}
5145
5146bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5147 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5148 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005149 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5150 "vkCmdDrawIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06005151}
5152
5153void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5154 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5155 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005156 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5157 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005158 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5159 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005160}
5161
5162bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5163 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5164 uint32_t stride, const char *function) const {
5165 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005166 const auto *cb_access_context = GetAccessContext(commandBuffer);
5167 assert(cb_access_context);
5168 if (!cb_access_context) return skip;
5169
5170 const auto *context = cb_access_context->GetCurrentAccessContext();
5171 assert(context);
5172 if (!context) return skip;
5173
locke-lunarg61870c22020-06-09 14:51:50 -06005174 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, function);
5175 skip |= cb_access_context->ValidateDrawSubpassAttachment(function);
John Zulauffaea0ee2021-01-14 14:01:32 -07005176 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
5177 offset, maxDrawCount, stride, function);
5178 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, function);
locke-lunargff255f92020-05-13 18:53:52 -06005179
5180 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5181 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5182 // We will validate the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005183 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, function);
locke-lunargff255f92020-05-13 18:53:52 -06005184 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005185}
5186
5187bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5188 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5189 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005190 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5191 "vkCmdDrawIndexedIndirectCount");
locke-lunarge1a67022020-04-29 00:15:36 -06005192}
5193
sfricke-samsung85584a72021-09-30 21:43:38 -07005194void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5195 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5196 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005197 auto *cb_access_context = GetAccessContext(commandBuffer);
5198 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005199 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005200 auto *context = cb_access_context->GetCurrentAccessContext();
5201 assert(context);
5202
locke-lunarg61870c22020-06-09 14:51:50 -06005203 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5204 cb_access_context->RecordDrawSubpassAttachment(tag);
5205 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5206 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005207
5208 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5209 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005210 // We will update the index and vertex buffer in SubmitQueue in the future.
5211 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005212}
5213
sfricke-samsung85584a72021-09-30 21:43:38 -07005214void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5215 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5216 uint32_t maxDrawCount, uint32_t stride) {
5217 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5218 maxDrawCount, stride);
5219 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5220 CMD_DRAWINDEXEDINDIRECTCOUNT);
5221}
5222
locke-lunarge1a67022020-04-29 00:15:36 -06005223bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5224 VkDeviceSize offset, VkBuffer countBuffer,
5225 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5226 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005227 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5228 "vkCmdDrawIndexedIndirectCountKHR");
locke-lunarge1a67022020-04-29 00:15:36 -06005229}
5230
5231void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5232 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5233 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005234 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5235 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005236 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5237 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005238}
5239
5240bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5241 VkDeviceSize offset, VkBuffer countBuffer,
5242 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5243 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005244 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5245 "vkCmdDrawIndexedIndirectCountAMD");
locke-lunarge1a67022020-04-29 00:15:36 -06005246}
5247
5248void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5249 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5250 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005251 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5252 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005253 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5254 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005255}
5256
5257bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5258 const VkClearColorValue *pColor, uint32_t rangeCount,
5259 const VkImageSubresourceRange *pRanges) const {
5260 bool skip = false;
5261 const auto *cb_access_context = GetAccessContext(commandBuffer);
5262 assert(cb_access_context);
5263 if (!cb_access_context) return skip;
5264
5265 const auto *context = cb_access_context->GetCurrentAccessContext();
5266 assert(context);
5267 if (!context) return skip;
5268
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005269 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005270
5271 for (uint32_t index = 0; index < rangeCount; index++) {
5272 const auto &range = pRanges[index];
5273 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005274 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005275 if (hazard.hazard) {
5276 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005277 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005278 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005279 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005280 }
5281 }
5282 }
5283 return skip;
5284}
5285
5286void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5287 const VkClearColorValue *pColor, uint32_t rangeCount,
5288 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005289 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005290 auto *cb_access_context = GetAccessContext(commandBuffer);
5291 assert(cb_access_context);
5292 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5293 auto *context = cb_access_context->GetCurrentAccessContext();
5294 assert(context);
5295
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005296 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005297
5298 for (uint32_t index = 0; index < rangeCount; index++) {
5299 const auto &range = pRanges[index];
5300 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005301 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005302 }
5303 }
5304}
5305
5306bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5307 VkImageLayout imageLayout,
5308 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5309 const VkImageSubresourceRange *pRanges) const {
5310 bool skip = false;
5311 const auto *cb_access_context = GetAccessContext(commandBuffer);
5312 assert(cb_access_context);
5313 if (!cb_access_context) return skip;
5314
5315 const auto *context = cb_access_context->GetCurrentAccessContext();
5316 assert(context);
5317 if (!context) return skip;
5318
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005319 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005320
5321 for (uint32_t index = 0; index < rangeCount; index++) {
5322 const auto &range = pRanges[index];
5323 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005324 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005325 if (hazard.hazard) {
5326 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005327 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005328 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005329 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005330 }
5331 }
5332 }
5333 return skip;
5334}
5335
5336void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5337 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5338 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005339 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005340 auto *cb_access_context = GetAccessContext(commandBuffer);
5341 assert(cb_access_context);
5342 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5343 auto *context = cb_access_context->GetCurrentAccessContext();
5344 assert(context);
5345
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005346 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005347
5348 for (uint32_t index = 0; index < rangeCount; index++) {
5349 const auto &range = pRanges[index];
5350 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005351 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005352 }
5353 }
5354}
5355
5356bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5357 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5358 VkDeviceSize dstOffset, VkDeviceSize stride,
5359 VkQueryResultFlags flags) const {
5360 bool skip = false;
5361 const auto *cb_access_context = GetAccessContext(commandBuffer);
5362 assert(cb_access_context);
5363 if (!cb_access_context) return skip;
5364
5365 const auto *context = cb_access_context->GetCurrentAccessContext();
5366 assert(context);
5367 if (!context) return skip;
5368
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005369 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005370
5371 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005372 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005373 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005374 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005375 skip |=
5376 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5377 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005378 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005379 }
5380 }
locke-lunargff255f92020-05-13 18:53:52 -06005381
5382 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005383 return skip;
5384}
5385
5386void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5387 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5388 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005389 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5390 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005391 auto *cb_access_context = GetAccessContext(commandBuffer);
5392 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005393 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005394 auto *context = cb_access_context->GetCurrentAccessContext();
5395 assert(context);
5396
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005397 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005398
5399 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005400 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005401 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005402 }
locke-lunargff255f92020-05-13 18:53:52 -06005403
5404 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005405}
5406
5407bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5408 VkDeviceSize size, uint32_t data) const {
5409 bool skip = false;
5410 const auto *cb_access_context = GetAccessContext(commandBuffer);
5411 assert(cb_access_context);
5412 if (!cb_access_context) return skip;
5413
5414 const auto *context = cb_access_context->GetCurrentAccessContext();
5415 assert(context);
5416 if (!context) return skip;
5417
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005418 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005419
5420 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005421 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005422 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005423 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005424 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005425 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005426 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005427 }
5428 }
5429 return skip;
5430}
5431
5432void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5433 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005434 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005435 auto *cb_access_context = GetAccessContext(commandBuffer);
5436 assert(cb_access_context);
5437 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5438 auto *context = cb_access_context->GetCurrentAccessContext();
5439 assert(context);
5440
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005441 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005442
5443 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005444 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005445 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005446 }
5447}
5448
5449bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5450 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5451 const VkImageResolve *pRegions) const {
5452 bool skip = false;
5453 const auto *cb_access_context = GetAccessContext(commandBuffer);
5454 assert(cb_access_context);
5455 if (!cb_access_context) return skip;
5456
5457 const auto *context = cb_access_context->GetCurrentAccessContext();
5458 assert(context);
5459 if (!context) return skip;
5460
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005461 auto src_image = Get<IMAGE_STATE>(srcImage);
5462 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005463
5464 for (uint32_t region = 0; region < regionCount; region++) {
5465 const auto &resolve_region = pRegions[region];
5466 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005467 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005468 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005469 if (hazard.hazard) {
5470 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005471 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005472 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005473 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005474 }
5475 }
5476
5477 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005478 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005479 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005480 if (hazard.hazard) {
5481 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005482 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005483 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005484 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005485 }
5486 if (skip) break;
5487 }
5488 }
5489
5490 return skip;
5491}
5492
5493void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5494 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5495 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005496 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5497 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005498 auto *cb_access_context = GetAccessContext(commandBuffer);
5499 assert(cb_access_context);
5500 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5501 auto *context = cb_access_context->GetCurrentAccessContext();
5502 assert(context);
5503
Jeremy Gebben9f537102021-10-05 16:37:12 -06005504 auto src_image = Get<IMAGE_STATE>(srcImage);
5505 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005506
5507 for (uint32_t region = 0; region < regionCount; region++) {
5508 const auto &resolve_region = pRegions[region];
5509 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005510 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005511 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005512 }
5513 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005514 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005515 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005516 }
5517 }
5518}
5519
Tony-LunarG562fc102021-11-12 13:58:35 -07005520bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5521 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005522 bool skip = false;
5523 const auto *cb_access_context = GetAccessContext(commandBuffer);
5524 assert(cb_access_context);
5525 if (!cb_access_context) return skip;
5526
5527 const auto *context = cb_access_context->GetCurrentAccessContext();
5528 assert(context);
5529 if (!context) return skip;
5530
Tony-LunarG562fc102021-11-12 13:58:35 -07005531 const char *func_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005532 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5533 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005534
5535 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5536 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5537 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005538 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005539 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005540 if (hazard.hazard) {
5541 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
Tony-LunarG562fc102021-11-12 13:58:35 -07005542 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04005543 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005544 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005545 }
5546 }
5547
5548 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005549 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005550 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005551 if (hazard.hazard) {
5552 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
Tony-LunarG562fc102021-11-12 13:58:35 -07005553 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", func_name,
Jeff Leger178b1e52020-10-05 12:22:23 -04005554 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005555 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005556 }
5557 if (skip) break;
5558 }
5559 }
5560
5561 return skip;
5562}
5563
Tony-LunarG562fc102021-11-12 13:58:35 -07005564bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5565 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5566 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5567}
5568
5569bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5570 const VkResolveImageInfo2 *pResolveImageInfo) const {
5571 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5572}
5573
5574void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5575 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005576 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5577 auto *cb_access_context = GetAccessContext(commandBuffer);
5578 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005579 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005580 auto *context = cb_access_context->GetCurrentAccessContext();
5581 assert(context);
5582
Jeremy Gebben9f537102021-10-05 16:37:12 -06005583 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5584 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005585
5586 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5587 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5588 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005589 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005590 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005591 }
5592 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005593 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005594 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005595 }
5596 }
5597}
5598
Tony-LunarG562fc102021-11-12 13:58:35 -07005599void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5600 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5601 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5602}
5603
5604void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5605 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5606}
5607
locke-lunarge1a67022020-04-29 00:15:36 -06005608bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5609 VkDeviceSize dataSize, const void *pData) const {
5610 bool skip = false;
5611 const auto *cb_access_context = GetAccessContext(commandBuffer);
5612 assert(cb_access_context);
5613 if (!cb_access_context) return skip;
5614
5615 const auto *context = cb_access_context->GetCurrentAccessContext();
5616 assert(context);
5617 if (!context) return skip;
5618
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005619 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005620
5621 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005622 // VK_WHOLE_SIZE not allowed
5623 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005624 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005625 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005626 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005627 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005628 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005629 }
5630 }
5631 return skip;
5632}
5633
5634void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5635 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005636 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005637 auto *cb_access_context = GetAccessContext(commandBuffer);
5638 assert(cb_access_context);
5639 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5640 auto *context = cb_access_context->GetCurrentAccessContext();
5641 assert(context);
5642
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005643 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005644
5645 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005646 // VK_WHOLE_SIZE not allowed
5647 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005648 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005649 }
5650}
locke-lunargff255f92020-05-13 18:53:52 -06005651
5652bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5653 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5654 bool skip = false;
5655 const auto *cb_access_context = GetAccessContext(commandBuffer);
5656 assert(cb_access_context);
5657 if (!cb_access_context) return skip;
5658
5659 const auto *context = cb_access_context->GetCurrentAccessContext();
5660 assert(context);
5661 if (!context) return skip;
5662
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005663 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005664
5665 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005666 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005667 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005668 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005669 skip |=
5670 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5671 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005672 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005673 }
5674 }
5675 return skip;
5676}
5677
5678void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5679 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005680 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005681 auto *cb_access_context = GetAccessContext(commandBuffer);
5682 assert(cb_access_context);
5683 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5684 auto *context = cb_access_context->GetCurrentAccessContext();
5685 assert(context);
5686
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005687 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005688
5689 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005690 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005691 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005692 }
5693}
John Zulauf49beb112020-11-04 16:06:31 -07005694
5695bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5696 bool skip = false;
5697 const auto *cb_context = GetAccessContext(commandBuffer);
5698 assert(cb_context);
5699 if (!cb_context) return skip;
5700
John Zulauf36ef9282021-02-02 11:47:24 -07005701 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005702 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005703}
5704
5705void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5706 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5707 auto *cb_context = GetAccessContext(commandBuffer);
5708 assert(cb_context);
5709 if (!cb_context) return;
John Zulauf1bf30522021-09-03 15:39:06 -06005710 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005711}
5712
John Zulauf4edde622021-02-15 08:54:50 -07005713bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5714 const VkDependencyInfoKHR *pDependencyInfo) const {
5715 bool skip = false;
5716 const auto *cb_context = GetAccessContext(commandBuffer);
5717 assert(cb_context);
5718 if (!cb_context || !pDependencyInfo) return skip;
5719
5720 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5721 return set_event_op.Validate(*cb_context);
5722}
5723
Tony-LunarGc43525f2021-11-15 16:12:38 -07005724bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5725 const VkDependencyInfo *pDependencyInfo) const {
5726 bool skip = false;
5727 const auto *cb_context = GetAccessContext(commandBuffer);
5728 assert(cb_context);
5729 if (!cb_context || !pDependencyInfo) return skip;
5730
5731 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5732 return set_event_op.Validate(*cb_context);
5733}
5734
John Zulauf4edde622021-02-15 08:54:50 -07005735void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5736 const VkDependencyInfoKHR *pDependencyInfo) {
5737 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5738 auto *cb_context = GetAccessContext(commandBuffer);
5739 assert(cb_context);
5740 if (!cb_context || !pDependencyInfo) return;
5741
John Zulauf1bf30522021-09-03 15:39:06 -06005742 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
John Zulauf4edde622021-02-15 08:54:50 -07005743}
5744
Tony-LunarGc43525f2021-11-15 16:12:38 -07005745void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5746 const VkDependencyInfo *pDependencyInfo) {
5747 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5748 auto *cb_context = GetAccessContext(commandBuffer);
5749 assert(cb_context);
5750 if (!cb_context || !pDependencyInfo) return;
5751
5752 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo);
5753}
5754
John Zulauf49beb112020-11-04 16:06:31 -07005755bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5756 VkPipelineStageFlags stageMask) const {
5757 bool skip = false;
5758 const auto *cb_context = GetAccessContext(commandBuffer);
5759 assert(cb_context);
5760 if (!cb_context) return skip;
5761
John Zulauf36ef9282021-02-02 11:47:24 -07005762 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005763 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005764}
5765
5766void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5767 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5768 auto *cb_context = GetAccessContext(commandBuffer);
5769 assert(cb_context);
5770 if (!cb_context) return;
5771
John Zulauf1bf30522021-09-03 15:39:06 -06005772 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005773}
5774
John Zulauf4edde622021-02-15 08:54:50 -07005775bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5776 VkPipelineStageFlags2KHR stageMask) const {
5777 bool skip = false;
5778 const auto *cb_context = GetAccessContext(commandBuffer);
5779 assert(cb_context);
5780 if (!cb_context) return skip;
5781
5782 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5783 return reset_event_op.Validate(*cb_context);
5784}
5785
Tony-LunarGa2662db2021-11-16 07:26:24 -07005786bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5787 VkPipelineStageFlags2 stageMask) const {
5788 bool skip = false;
5789 const auto *cb_context = GetAccessContext(commandBuffer);
5790 assert(cb_context);
5791 if (!cb_context) return skip;
5792
5793 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5794 return reset_event_op.Validate(*cb_context);
5795}
5796
John Zulauf4edde622021-02-15 08:54:50 -07005797void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5798 VkPipelineStageFlags2KHR stageMask) {
5799 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5800 auto *cb_context = GetAccessContext(commandBuffer);
5801 assert(cb_context);
5802 if (!cb_context) return;
5803
John Zulauf1bf30522021-09-03 15:39:06 -06005804 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005805}
5806
Tony-LunarGa2662db2021-11-16 07:26:24 -07005807void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5808 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5809 auto *cb_context = GetAccessContext(commandBuffer);
5810 assert(cb_context);
5811 if (!cb_context) return;
5812
5813 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5814}
5815
John Zulauf49beb112020-11-04 16:06:31 -07005816bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5817 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5818 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5819 uint32_t bufferMemoryBarrierCount,
5820 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5821 uint32_t imageMemoryBarrierCount,
5822 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5823 bool skip = false;
5824 const auto *cb_context = GetAccessContext(commandBuffer);
5825 assert(cb_context);
5826 if (!cb_context) return skip;
5827
John Zulauf36ef9282021-02-02 11:47:24 -07005828 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5829 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5830 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005831 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005832}
5833
5834void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5835 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5836 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5837 uint32_t bufferMemoryBarrierCount,
5838 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5839 uint32_t imageMemoryBarrierCount,
5840 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5841 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5842 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5843 imageMemoryBarrierCount, pImageMemoryBarriers);
5844
5845 auto *cb_context = GetAccessContext(commandBuffer);
5846 assert(cb_context);
5847 if (!cb_context) return;
5848
John Zulauf1bf30522021-09-03 15:39:06 -06005849 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06005850 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06005851 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07005852}
5853
John Zulauf4edde622021-02-15 08:54:50 -07005854bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5855 const VkDependencyInfoKHR *pDependencyInfos) const {
5856 bool skip = false;
5857 const auto *cb_context = GetAccessContext(commandBuffer);
5858 assert(cb_context);
5859 if (!cb_context) return skip;
5860
5861 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5862 skip |= wait_events_op.Validate(*cb_context);
5863 return skip;
5864}
5865
5866void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5867 const VkDependencyInfoKHR *pDependencyInfos) {
5868 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5869
5870 auto *cb_context = GetAccessContext(commandBuffer);
5871 assert(cb_context);
5872 if (!cb_context) return;
5873
John Zulauf1bf30522021-09-03 15:39:06 -06005874 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5875 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07005876}
5877
Tony-LunarG1364cf52021-11-17 16:10:11 -07005878bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5879 const VkDependencyInfo *pDependencyInfos) const {
5880 bool skip = false;
5881 const auto *cb_context = GetAccessContext(commandBuffer);
5882 assert(cb_context);
5883 if (!cb_context) return skip;
5884
5885 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5886 skip |= wait_events_op.Validate(*cb_context);
5887 return skip;
5888}
5889
5890void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5891 const VkDependencyInfo *pDependencyInfos) {
5892 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
5893
5894 auto *cb_context = GetAccessContext(commandBuffer);
5895 assert(cb_context);
5896 if (!cb_context) return;
5897
5898 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
5899 pDependencyInfos);
5900}
5901
John Zulauf4a6105a2020-11-17 15:11:05 -07005902void SyncEventState::ResetFirstScope() {
5903 for (const auto address_type : kAddressTypes) {
5904 first_scope[static_cast<size_t>(address_type)].clear();
5905 }
Jeremy Gebben9893daf2021-01-04 10:40:50 -07005906 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06005907 first_scope_set = false;
5908 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07005909}
5910
5911// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
John Zulauf4edde622021-02-15 08:54:50 -07005912SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005913 IgnoreReason reason = NotIgnored;
5914
Tony-LunarG1364cf52021-11-17 16:10:11 -07005915 if ((CMD_WAITEVENTS2KHR == cmd || CMD_WAITEVENTS2 == cmd) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07005916 reason = SetVsWait2;
5917 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
5918 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07005919 } else if (unsynchronized_set) {
5920 reason = SetRace;
John Zulauf78b1f892021-09-20 15:02:09 -06005921 } else if (first_scope_set) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005922 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulauf4a6105a2020-11-17 15:11:05 -07005923 if (missing_bits) reason = MissingStageBits;
5924 }
5925
5926 return reason;
5927}
5928
Jeremy Gebben40a22942020-12-22 14:22:06 -07005929bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07005930 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
5931 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
5932 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07005933}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005934
John Zulaufbb890452021-12-14 11:30:18 -07005935void SyncOpBase::SetReplayContext(uint32_t subpass, ReplayContextPtr &&replay) {
5936 subpass_ = subpass;
5937 replay_context_ = std::move(replay);
5938}
5939
5940const ReplayTrackbackBarriersAction *SyncOpBase::GetReplayTrackback() const {
5941 if (replay_context_) {
5942 assert(subpass_ < replay_context_->subpass_contexts.size());
5943 return &replay_context_->subpass_contexts[subpass_];
5944 }
5945 return nullptr;
5946}
5947
John Zulauf36ef9282021-02-02 11:47:24 -07005948SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
5949 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5950 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07005951 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5952 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5953 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf4edde622021-02-15 08:54:50 -07005954 : SyncOpBase(cmd), barriers_(1) {
5955 auto &barrier_set = barriers_[0];
5956 barrier_set.dependency_flags = dependencyFlags;
5957 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
5958 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005959 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07005960 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
5961 pMemoryBarriers);
5962 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5963 bufferMemoryBarrierCount, pBufferMemoryBarriers);
5964 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
5965 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07005966}
5967
John Zulauf4edde622021-02-15 08:54:50 -07005968SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
5969 const VkDependencyInfoKHR *dep_infos)
5970 : SyncOpBase(cmd), barriers_(event_count) {
5971 for (uint32_t i = 0; i < event_count; i++) {
5972 const auto &dep_info = dep_infos[i];
5973 auto &barrier_set = barriers_[i];
5974 barrier_set.dependency_flags = dep_info.dependencyFlags;
5975 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
5976 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
5977 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
5978 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
5979 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
5980 dep_info.pMemoryBarriers);
5981 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
5982 dep_info.pBufferMemoryBarriers);
5983 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
5984 dep_info.pImageMemoryBarriers);
5985 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005986}
5987
John Zulauf36ef9282021-02-02 11:47:24 -07005988SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07005989 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5990 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
5991 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
5992 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
5993 const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf36ef9282021-02-02 11:47:24 -07005994 : SyncOpBarriers(cmd, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
John Zulaufd5115702021-01-18 12:34:33 -07005995 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers) {}
5996
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07005997SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags,
5998 const VkDependencyInfoKHR &dep_info)
John Zulauf4edde622021-02-15 08:54:50 -07005999 : SyncOpBarriers(cmd, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006000
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006001bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6002 bool skip = false;
6003 const auto *context = cb_context.GetCurrentAccessContext();
6004 assert(context);
6005 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006006 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6007
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006008 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006009 const auto &barrier_set = barriers_[0];
6010 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6011 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6012 const auto *image_state = image_barrier.image.get();
6013 if (!image_state) continue;
6014 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6015 if (hazard.hazard) {
6016 // PHASE1 TODO -- add tag information to log msg when useful.
6017 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006018 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006019 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6020 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6021 string_SyncHazard(hazard.hazard), image_barrier.index,
6022 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006023 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006024 }
6025 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006026 return skip;
6027}
6028
John Zulaufd5115702021-01-18 12:34:33 -07006029struct SyncOpPipelineBarrierFunctorFactory {
6030 using BarrierOpFunctor = PipelineBarrierOp;
6031 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6032 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6033 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6034 using BufferRange = ResourceAccessRange;
6035 using ImageRange = subresource_adapter::ImageRangeGenerator;
6036 using GlobalRange = ResourceAccessRange;
6037
John Zulauf00119522022-05-23 19:07:42 -06006038 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6039 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006040 }
John Zulauf14940722021-04-12 15:19:02 -06006041 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006042 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6043 }
John Zulauf00119522022-05-23 19:07:42 -06006044 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6045 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006046 }
6047
6048 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6049 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6050 const auto base_address = ResourceBaseAddress(buffer);
6051 return (range + base_address);
6052 }
John Zulauf110413c2021-03-20 05:38:38 -06006053 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006054 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006055
6056 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006057 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006058 return range_gen;
6059 }
6060 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6061};
6062
6063template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006064void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6065 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006066 for (const auto &barrier : barriers) {
6067 const auto *state = barrier.GetState();
6068 if (state) {
6069 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006070 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006071 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6072 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6073 }
6074 }
6075}
6076
6077template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006078void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6079 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006080 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6081 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006082 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006083 }
6084 for (const auto address_type : kAddressTypes) {
6085 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6086 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6087 }
6088}
6089
John Zulauf8eda1562021-04-13 17:06:41 -06006090ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006091 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf8eda1562021-04-13 17:06:41 -06006092 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006093 const QueueId queue_id = cb_context->GetQueueId();
John Zulauf36ef9282021-02-02 11:47:24 -07006094 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf00119522022-05-23 19:07:42 -06006095 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006096 return tag;
6097}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006098
John Zulauf00119522022-05-23 19:07:42 -06006099void SyncOpPipelineBarrier::ReplayRecord(QueueId queue_id, const ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006100 SyncEventsContext *events_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006101 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006102 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6103 assert(barriers_.size() == 1);
6104 const auto &barrier_set = barriers_[0];
John Zulauf00119522022-05-23 19:07:42 -06006105 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6106 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6107 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006108 if (barrier_set.single_exec_scope) {
John Zulauf8eda1562021-04-13 17:06:41 -06006109 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006110 } else {
6111 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulauf8eda1562021-04-13 17:06:41 -06006112 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope);
John Zulauf4edde622021-02-15 08:54:50 -07006113 }
6114 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006115}
6116
John Zulauf8eda1562021-04-13 17:06:41 -06006117bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006118 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006119 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6120 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006121 return false;
6122}
6123
John Zulauf4edde622021-02-15 08:54:50 -07006124void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6125 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6126 const VkMemoryBarrier *barriers) {
6127 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006128 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006129 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006130 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006131 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006132 }
6133 if (0 == memory_barrier_count) {
6134 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006135 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006136 }
John Zulauf4edde622021-02-15 08:54:50 -07006137 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006138}
6139
John Zulauf4edde622021-02-15 08:54:50 -07006140void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6141 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6142 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6143 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006144 for (uint32_t index = 0; index < barrier_count; index++) {
6145 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006146 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006147 if (buffer) {
6148 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6149 const auto range = MakeRange(barrier.offset, barrier_size);
6150 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006151 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006152 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006153 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006154 }
6155 }
6156}
6157
John Zulauf4edde622021-02-15 08:54:50 -07006158void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006159 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006160 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006161 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006162 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006163 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6164 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6165 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006166 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006167 }
John Zulauf4edde622021-02-15 08:54:50 -07006168 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006169}
6170
John Zulauf4edde622021-02-15 08:54:50 -07006171void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6172 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006173 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006174 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006175 for (uint32_t index = 0; index < barrier_count; index++) {
6176 const auto &barrier = barriers[index];
6177 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6178 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006179 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006180 if (buffer) {
6181 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6182 const auto range = MakeRange(barrier.offset, barrier_size);
6183 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006184 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006185 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006186 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006187 }
6188 }
6189}
6190
John Zulauf4edde622021-02-15 08:54:50 -07006191void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6192 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6193 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6194 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006195 for (uint32_t index = 0; index < barrier_count; index++) {
6196 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006197 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006198 if (image) {
6199 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6200 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006201 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006202 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006203 image_memory_barriers.emplace_back();
6204 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006205 }
6206 }
6207}
John Zulaufd5115702021-01-18 12:34:33 -07006208
John Zulauf4edde622021-02-15 08:54:50 -07006209void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6210 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006211 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006212 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006213 for (uint32_t index = 0; index < barrier_count; index++) {
6214 const auto &barrier = barriers[index];
6215 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6216 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006217 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006218 if (image) {
6219 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6220 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006221 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006222 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006223 image_memory_barriers.emplace_back();
6224 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006225 }
6226 }
6227}
6228
John Zulauf36ef9282021-02-02 11:47:24 -07006229SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
John Zulaufd5115702021-01-18 12:34:33 -07006230 const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6231 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
6232 uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers,
6233 uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers)
John Zulauf36ef9282021-02-02 11:47:24 -07006234 : SyncOpBarriers(cmd, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006235 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6236 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006237 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006238}
6239
John Zulauf4edde622021-02-15 08:54:50 -07006240SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t eventCount,
6241 const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6242 : SyncOpBarriers(cmd, sync_state, queue_flags, eventCount, pDependencyInfo) {
6243 MakeEventsList(sync_state, eventCount, pEvents);
6244 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6245}
6246
John Zulauf610e28c2021-08-03 17:46:23 -06006247const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6248
John Zulaufd5115702021-01-18 12:34:33 -07006249bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006250 bool skip = false;
6251 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006252 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006253
John Zulauf610e28c2021-08-03 17:46:23 -06006254 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006255 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6256 const auto &barrier_set = barriers_[barrier_set_index];
6257 if (barrier_set.single_exec_scope) {
6258 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6259 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6260 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6261 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6262 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6263 } else {
6264 const auto &barriers = barrier_set.memory_barriers;
6265 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6266 const auto &barrier = barriers[barrier_index];
6267 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6268 const std::string vuid =
6269 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6270 skip =
6271 sync_state.LogInfo(command_buffer_handle, vuid,
6272 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6273 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6274 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6275 }
6276 }
6277 }
6278 }
John Zulaufd5115702021-01-18 12:34:33 -07006279 }
6280
John Zulauf610e28c2021-08-03 17:46:23 -06006281 // The rest is common to record time and replay time.
6282 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6283 return skip;
6284}
6285
John Zulaufbb890452021-12-14 11:30:18 -07006286bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006287 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006288 const auto &sync_state = exec_context.GetSyncState();
John Zulauf610e28c2021-08-03 17:46:23 -06006289
Jeremy Gebben40a22942020-12-22 14:22:06 -07006290 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006291 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006292 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006293 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006294 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006295 size_t barrier_set_index = 0;
6296 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006297 for (const auto &event : events_) {
6298 const auto *sync_event = events_context->Get(event.get());
6299 const auto &barrier_set = barriers_[barrier_set_index];
6300 if (!sync_event) {
6301 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6302 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6303 // new validation error... wait without previously submitted set event...
6304 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 -07006305 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006306 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006307 }
John Zulauf610e28c2021-08-03 17:46:23 -06006308
6309 // For replay calls, don't revalidate "same command buffer" events
6310 if (sync_event->last_command_tag > base_tag) continue;
6311
John Zulauf78394fc2021-07-12 15:41:40 -06006312 const auto event_handle = sync_event->event->event();
6313 // TODO add "destroyed" checks
6314
John Zulauf78b1f892021-09-20 15:02:09 -06006315 if (sync_event->first_scope_set) {
6316 // Only accumulate barrier and event stages if there is a pending set in the current context
6317 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6318 event_stage_masks |= sync_event->scope.mask_param;
6319 }
6320
John Zulauf78394fc2021-07-12 15:41:40 -06006321 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006322
John Zulauf78394fc2021-07-12 15:41:40 -06006323 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_, src_exec_scope.mask_param);
6324 if (ignore_reason) {
6325 switch (ignore_reason) {
6326 case SyncEventState::ResetWaitRace:
6327 case SyncEventState::Reset2WaitRace: {
6328 // Four permuations of Reset and Wait calls...
6329 const char *vuid =
6330 (cmd_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
6331 if (ignore_reason == SyncEventState::Reset2WaitRace) {
Tony-LunarG279601c2021-11-16 10:50:51 -07006332 vuid = (cmd_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6333 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006334 }
6335 const char *const message =
6336 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6337 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6338 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006339 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006340 break;
6341 }
6342 case SyncEventState::SetRace: {
6343 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6344 // this event
6345 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6346 const char *const message =
6347 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6348 const char *const reason = "First synchronization scope is undefined.";
6349 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6350 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006351 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006352 break;
6353 }
6354 case SyncEventState::MissingStageBits: {
6355 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6356 // Issue error message that event waited for is not in wait events scope
6357 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6358 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6359 ". Bits missing from srcStageMask %s. %s";
6360 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6361 sync_state.report_data->FormatHandle(event_handle).c_str(),
6362 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006363 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006364 break;
6365 }
6366 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006367 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006368 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6369 sync_state.report_data->FormatHandle(event_handle).c_str(),
6370 CommandTypeString(sync_event->last_command));
6371 break;
6372 }
6373 default:
6374 assert(ignore_reason == SyncEventState::NotIgnored);
6375 }
6376 } else if (barrier_set.image_memory_barriers.size()) {
6377 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006378 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006379 assert(context);
6380 for (const auto &image_memory_barrier : image_memory_barriers) {
6381 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6382 const auto *image_state = image_memory_barrier.image.get();
6383 if (!image_state) continue;
6384 const auto &subresource_range = image_memory_barrier.range;
6385 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
6386 const auto hazard =
6387 context->DetectImageBarrierHazard(*image_state, sync_event->scope.exec_scope, src_access_scope,
6388 subresource_range, *sync_event, AccessContext::DetectOptions::kDetectAll);
6389 if (hazard.hazard) {
6390 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6391 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6392 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6393 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006394 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006395 break;
6396 }
6397 }
6398 }
6399 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6400 // 03839
6401 barrier_set_index += barrier_set_incr;
6402 }
John Zulaufd5115702021-01-18 12:34:33 -07006403
6404 // 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 -07006405 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 -07006406 if (extra_stage_bits) {
6407 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006408 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6409 const char *const vuid =
Tony-LunarG279601c2021-11-16 10:50:51 -07006410 (CMD_WAITEVENTS == cmd_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006411 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006412 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006413 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006414 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006415 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006416 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006417 " vkCmdSetEvent may be in previously submitted command buffer.");
6418 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006419 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006420 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006421 }
6422 }
6423 return skip;
6424}
6425
6426struct SyncOpWaitEventsFunctorFactory {
6427 using BarrierOpFunctor = WaitEventBarrierOp;
6428 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6429 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6430 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6431 using BufferRange = EventSimpleRangeGenerator;
6432 using ImageRange = EventImageRangeGenerator;
6433 using GlobalRange = EventSimpleRangeGenerator;
6434
6435 // Need to restrict to only valid exec and access scope for this event
6436 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6437 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006438 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006439 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6440 return barrier;
6441 }
John Zulauf00119522022-05-23 19:07:42 -06006442 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006443 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006444 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006445 }
John Zulauf14940722021-04-12 15:19:02 -06006446 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006447 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6448 }
John Zulauf00119522022-05-23 19:07:42 -06006449 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006450 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006451 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006452 }
6453
6454 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6455 const AccessAddressType address_type = GetAccessAddressType(buffer);
6456 const auto base_address = ResourceBaseAddress(buffer);
6457 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6458 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6459 return filtered_range_gen;
6460 }
John Zulauf110413c2021-03-20 05:38:38 -06006461 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006462 if (!SimpleBinding(image)) return ImageRange();
6463 const auto address_type = GetAccessAddressType(image);
6464 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006465 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6466 false);
John Zulaufd5115702021-01-18 12:34:33 -07006467 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6468
6469 return filtered_range_gen;
6470 }
6471 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6472 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6473 }
6474 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6475 SyncEventState *sync_event;
6476};
6477
John Zulauf8eda1562021-04-13 17:06:41 -06006478ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf36ef9282021-02-02 11:47:24 -07006479 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulaufd5115702021-01-18 12:34:33 -07006480 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006481 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufd5115702021-01-18 12:34:33 -07006482 assert(access_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006483 if (!access_context) return tag;
John Zulauf669dfd52021-01-27 17:15:28 -07006484 auto *events_context = cb_context->GetCurrentEventsContext();
6485 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006486 if (!events_context) return tag;
John Zulaufd5115702021-01-18 12:34:33 -07006487
John Zulauf00119522022-05-23 19:07:42 -06006488 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006489 return tag;
6490}
6491
John Zulauf00119522022-05-23 19:07:42 -06006492void SyncOpWaitEvents::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6493 SyncEventsContext *events_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006494 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6495 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6496 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
6497 access_context->ResolvePreviousAccesses();
6498
John Zulauf4edde622021-02-15 08:54:50 -07006499 size_t barrier_set_index = 0;
6500 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6501 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006502 for (auto &event_shared : events_) {
6503 if (!event_shared.get()) continue;
6504 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006505
John Zulauf4edde622021-02-15 08:54:50 -07006506 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006507 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006508
John Zulauf4edde622021-02-15 08:54:50 -07006509 const auto &barrier_set = barriers_[barrier_set_index];
6510 const auto &dst = barrier_set.dst_exec_scope;
6511 if (!sync_event->IsIgnoredByWait(cmd_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006512 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6513 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6514 // of the barriers is maintained.
6515 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006516 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6517 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6518 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006519
6520 // Apply the global barrier to the event itself (for race condition tracking)
6521 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6522 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6523 sync_event->barriers |= dst.exec_scope;
6524 } else {
6525 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6526 sync_event->barriers = 0U;
6527 }
John Zulauf4edde622021-02-15 08:54:50 -07006528 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006529 }
6530
6531 // Apply the pending barriers
6532 ResolvePendingBarrierFunctor apply_pending_action(tag);
6533 access_context->ApplyToContext(apply_pending_action);
6534}
6535
John Zulauf8eda1562021-04-13 17:06:41 -06006536bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006537 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6538 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006539}
6540
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006541bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6542 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6543 bool skip = false;
6544 const auto *cb_access_context = GetAccessContext(commandBuffer);
6545 assert(cb_access_context);
6546 if (!cb_access_context) return skip;
6547
6548 const auto *context = cb_access_context->GetCurrentAccessContext();
6549 assert(context);
6550 if (!context) return skip;
6551
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006552 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006553
6554 if (dst_buffer) {
6555 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6556 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6557 if (hazard.hazard) {
6558 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6559 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6560 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006561 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006562 }
6563 }
6564 return skip;
6565}
6566
John Zulauf669dfd52021-01-27 17:15:28 -07006567void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006568 events_.reserve(event_count);
6569 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006570 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006571 }
6572}
John Zulauf6ce24372021-01-30 05:56:25 -07006573
John Zulauf36ef9282021-02-02 11:47:24 -07006574SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006575 VkPipelineStageFlags2KHR stageMask)
Jeremy Gebben9f537102021-10-05 16:37:12 -06006576 : SyncOpBase(cmd), event_(sync_state.Get<EVENT_STATE>(event)), exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006577
John Zulauf1bf30522021-09-03 15:39:06 -06006578bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6579 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6580}
6581
John Zulaufbb890452021-12-14 11:30:18 -07006582bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6583 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006584 assert(events_context);
6585 bool skip = false;
6586 if (!events_context) return skip;
6587
John Zulaufbb890452021-12-14 11:30:18 -07006588 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006589 const auto *sync_event = events_context->Get(event_);
6590 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6591
John Zulauf1bf30522021-09-03 15:39:06 -06006592 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6593
John Zulauf6ce24372021-01-30 05:56:25 -07006594 const char *const set_wait =
6595 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6596 "hazards.";
6597 const char *message = set_wait; // Only one message this call.
6598 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6599 const char *vuid = nullptr;
6600 switch (sync_event->last_command) {
6601 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006602 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006603 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006604 // Needs a barrier between set and reset
6605 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6606 break;
John Zulauf4edde622021-02-15 08:54:50 -07006607 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006608 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006609 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006610 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6611 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6612 break;
6613 }
6614 default:
6615 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006616 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6617 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006618 break;
6619 }
6620 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006621 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6622 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006623 CommandTypeString(sync_event->last_command));
6624 }
6625 }
6626 return skip;
6627}
6628
John Zulauf8eda1562021-04-13 17:06:41 -06006629ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) const {
6630 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf6ce24372021-01-30 05:56:25 -07006631 auto *events_context = cb_context->GetCurrentEventsContext();
6632 assert(events_context);
John Zulauf8eda1562021-04-13 17:06:41 -06006633 if (!events_context) return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006634
6635 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf8eda1562021-04-13 17:06:41 -06006636 if (!sync_event) return tag; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006637
6638 // Update the event state
John Zulauf36ef9282021-02-02 11:47:24 -07006639 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006640 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006641 sync_event->unsynchronized_set = CMD_NONE;
6642 sync_event->ResetFirstScope();
6643 sync_event->barriers = 0U;
John Zulauf8eda1562021-04-13 17:06:41 -06006644
6645 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006646}
6647
John Zulauf8eda1562021-04-13 17:06:41 -06006648bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006649 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6650 return DoValidate(*exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006651}
6652
John Zulauf00119522022-05-23 19:07:42 -06006653void SyncOpResetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6654 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006655
John Zulauf36ef9282021-02-02 11:47:24 -07006656SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006657 VkPipelineStageFlags2KHR stageMask)
John Zulauf36ef9282021-02-02 11:47:24 -07006658 : 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, stageMask)),
6661 dep_info_() {}
6662
6663SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
6664 const VkDependencyInfoKHR &dep_info)
6665 : SyncOpBase(cmd),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006666 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulauf4edde622021-02-15 08:54:50 -07006667 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
Tony-LunarG273f32f2021-09-28 08:56:30 -06006668 dep_info_(new safe_VkDependencyInfo(&dep_info)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006669
6670bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006671 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6672}
6673bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006674 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
6675 assert(exec_context);
6676 return DoValidate(*exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006677}
6678
John Zulaufbb890452021-12-14 11:30:18 -07006679bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006680 bool skip = false;
6681
John Zulaufbb890452021-12-14 11:30:18 -07006682 const auto &sync_state = exec_context.GetSyncState();
6683 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006684 assert(events_context);
6685 if (!events_context) return skip;
6686
6687 const auto *sync_event = events_context->Get(event_);
6688 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6689
John Zulauf610e28c2021-08-03 17:46:23 -06006690 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6691
John Zulauf6ce24372021-01-30 05:56:25 -07006692 const char *const reset_set =
6693 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6694 "hazards.";
6695 const char *const wait =
6696 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6697
6698 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006699 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006700 const char *message = nullptr;
6701 switch (sync_event->last_command) {
6702 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006703 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006704 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006705 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006706 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006707 message = reset_set;
6708 break;
6709 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006710 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006711 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006712 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006713 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006714 message = reset_set;
6715 break;
6716 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006717 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006718 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006719 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006720 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006721 message = wait;
6722 break;
6723 default:
6724 // The only other valid last command that wasn't one.
6725 assert(sync_event->last_command == CMD_NONE);
6726 break;
6727 }
John Zulauf4edde622021-02-15 08:54:50 -07006728 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006729 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006730 std::string vuid("SYNC-");
6731 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006732 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6733 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006734 CommandTypeString(sync_event->last_command));
6735 }
6736 }
6737
6738 return skip;
6739}
6740
John Zulauf8eda1562021-04-13 17:06:41 -06006741ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf36ef9282021-02-02 11:47:24 -07006742 const auto tag = cb_context->NextCommandTag(cmd_);
John Zulauf6ce24372021-01-30 05:56:25 -07006743 auto *events_context = cb_context->GetCurrentEventsContext();
6744 auto *access_context = cb_context->GetCurrentAccessContext();
John Zulauf00119522022-05-23 19:07:42 -06006745 const QueueId queue_id = cb_context->GetQueueId();
John Zulauf6ce24372021-01-30 05:56:25 -07006746 assert(events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006747 if (access_context && events_context) {
John Zulauf00119522022-05-23 19:07:42 -06006748 ReplayRecord(queue_id, tag, access_context, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006749 }
6750 return tag;
6751}
John Zulauf6ce24372021-01-30 05:56:25 -07006752
John Zulauf00119522022-05-23 19:07:42 -06006753void SyncOpSetEvent::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6754 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006755 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006756 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006757
6758 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6759 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6760 // any issues caused by naive scope setting here.
6761
6762 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6763 // Given:
6764 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6765 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6766
6767 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6768 sync_event->unsynchronized_set = sync_event->last_command;
6769 sync_event->ResetFirstScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006770 } else if (!sync_event->first_scope_set) {
John Zulauf6ce24372021-01-30 05:56:25 -07006771 // We only set the scope if there isn't one
6772 sync_event->scope = src_exec_scope_;
6773
6774 auto set_scope = [&sync_event](AccessAddressType address_type, const ResourceAccessRangeMap::value_type &access) {
6775 auto &scope_map = sync_event->first_scope[static_cast<size_t>(address_type)];
6776 if (access.second.InSourceScopeOrChain(sync_event->scope.exec_scope, sync_event->scope.valid_accesses)) {
6777 scope_map.insert(scope_map.end(), std::make_pair(access.first, true));
6778 }
6779 };
6780 access_context->ForAll(set_scope);
6781 sync_event->unsynchronized_set = CMD_NONE;
John Zulauf78b1f892021-09-20 15:02:09 -06006782 sync_event->first_scope_set = true;
John Zulauf6ce24372021-01-30 05:56:25 -07006783 sync_event->first_scope_tag = tag;
6784 }
John Zulauf4edde622021-02-15 08:54:50 -07006785 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
6786 sync_event->last_command = cmd_;
John Zulauf610e28c2021-08-03 17:46:23 -06006787 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006788 sync_event->barriers = 0U;
6789}
John Zulauf64ffe552021-02-06 10:25:07 -07006790
6791SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd, const SyncValidator &sync_state,
6792 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006793 const VkSubpassBeginInfo *pSubpassBeginInfo)
6794 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006795 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006796 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006797 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006798 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006799 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006800 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006801 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6802 // Note that this a safe to presist as long as shared_attachments is not cleared
6803 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006804 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006805 attachments_.emplace_back(attachment.get());
6806 }
6807 }
6808 if (pSubpassBeginInfo) {
6809 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6810 }
6811 }
6812}
6813
6814bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6815 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6816 bool skip = false;
6817
6818 assert(rp_state_.get());
6819 if (nullptr == rp_state_.get()) return skip;
6820 auto &rp_state = *rp_state_.get();
6821
6822 const uint32_t subpass = 0;
6823
6824 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
6825 // hasn't happened yet)
6826 const std::vector<AccessContext> empty_context_vector;
6827 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
6828 cb_context.GetCurrentAccessContext());
6829
6830 // Validate attachment operations
6831 if (attachments_.size() == 0) return skip;
6832 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07006833
6834 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
6835 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
6836 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
6837 // operations (though it's currently a messy approach)
6838 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
6839 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, CmdName());
John Zulauf64ffe552021-02-06 10:25:07 -07006840
6841 // Validate load operations if there were no layout transition hazards
6842 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06006843 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07006844 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, CmdName());
John Zulauf64ffe552021-02-06 10:25:07 -07006845 }
6846
6847 return skip;
6848}
6849
John Zulauf8eda1562021-04-13 17:06:41 -06006850ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf64ffe552021-02-06 10:25:07 -07006851 // TODO PHASE2 need to have a consistent way to record to either command buffer or queue contexts
6852 assert(rp_state_.get());
John Zulauf41a9c7c2021-12-07 15:59:53 -07006853 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_);
6854 return cb_context->RecordBeginRenderPass(cmd_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
John Zulauf64ffe552021-02-06 10:25:07 -07006855}
6856
John Zulauf8eda1562021-04-13 17:06:41 -06006857bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006858 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006859 return false;
6860}
6861
John Zulauf00119522022-05-23 19:07:42 -06006862void SyncOpBeginRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006863 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006864
John Zulauf64ffe552021-02-06 10:25:07 -07006865SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd, const SyncValidator &sync_state, const VkSubpassBeginInfo *pSubpassBeginInfo,
sfricke-samsung85584a72021-09-30 21:43:38 -07006866 const VkSubpassEndInfo *pSubpassEndInfo)
6867 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006868 if (pSubpassBeginInfo) {
6869 subpass_begin_info_.initialize(pSubpassBeginInfo);
6870 }
6871 if (pSubpassEndInfo) {
6872 subpass_end_info_.initialize(pSubpassEndInfo);
6873 }
6874}
6875
6876bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
6877 bool skip = false;
6878 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6879 if (!renderpass_context) return skip;
6880
6881 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), CmdName());
6882 return skip;
6883}
6884
John Zulauf8eda1562021-04-13 17:06:41 -06006885ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006886 return cb_context->RecordNextSubpass(cmd_);
John Zulauf8eda1562021-04-13 17:06:41 -06006887}
6888
6889bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006890 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006891 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07006892}
6893
sfricke-samsung85584a72021-09-30 21:43:38 -07006894SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd, const SyncValidator &sync_state, const VkSubpassEndInfo *pSubpassEndInfo)
6895 : SyncOpBase(cmd) {
John Zulauf64ffe552021-02-06 10:25:07 -07006896 if (pSubpassEndInfo) {
6897 subpass_end_info_.initialize(pSubpassEndInfo);
6898 }
6899}
6900
John Zulauf00119522022-05-23 19:07:42 -06006901void SyncOpNextSubpass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
6902 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006903
John Zulauf64ffe552021-02-06 10:25:07 -07006904bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6905 bool skip = false;
6906 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
6907
6908 if (!renderpass_context) return skip;
6909 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), CmdName());
6910 return skip;
6911}
6912
John Zulauf8eda1562021-04-13 17:06:41 -06006913ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006914 return cb_context->RecordEndRenderPass(cmd_);
John Zulauf64ffe552021-02-06 10:25:07 -07006915}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006916
John Zulauf8eda1562021-04-13 17:06:41 -06006917bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulaufbb890452021-12-14 11:30:18 -07006918 ResourceUsageTag base_tag, CommandExecutionContext *exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006919 return false;
6920}
6921
John Zulauf00119522022-05-23 19:07:42 -06006922void SyncOpEndRenderPass::ReplayRecord(QueueId queue_id, ResourceUsageTag tag, AccessContext *access_context,
John Zulaufbb890452021-12-14 11:30:18 -07006923 SyncEventsContext *events_context) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06006924
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006925void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6926 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
6927 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
6928 auto *cb_access_context = GetAccessContext(commandBuffer);
6929 assert(cb_access_context);
6930 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
6931 auto *context = cb_access_context->GetCurrentAccessContext();
6932 assert(context);
6933
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006934 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006935
6936 if (dst_buffer) {
6937 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6938 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
6939 }
6940}
John Zulaufd05c5842021-03-26 11:32:16 -06006941
John Zulaufae842002021-04-15 18:20:55 -06006942bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6943 const VkCommandBuffer *pCommandBuffers) const {
6944 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
6945 const char *func_name = "vkCmdExecuteCommands";
6946 const auto *cb_context = GetAccessContext(commandBuffer);
6947 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006948
6949 // Heavyweight, but we need a proxy copy of the active command buffer access context
6950 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06006951
6952 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06006953 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006954 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
6955
John Zulaufae842002021-04-15 18:20:55 -06006956 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6957 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06006958
6959 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
6960 assert(recorded_context);
6961 skip |= recorded_cb_context->ValidateFirstUse(&proxy_cb_context, func_name, cb_index);
6962
6963 // The barriers have already been applied in ValidatFirstUse
6964 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06006965 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06006966 }
6967
John Zulaufae842002021-04-15 18:20:55 -06006968 return skip;
6969}
6970
6971void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
6972 const VkCommandBuffer *pCommandBuffers) {
6973 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06006974 auto *cb_context = GetAccessContext(commandBuffer);
6975 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06006976 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07006977 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06006978 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
6979 if (!recorded_cb_context) continue;
6980 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context, CMD_EXECUTECOMMANDS);
6981 }
John Zulaufae842002021-04-15 18:20:55 -06006982}
6983
John Zulauf1d5f9c12022-05-13 14:51:08 -06006984void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
6985 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
6986 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
6987
6988 const auto queue_state = GetQueueSyncStateShared(queue);
6989 if (!queue_state) return; // Invalid queue
6990 QueueId waited_queue = queue_state->GetQueueId();
6991
6992 // We need to go through every queue batch context and clear all accesses this wait synchronizes
6993 // As usual -- two groups, the "last batch" and the signaled semaphores
6994 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
6995 // QueueBatchContext, track which we've done to avoid duplicate traversals
6996 QueueBatchContext::BatchSet waited;
6997 for (auto &queue : queue_sync_states_) {
6998 auto batch = queue.second->LastBatch();
6999 if (batch) {
7000 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
7001 waited.emplace(batch);
7002 }
7003 }
7004
7005 for (const auto &signaled : signaled_semaphores_) {
7006 auto &sem_sig = signaled.second;
7007 if (sem_sig && sem_sig->batch && (waited.find(sem_sig->batch) == waited.end())) {
7008 sem_sig->batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
7009 waited.emplace(sem_sig->batch);
7010 }
7011 }
7012 // TODO: Update Events and Fences affected by Wait
7013}
7014
7015void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7016 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
7017 for (auto &queue : queue_sync_states_) {
7018 auto batch = queue.second->LastBatch();
7019 if (batch) {
7020 batch->ApplyDeviceWait();
7021 }
7022 }
7023
7024 auto wait_no_list = [](std::shared_ptr<QueueBatchContext> &batch) {
7025 batch->ApplyDeviceWait();
7026 return false;
7027 };
7028
7029 GetQueueLastBatchSnapshot(wait_no_list);
7030
7031 // TODO: Update Events and Fences affected by Wait
7032}
7033
John Zulauf697c0e12022-04-19 16:31:12 -06007034struct QueueSubmitCmdState {
7035 std::shared_ptr<const QueueSyncState> queue;
7036 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007037 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007038 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007039 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7040 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007041};
7042
7043template <>
7044thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7045
John Zulaufbbda4572022-04-19 16:20:45 -06007046bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7047 VkFence fence) const {
7048 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007049
7050 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007051 if (!enabled[sync_validation_queue_submit]) return skip;
7052
John Zulauf00119522022-05-23 19:07:42 -06007053 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007054 const auto fence_state = Get<FENCE_STATE>(fence);
7055 cmd_state->queue = GetQueueSyncStateShared(queue);
7056 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007057
John Zulauf697c0e12022-04-19 16:31:12 -06007058 const char *func_name = "vkQueueSubmit";
7059
7060 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7061 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7062
7063 // verify each submit batch
7064 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7065 // most recently created batch
7066 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7067 std::shared_ptr<QueueBatchContext> batch;
7068 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7069 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007070 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7071 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007072 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
7073
7074 // For each submit in the batch...
7075 for (const auto &cb : *batch) {
7076 skip |= cb.cb->ValidateFirstUse(batch.get(), func_name, cb.index);
7077
7078 // The barriers have already been applied in ValidatFirstUse
7079 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007080 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
John Zulauf697c0e12022-04-19 16:31:12 -06007081 }
7082
John Zulauf697c0e12022-04-19 16:31:12 -06007083 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7084 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007085 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007086 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007087 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7088 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7089 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007090 }
7091 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7092 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7093 last_batch = batch;
7094 }
7095 // The most recently created batch will become the queue's "last batch" in the record phase
7096 if (batch) {
7097 cmd_state->last_batch = std::move(batch);
7098 }
7099
7100 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007101 return skip;
7102}
7103
7104void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7105 VkResult result) {
7106 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007107
John Zulaufcb7e1672022-05-04 13:46:08 -06007108 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007109 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7110
John Zulaufcb7e1672022-05-04 13:46:08 -06007111 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7112 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007113 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007114
7115 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007116 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7117
John Zulauf697c0e12022-04-19 16:31:12 -06007118 // Don't need to look up the queue state again, but we need a non-const version
7119 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007120
John Zulaufcb7e1672022-05-04 13:46:08 -06007121 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7122 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7123 // QBC's are those referenced by unwaited signals and the last batch.
7124 for (auto &sig_sem : cmd_state->signaled) {
7125 if (sig_sem.second && sig_sem.second->batch) {
7126 sig_sem.second->batch->ResetAccessLog();
7127 }
7128 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007129 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007130 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007131
John Zulaufcb7e1672022-05-04 13:46:08 -06007132 // Update the queue to point to the last batch from the submit
7133 if (cmd_state->last_batch) {
7134 cmd_state->last_batch->ResetAccessLog();
7135 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007136 }
7137
7138 // Update the global access log from the one built during validation
7139 global_access_log_.MergeMove(std::move(cmd_state->logger));
7140
John Zulauf697c0e12022-04-19 16:31:12 -06007141
7142 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007143}
7144
7145bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7146 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007147 bool skip = false;
7148 if (!enabled[sync_validation_queue_submit]) return skip;
7149
John Zulauf697c0e12022-04-19 16:31:12 -06007150 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007151 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007152}
7153
7154void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7155 VkFence fence, VkResult result) {
7156 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007157 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7158
7159 if (!enabled[sync_validation_queue_submit]) return;
7160
John Zulauf697c0e12022-04-19 16:31:12 -06007161 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007162}
7163
John Zulaufd0ec59f2021-03-13 14:25:08 -07007164AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7165 : view_(view), view_mask_(), gen_store_() {
7166 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7167 const IMAGE_STATE &image_state = *view_->image_state.get();
7168 const auto base_address = ResourceBaseAddress(image_state);
7169 const auto *encoder = image_state.fragment_encoder.get();
7170 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007171 // Get offset and extent for the view, accounting for possible depth slicing
7172 const VkOffset3D zero_offset = view->GetOffset();
7173 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007174 // Intentional copy
7175 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7176 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007177 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7178 view->IsDepthSliced());
7179 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007180
7181 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7182 if (depth && (depth != view_mask_)) {
7183 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007184 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007185 }
7186 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7187 if (stencil && (stencil != view_mask_)) {
7188 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007189 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7190 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007191 }
7192}
7193
7194const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7195 const ImageRangeGen *got = nullptr;
7196 switch (gen_type) {
7197 case kViewSubresource:
7198 got = &gen_store_[kViewSubresource];
7199 break;
7200 case kRenderArea:
7201 got = &gen_store_[kRenderArea];
7202 break;
7203 case kDepthOnlyRenderArea:
7204 got =
7205 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7206 break;
7207 case kStencilOnlyRenderArea:
7208 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7209 : &gen_store_[Gen::kStencilOnlyRenderArea];
7210 break;
7211 default:
7212 assert(got);
7213 }
7214 return got;
7215}
7216
7217AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7218 assert(IsValid());
7219 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7220 if (depth_op) {
7221 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7222 if (stencil_op) {
7223 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7224 return kRenderArea;
7225 }
7226 return kDepthOnlyRenderArea;
7227 }
7228 if (stencil_op) {
7229 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7230 return kStencilOnlyRenderArea;
7231 }
7232
7233 assert(depth_op || stencil_op);
7234 return kRenderArea;
7235}
7236
7237AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007238
7239void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst) {
7240 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7241 for (auto &event_pair : map_) {
7242 assert(event_pair.second); // Shouldn't be storing empty
7243 auto &sync_event = *event_pair.second;
7244 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
7245 if ((sync_event.barriers & src.exec_scope) || all_commands_bit) {
7246 sync_event.barriers |= dst.exec_scope;
7247 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7248 }
7249 }
7250}
John Zulaufbb890452021-12-14 11:30:18 -07007251
7252ReplayTrackbackBarriersAction::ReplayTrackbackBarriersAction(VkQueueFlags queue_flags,
7253 const SubpassDependencyGraphNode &subpass_dep,
7254 const std::vector<ReplayTrackbackBarriersAction> &replay_contexts) {
7255 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
7256 trackback_barriers.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
7257 for (const auto &prev_dep : subpass_dep.prev) {
7258 const auto prev_pass = prev_dep.first->pass;
7259 const auto &prev_barriers = prev_dep.second;
7260 trackback_barriers.emplace_back(&replay_contexts[prev_pass], queue_flags, prev_barriers);
7261 }
7262 if (has_barrier_from_external) {
7263 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
7264 trackback_barriers.emplace_back(nullptr, queue_flags, subpass_dep.barrier_from_external);
7265 }
7266}
7267
7268void ReplayTrackbackBarriersAction::operator()(ResourceAccessState *access) const {
7269 if (trackback_barriers.size() == 1) {
7270 trackback_barriers[0](access);
7271 } else {
7272 ResourceAccessState resolved;
7273 for (const auto &trackback : trackback_barriers) {
7274 ResourceAccessState access_copy = *access;
7275 trackback(&access_copy);
7276 resolved.Resolve(access_copy);
7277 }
7278 *access = resolved;
7279 }
7280}
7281
7282ReplayTrackbackBarriersAction::TrackbackBarriers::TrackbackBarriers(
7283 const ReplayTrackbackBarriersAction *source_subpass_, VkQueueFlags queue_flags_,
7284 const std::vector<const VkSubpassDependency2 *> &subpass_dependencies_)
7285 : Base(source_subpass_, queue_flags_, subpass_dependencies_) {}
7286
7287void ReplayTrackbackBarriersAction::TrackbackBarriers::operator()(ResourceAccessState *access) const {
7288 if (source_subpass) {
7289 (*source_subpass)(access);
7290 }
7291 access->ApplyBarriersImmediate(barriers);
7292}
John Zulauf697c0e12022-04-19 16:31:12 -06007293
John Zulaufcb7e1672022-05-04 13:46:08 -06007294QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
7295 : CommandExecutionContext(&sync_state), queue_state_(&queue_state), tag_range_(0, 0), batch_log_(nullptr) {}
7296
John Zulauf697c0e12022-04-19 16:31:12 -06007297template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007298void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7299 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007300 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007301 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007302}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007303void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
7304 QueueId queue_id = queue_state_->GetQueueId();
7305 auto tag_queue_op = [offset, queue_id](ResourceAccessState *access) {
7306 access->OffsetTag(offset);
7307 access->SetQueueId(queue_id);
7308 };
7309 GetCurrentAccessContext()->ResolveFromContext(tag_queue_op, recorded_context);
7310}
John Zulauf697c0e12022-04-19 16:31:12 -06007311
7312VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7313
John Zulauf1d5f9c12022-05-13 14:51:08 -06007314void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7315 QueueWaitWorm wait_worm(queue_id);
7316 access_context_.ForAll(wait_worm);
7317 if (wait_worm.erase_all) {
7318 access_context_.Reset();
7319 } else {
7320 // TODO: Profiling will tell us if we need a more efficient clean up.
7321 for (const auto &address : wait_worm.erase_list) {
7322 access_context_.DeleteAccess(address);
7323 }
7324 }
7325}
7326
7327// Clear all accesses
7328void QueueBatchContext::ApplyDeviceWait() { access_context_.Reset(); }
7329
John Zulaufcb7e1672022-05-04 13:46:08 -06007330void QueueBatchContext::WaitOneSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask, WaitBatchMap &batch_trackbacks,
7331 SignaledSemaphores &signaled) {
7332 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
7333 if (!sem_state) return; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007334
John Zulaufcb7e1672022-05-04 13:46:08 -06007335 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7336 auto signal_state = signaled.Unsignal(sem);
7337 if (!signal_state) return; // Invalid signal, skip it.
7338
7339 const auto &sem_batch = signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007340 assert(sem_batch);
7341
7342 const AccessContext *sem_context = sem_batch->GetCurrentAccessContext();
7343
7344 using TrackBackPtr = AccessContext::TrackBack *;
John Zulaufcb7e1672022-05-04 13:46:08 -06007345 const auto trackback_insert = batch_trackbacks.emplace(sem_batch.get(), TrackBackPtr());
John Zulauf697c0e12022-04-19 16:31:12 -06007346 const bool inserted = trackback_insert.second;
7347 const auto trackback_it = trackback_insert.first;
7348
John Zulaufcb7e1672022-05-04 13:46:08 -06007349 const SyncExecScope &sem_scope = signal_state->exec_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007350 const auto queue_flags = queue_state_->GetQueueFlags();
7351 SyncExecScope dst_mask = SyncExecScope::MakeDst(queue_flags, wait_mask);
7352 const SyncBarrier sem_barrier(sem_scope, sem_scope.valid_accesses, dst_mask, SyncStageAccessFlags());
7353 if (inserted) {
7354 // If this is the first time we referenced this QueueBatchContext
7355 trackback_it->second = access_context_.AddTrackBack(sem_context, sem_barrier);
7356 }
7357 assert(trackback_it->second);
7358 trackback_it->second->barriers.emplace_back(sem_barrier);
7359}
7360
7361// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7362template <>
7363class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7364 public:
7365 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7366 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7367 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7368 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7369 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7370 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7371
7372 private:
7373 const VkSubmitInfo &info_;
7374};
7375template <typename BatchInfo, typename Fn>
7376void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7377 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7378 Accessor batch(batch_info);
7379 const uint32_t wait_count = batch.WaitSemaphoreCount();
7380 for (uint32_t i = 0; i < wait_count; ++i) {
7381 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7382 }
7383}
7384
7385template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007386void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7387 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007388 // Create trackbacks for the access context for this batch based on the semaphores and the previous batch in this
7389 // queue.
7390 WaitBatchMap batch_trackbacks;
John Zulaufcb7e1672022-05-04 13:46:08 -06007391 ForEachWaitSemaphore(batch_info, [this, &batch_trackbacks, &signaled](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7392 WaitOneSemaphore(sem, wait_mask, batch_trackbacks, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007393 });
7394
John Zulauf78cb2082022-04-20 16:37:48 -06007395 // If there are no semaphores to the previous batch, make sure a "submit order" empty trackback is added
7396 if (prev && (batch_trackbacks.find(prev.get()) == batch_trackbacks.end())) {
7397 access_context_.AddTrackBack(prev->GetCurrentAccessContext(), SyncBarrier());
7398 }
7399
John Zulauf697c0e12022-04-19 16:31:12 -06007400 // Flatten all previous contexts into the current one (for dependency chaining reasons)
7401 access_context_.ResolvePreviousAccesses();
7402 access_context_.ClearTrackBacks();
7403
7404 // Gather async context information for hazard checks and conserve the QBC's for the async batches
7405 const auto end_it = batch_trackbacks.end();
John Zulauf78cb2082022-04-20 16:37:48 -06007406 async_batches_ = sync_state_->GetQueueLastBatchSnapshot(
7407 [&batch_trackbacks, end_it, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
John Zulauf697c0e12022-04-19 16:31:12 -06007408 const auto found_it = batch_trackbacks.find(batch.get());
John Zulauf78cb2082022-04-20 16:37:48 -06007409 return found_it == end_it && (batch != prev);
John Zulauf697c0e12022-04-19 16:31:12 -06007410 });
7411 for (const auto &async_batch : async_batches_) {
7412 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7413 }
7414}
7415
7416template <typename BatchInfo>
7417void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7418 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7419 Accessor batch(batch_info);
7420
7421 // Create the list of command buffers to submit
7422 const uint32_t cb_count = batch.CommandBufferCount();
7423 command_buffers_.reserve(cb_count);
7424 for (uint32_t index = 0; index < cb_count; ++index) {
7425 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7426 if (cb_context) {
7427 tag_range_.end += cb_context->GetTagLimit();
7428 command_buffers_.emplace_back(index, std::move(cb_context));
7429 }
7430 }
7431}
7432
7433// Look up the usage informaiton from the local or global logger
7434std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7435 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7436 std::stringstream out;
7437 AccessLogger::AccessRecord access = use_logger[tag];
7438 if (access.IsValid()) {
7439 const AccessLogger::BatchRecord &batch = *access.batch;
7440 const ResourceUsageRecord &record = *access.record;
7441 // Queue and Batch information
7442 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7443 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7444
7445 // Commandbuffer Usages Information
7446 out << record;
7447 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7448 out << ", reset_no: " << std::to_string(record.reset_count);
7449 }
7450 return out.str();
7451}
7452
7453VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7454
John Zulauf00119522022-05-23 19:07:42 -06007455QueueId QueueBatchContext::GetQueueId() const {
7456 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7457 return id;
7458}
7459
John Zulauf697c0e12022-04-19 16:31:12 -06007460void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7461 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7462 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7463 SetTagBias(global_tags.begin);
7464 // Add an access log for the batches range and point the batch at it.
7465 logger_ = &logger;
7466 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7467}
7468
7469void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7470 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7471 batch_log_->Append(submitted_cb.GetAccessLog());
7472}
7473
7474void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7475 const auto size = tag_range_.size();
7476 tag_range_.begin = bias;
7477 tag_range_.end = bias + size;
7478 access_context_.SetStartTag(bias);
7479}
7480
John Zulauf1d5f9c12022-05-13 14:51:08 -06007481QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7482
7483void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7484 bool erased = access.second.ApplyQueueTagWait(predicate);
7485 if (erased) {
7486 erase_list.emplace_back(address_type, access.first);
7487 } else {
7488 erase_all = false;
7489 }
7490}
7491
John Zulauf697c0e12022-04-19 16:31:12 -06007492AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7493 const ResourceUsageRange &range) {
7494 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7495 assert(inserted.second);
7496 return &inserted.first->second;
7497}
7498
7499void AccessLogger::MergeMove(AccessLogger &&child) {
7500 for (auto &range : child.access_log_map_) {
7501 BatchLog &child_batch = range.second;
7502 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7503 insert_pair.first->second = std::move(child_batch);
7504 assert(insert_pair.second);
7505 }
7506 child.Reset();
7507}
7508
7509void AccessLogger::Reset() {
7510 prev_ = nullptr;
7511 access_log_map_.clear();
7512}
7513
7514// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7515// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7516// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7517// the contexts Resolve all history from previous all contexts when created
7518void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7519 last_batch_ = std::move(last);
7520 last_batch_->ResetAccessLog();
7521}
7522
7523// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7524// scope state.
7525// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7526// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7527uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7528
7529void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7530 log_.insert(log_.end(), other.cbegin(), other.cend());
7531 for (const auto &record : other) {
7532 assert(record.cb_state);
7533 cbs_referenced_.insert(record.cb_state->shared_from_this());
7534 }
7535}
7536
7537AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7538 assert(index < log_.size());
7539 return AccessRecord{&batch_, &log_[index]};
7540}
7541
7542AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7543 AccessRecord access_record = {nullptr, nullptr};
7544
7545 auto found_range = access_log_map_.find(tag);
7546 if (found_range != access_log_map_.cend()) {
7547 const ResourceUsageTag bias = found_range->first.begin;
7548 assert(tag >= bias);
7549 access_record = found_range->second[tag - bias];
7550 } else if (prev_) {
7551 access_record = (*prev_)[tag];
7552 }
7553
7554 return access_record;
7555}
John Zulaufcb7e1672022-05-04 13:46:08 -06007556
7557std::shared_ptr<SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
7558 std::shared_ptr<Signal> prev_state;
7559 if (prev_) {
7560 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7561 }
7562 return prev_state;
7563}