blob: d73ceb149f7debd55914859cfc5e2e421001673a [file] [log] [blame]
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001/* Copyright (c) 2015-2021 The Khronos Group Inc.
2 * Copyright (c) 2015-2021 Valve Corporation
3 * Copyright (c) 2015-2021 LunarG, Inc.
4 * Copyright (C) 2015-2021 Google Inc.
5 * Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * Author: Courtney Goeltzenleuchter <courtneygo@google.com>
20 * Author: Tobin Ehlis <tobine@google.com>
21 * Author: Chris Forbes <chrisf@ijw.co.nz>
22 * Author: Mark Lobodzinski <mark@lunarg.com>
23 * Author: Dave Houlton <daveh@lunarg.com>
24 * Author: John Zulauf <jzulauf@lunarg.com>
25 * Author: Tobias Hector <tobias.hector@amd.com>
26 */
27#pragma once
28#include "base_node.h"
29#include "query_state.h"
30#include "command_validation.h"
31#include "hash_vk_types.h"
32#include "subresource_adapter.h"
33#include "image_layout_map.h"
34#include "pipeline_state.h"
35#include "device_state.h"
36#include "descriptor_sets.h"
37#include "qfo_transfer.h"
38
39class RENDER_PASS_STATE;
40class CoreChecks;
41class ValidationStateTracker;
42
43class EVENT_STATE : public BASE_NODE {
44 public:
45 int write_in_use;
46 VkPipelineStageFlags2KHR stageMask = VkPipelineStageFlags2KHR(0);
47 VkEventCreateFlags flags;
48
49 EVENT_STATE(VkEvent event_, VkEventCreateFlags flags_)
50 : BASE_NODE(event_, kVulkanObjectTypeEvent), write_in_use(0), flags(flags_) {}
51
52 VkEvent event() const { return handle_.Cast<VkEvent>(); }
53};
54
55// Only CoreChecks uses this, but the state tracker stores it.
56constexpr static auto kInvalidLayout = image_layout_map::kInvalidLayout;
57using ImageSubresourceLayoutMap = image_layout_map::ImageSubresourceLayoutMap;
58typedef layer_data::unordered_map<VkEvent, VkPipelineStageFlags2KHR> EventToStageMap;
59
60// Track command pools and their command buffers
61class COMMAND_POOL_STATE : public BASE_NODE {
62 public:
63 VkCommandPoolCreateFlags createFlags;
64 uint32_t queueFamilyIndex;
65 VkQueueFlags queue_flags;
66 bool unprotected; // can't be used for protected memory
67 // Cmd buffers allocated from this pool
68 layer_data::unordered_set<VkCommandBuffer> commandBuffers;
69
70 COMMAND_POOL_STATE(VkCommandPool cp, const VkCommandPoolCreateInfo *pCreateInfo, VkQueueFlags flags)
71 : BASE_NODE(cp, kVulkanObjectTypeCommandPool),
72 createFlags(pCreateInfo->flags),
73 queueFamilyIndex(pCreateInfo->queueFamilyIndex),
74 queue_flags(flags),
75 unprotected((pCreateInfo->flags & VK_COMMAND_POOL_CREATE_PROTECTED_BIT) == 0) {}
76
77 VkCommandPool commandPool() const { return handle_.Cast<VkCommandPool>(); }
78
79 virtual ~COMMAND_POOL_STATE() { Destroy(); }
80
81 void Destroy() override {
82 commandBuffers.clear();
83 BASE_NODE::Destroy();
84 }
85};
86
Jeremy Gebben159b3cc2021-06-03 09:09:03 -060087// Autogenerated as part of the command_validation.h codegen
88const char *CommandTypeString(CMD_TYPE type);
89
90enum CB_STATE {
91 CB_NEW, // Newly created CB w/o any cmds
92 CB_RECORDING, // BeginCB has been called on this CB
93 CB_RECORDED, // EndCB has been called on this CB
94 CB_INVALID_COMPLETE, // had a complete recording, but was since invalidated
95 CB_INVALID_INCOMPLETE, // fouled before recording was completed
96};
97
98// CB Status -- used to track status of various bindings on cmd buffer objects
99typedef uint64_t CBStatusFlags;
100enum CBStatusFlagBits : uint64_t {
101 // clang-format off
102 CBSTATUS_NONE = 0x00000000, // No status is set
103 CBSTATUS_LINE_WIDTH_SET = 0x00000001, // Line width has been set
104 CBSTATUS_DEPTH_BIAS_SET = 0x00000002, // Depth bias has been set
105 CBSTATUS_BLEND_CONSTANTS_SET = 0x00000004, // Blend constants state has been set
106 CBSTATUS_DEPTH_BOUNDS_SET = 0x00000008, // Depth bounds state object has been set
107 CBSTATUS_STENCIL_READ_MASK_SET = 0x00000010, // Stencil read mask has been set
108 CBSTATUS_STENCIL_WRITE_MASK_SET = 0x00000020, // Stencil write mask has been set
109 CBSTATUS_STENCIL_REFERENCE_SET = 0x00000040, // Stencil reference has been set
110 CBSTATUS_VIEWPORT_SET = 0x00000080,
111 CBSTATUS_SCISSOR_SET = 0x00000100,
112 CBSTATUS_INDEX_BUFFER_BOUND = 0x00000200, // Index buffer has been set
113 CBSTATUS_EXCLUSIVE_SCISSOR_SET = 0x00000400,
114 CBSTATUS_SHADING_RATE_PALETTE_SET = 0x00000800,
115 CBSTATUS_LINE_STIPPLE_SET = 0x00001000,
116 CBSTATUS_VIEWPORT_W_SCALING_SET = 0x00002000,
117 CBSTATUS_CULL_MODE_SET = 0x00004000,
118 CBSTATUS_FRONT_FACE_SET = 0x00008000,
119 CBSTATUS_PRIMITIVE_TOPOLOGY_SET = 0x00010000,
120 CBSTATUS_VIEWPORT_WITH_COUNT_SET = 0x00020000,
121 CBSTATUS_SCISSOR_WITH_COUNT_SET = 0x00040000,
122 CBSTATUS_VERTEX_INPUT_BINDING_STRIDE_SET = 0x00080000,
123 CBSTATUS_DEPTH_TEST_ENABLE_SET = 0x00100000,
124 CBSTATUS_DEPTH_WRITE_ENABLE_SET = 0x00200000,
125 CBSTATUS_DEPTH_COMPARE_OP_SET = 0x00400000,
126 CBSTATUS_DEPTH_BOUNDS_TEST_ENABLE_SET = 0x00800000,
127 CBSTATUS_STENCIL_TEST_ENABLE_SET = 0x01000000,
128 CBSTATUS_STENCIL_OP_SET = 0x02000000,
129 CBSTATUS_DISCARD_RECTANGLE_SET = 0x04000000,
130 CBSTATUS_SAMPLE_LOCATIONS_SET = 0x08000000,
131 CBSTATUS_COARSE_SAMPLE_ORDER_SET = 0x10000000,
132 CBSTATUS_PATCH_CONTROL_POINTS_SET = 0x20000000,
133 CBSTATUS_RASTERIZER_DISCARD_ENABLE_SET = 0x40000000,
134 CBSTATUS_DEPTH_BIAS_ENABLE_SET = 0x80000000,
135 CBSTATUS_LOGIC_OP_SET = 0x100000000,
136 CBSTATUS_PRIMITIVE_RESTART_ENABLE_SET = 0x200000000,
137 CBSTATUS_VERTEX_INPUT_SET = 0x400000000,
138 CBSTATUS_ALL_STATE_SET = 0x7FFFFFDFF, // All state set (intentionally exclude index buffer)
139 // clang-format on
140};
141
142VkDynamicState ConvertToDynamicState(CBStatusFlagBits flag);
143CBStatusFlagBits ConvertToCBStatusFlagBits(VkDynamicState state);
144std::string DynamicStateString(CBStatusFlags input_value);
145
146struct BufferBinding {
147 std::shared_ptr<BUFFER_STATE> buffer_state;
148 VkDeviceSize size;
149 VkDeviceSize offset;
150 VkDeviceSize stride;
151
152 BufferBinding() : buffer_state(), size(0), offset(0), stride(0) {}
153 virtual ~BufferBinding() {}
154
155 virtual void reset() { *this = BufferBinding(); }
156};
157
158struct IndexBufferBinding : BufferBinding {
159 VkIndexType index_type;
160
161 IndexBufferBinding() : BufferBinding(), index_type(static_cast<VkIndexType>(0)) {}
162 virtual ~IndexBufferBinding() {}
163
164 virtual void reset() override { *this = IndexBufferBinding(); }
165};
166
167struct CBVertexBufferBindingInfo {
168 std::vector<BufferBinding> vertex_buffer_bindings;
169};
170
171typedef subresource_adapter::BothRangeMap<VkImageLayout, 16> GlobalImageLayoutRangeMap;
172typedef layer_data::unordered_map<VkImage, layer_data::optional<GlobalImageLayoutRangeMap>> GlobalImageLayoutMap;
173
174typedef layer_data::unordered_map<VkImage, layer_data::optional<ImageSubresourceLayoutMap>> CommandBufferImageLayoutMap;
175
176struct SUBPASS_INFO;
177class FRAMEBUFFER_STATE;
178
179class CMD_BUFFER_STATE : public REFCOUNTED_NODE {
180 public:
181 VkCommandBufferAllocateInfo createInfo = {};
182 VkCommandBufferBeginInfo beginInfo;
183 VkCommandBufferInheritanceInfo inheritanceInfo;
184 std::shared_ptr<const COMMAND_POOL_STATE> command_pool;
185 bool hasDrawCmd;
186 bool hasTraceRaysCmd;
187 bool hasBuildAccelerationStructureCmd;
188 bool hasDispatchCmd;
189 bool unprotected; // can't be used for protected memory
190
191 CB_STATE state; // Track cmd buffer update state
192 uint64_t commandCount; // Number of commands recorded. Currently only used with VK_KHR_performance_query
193 uint64_t submitCount; // Number of times CB has been submitted
194 typedef uint64_t ImageLayoutUpdateCount;
195 ImageLayoutUpdateCount image_layout_change_count; // The sequence number for changes to image layout (for cached validation)
196 CBStatusFlags status; // Track status of various bindings on cmd buffer
197 CBStatusFlags static_status; // All state bits provided by current graphics pipeline
198 // rather than dynamic state
199 CBStatusFlags dynamic_status; // dynamic state set up in pipeline
200 // Currently storing "lastBound" objects on per-CB basis
201 // long-term may want to create caches of "lastBound" states and could have
202 // each individual CMD_NODE referencing its own "lastBound" state
203 // Store last bound state for Gfx & Compute pipeline bind points
204 std::array<LAST_BOUND_STATE, BindPoint_Count> lastBound; // index is LvlBindPoint.
205
206 struct CmdDrawDispatchInfo {
207 CMD_TYPE cmd_type;
208 std::string function;
209 std::vector<std::pair<const uint32_t, DescriptorRequirement>> binding_infos;
210 VkFramebuffer framebuffer;
211 std::shared_ptr<std::vector<SUBPASS_INFO>> subpasses;
212 std::shared_ptr<std::vector<IMAGE_VIEW_STATE *>> attachments;
213 };
214 layer_data::unordered_map<VkDescriptorSet, std::vector<CmdDrawDispatchInfo>> validate_descriptorsets_in_queuesubmit;
215
216 // If VK_NV_inherited_viewport_scissor is enabled and VkCommandBufferInheritanceViewportScissorInfoNV::viewportScissor2D is
217 // true, then is the nonempty list of viewports passed in pViewportDepths. Otherwise, this is empty.
218 std::vector<VkViewport> inheritedViewportDepths;
219
220 // For each draw command D recorded to this command buffer, let
221 // * g_D be the graphics pipeline used
222 // * v_G be the viewportCount of g_D (0 if g_D disables rasterization or enables VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT)
223 // * s_G be the scissorCount of g_D (0 if g_D disables rasterization or enables VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT)
224 // Then this value is max(0, max(v_G for all D in cb), max(s_G for all D in cb))
225 uint32_t usedViewportScissorCount;
226 uint32_t pipelineStaticViewportCount; // v_G for currently-bound graphics pipeline.
227 uint32_t pipelineStaticScissorCount; // s_G for currently-bound graphics pipeline.
228
229 uint32_t viewportMask;
230 uint32_t viewportWithCountMask;
231 uint32_t viewportWithCountCount;
232 uint32_t scissorMask;
233 uint32_t scissorWithCountMask;
234 uint32_t scissorWithCountCount;
235
236 // Dynamic viewports set in this command buffer; if bit j of viewportMask is set then dynamicViewports[j] is valid, but the
237 // converse need not be true.
238 std::vector<VkViewport> dynamicViewports;
239
240 // Bits set when binding graphics pipeline defining corresponding static state, or executing any secondary command buffer.
241 // Bits unset by calling a corresponding vkCmdSet[State] cmd.
242 uint32_t trashedViewportMask;
243 uint32_t trashedScissorMask;
244 bool trashedViewportCount;
245 bool trashedScissorCount;
246
247 // True iff any draw command recorded to this command buffer consumes dynamic viewport/scissor with count state.
248 bool usedDynamicViewportCount;
249 bool usedDynamicScissorCount;
250
251 uint32_t initial_device_mask;
252 VkPrimitiveTopology primitiveTopology;
253
254 safe_VkRenderPassBeginInfo activeRenderPassBeginInfo;
255 std::shared_ptr<RENDER_PASS_STATE> activeRenderPass;
256 std::shared_ptr<std::vector<SUBPASS_INFO>> active_subpasses;
257 std::shared_ptr<std::vector<IMAGE_VIEW_STATE *>> active_attachments;
258 std::set<std::shared_ptr<IMAGE_VIEW_STATE>> attachments_view_states;
259
260 VkSubpassContents activeSubpassContents;
261 uint32_t active_render_pass_device_mask;
262 uint32_t activeSubpass;
263 std::shared_ptr<FRAMEBUFFER_STATE> activeFramebuffer;
264 layer_data::unordered_set<std::shared_ptr<FRAMEBUFFER_STATE>> framebuffers;
265 // Unified data structs to track objects bound to this command buffer as well as object
266 // dependencies that have been broken : either destroyed objects, or updated descriptor sets
267 layer_data::unordered_set<VulkanTypedHandle> object_bindings;
268 layer_data::unordered_map<VulkanTypedHandle, LogObjectList> broken_bindings;
269
270 QFOTransferBarrierSets<QFOBufferTransferBarrier> qfo_transfer_buffer_barriers;
271 QFOTransferBarrierSets<QFOImageTransferBarrier> qfo_transfer_image_barriers;
272
273 layer_data::unordered_set<VkEvent> waitedEvents;
274 std::vector<VkEvent> writeEventsBeforeWait;
275 std::vector<VkEvent> events;
276 layer_data::unordered_set<QueryObject> activeQueries;
277 layer_data::unordered_set<QueryObject> startedQueries;
278 layer_data::unordered_set<QueryObject> resetQueries;
279 CommandBufferImageLayoutMap image_layout_map;
280 CBVertexBufferBindingInfo current_vertex_buffer_binding_info;
281 bool vertex_buffer_used; // Track for perf warning to make sure any bound vtx buffer used
282 VkCommandBuffer primaryCommandBuffer;
283 // If primary, the secondary command buffers we will call.
284 // If secondary, the primary command buffers we will be called by.
285 layer_data::unordered_set<CMD_BUFFER_STATE *> linkedCommandBuffers;
286 // Validation functions run at primary CB queue submit time
287 std::vector<std::function<bool(const ValidationStateTracker *device_data, const class QUEUE_STATE *queue_state)>>
288 queue_submit_functions;
Hans-Kristian Arntzen59c2c3f2021-06-14 11:40:12 +0200289 // Used by some layers to defer actions until vkCmdEndRenderPass time.
290 // Layers using this are responsible for inserting the callbacks into queue_submit_functions.
291 std::vector<std::function<bool(const ValidationStateTracker *device_data, const class QUEUE_STATE *queue_state)>>
292 queue_submit_functions_after_render_pass;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600293 // Validation functions run when secondary CB is executed in primary
294 std::vector<std::function<bool(const CMD_BUFFER_STATE *, const FRAMEBUFFER_STATE *)>> cmd_execute_commands_functions;
295 std::vector<
296 std::function<bool(const ValidationStateTracker *device_data, bool do_validate, EventToStageMap *localEventToStageMap)>>
297 eventUpdates;
298 std::vector<std::function<bool(const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool,
299 uint32_t perfQueryPass, QueryMap *localQueryToStateMap)>>
300 queryUpdates;
301 layer_data::unordered_set<cvdescriptorset::DescriptorSet *> validated_descriptor_sets;
302 // Contents valid only after an index buffer is bound (CBSTATUS_INDEX_BUFFER_BOUND set)
303 IndexBufferBinding index_buffer_binding;
304 bool performance_lock_acquired = false;
305 bool performance_lock_released = false;
306
307 // Cache of current insert label...
308 LoggingLabel debug_label;
309
310 std::vector<uint8_t> push_constant_data;
311 PushConstantRangesId push_constant_data_ranges;
312
313 std::map<VkShaderStageFlagBits, std::vector<uint8_t>>
314 push_constant_data_update; // vector's value is enum PushConstantByteState.
315 VkPipelineLayout push_constant_pipeline_layout_set;
316
317 // Used for Best Practices tracking
318 uint32_t small_indexed_draw_call_count;
319
320 bool transform_feedback_active{false};
321
322 CMD_BUFFER_STATE(VkCommandBuffer cb, const VkCommandBufferAllocateInfo *pCreateInfo)
323 : REFCOUNTED_NODE(cb, kVulkanObjectTypeCommandBuffer), createInfo(*pCreateInfo) {}
324
325 ~CMD_BUFFER_STATE() { Destroy(); }
326
327 void Destroy() override;
328
329 VkCommandBuffer commandBuffer() const { return handle_.Cast<VkCommandBuffer>(); }
330
331 int AddReverseBinding(const VulkanTypedHandle &obj);
332
333 IMAGE_VIEW_STATE *GetActiveAttachmentImageViewState(uint32_t index);
334 const IMAGE_VIEW_STATE *GetActiveAttachmentImageViewState(uint32_t index) const;
335
336 void AddChild(BASE_NODE *child_node);
337
338 void RemoveChild(BASE_NODE *child_node);
339
340 void Reset();
341
342 ImageSubresourceLayoutMap *GetImageSubresourceLayoutMap(const IMAGE_STATE &image_state);
343 const ImageSubresourceLayoutMap *GetImageSubresourceLayoutMap(VkImage image) const;
344
345 const QFOTransferBarrierSets<QFOImageTransferBarrier> &GetQFOBarrierSets(const QFOImageTransferBarrier &type_tag) const {
346 return qfo_transfer_image_barriers;
347 }
348
349 const QFOTransferBarrierSets<QFOBufferTransferBarrier> &GetQFOBarrierSets(const QFOBufferTransferBarrier &type_tag) const {
350 return qfo_transfer_buffer_barriers;
351 }
352
353 QFOTransferBarrierSets<QFOImageTransferBarrier> &GetQFOBarrierSets(const QFOImageTransferBarrier &type_tag) {
354 return qfo_transfer_image_barriers;
355 }
356
357 QFOTransferBarrierSets<QFOBufferTransferBarrier> &GetQFOBarrierSets(const QFOBufferTransferBarrier &type_tag) {
358 return qfo_transfer_buffer_barriers;
359 }
360
361 PIPELINE_STATE *GetCurrentPipeline(VkPipelineBindPoint pipelineBindPoint) const {
362 const auto lv_bind_point = ConvertToLvlBindPoint(pipelineBindPoint);
363 return lastBound[lv_bind_point].pipeline_state;
364 }
365
366 void GetCurrentPipelineAndDesriptorSets(VkPipelineBindPoint pipelineBindPoint, const PIPELINE_STATE **rtn_pipe,
367 const std::vector<LAST_BOUND_STATE::PER_SET> **rtn_sets) const {
368 const auto lv_bind_point = ConvertToLvlBindPoint(pipelineBindPoint);
369 const auto &last_bound_it = lastBound[lv_bind_point];
370 if (!last_bound_it.IsUsing()) {
371 return;
372 }
373 *rtn_pipe = last_bound_it.pipeline_state;
374 *rtn_sets = &(last_bound_it.per_set);
375 }
376
377 VkQueueFlags GetQueueFlags() const {
378 return command_pool->queue_flags;
379 }
380
Jeremy Gebbenefead332021-06-18 08:22:44 -0600381 template <typename Barrier>
Jeremy Gebben7ba56152021-06-18 10:40:10 -0600382 inline bool IsReleaseOp(const Barrier &barrier) const {
383 return (IsTransferOp(barrier)) && (command_pool->queueFamilyIndex == barrier.srcQueueFamilyIndex);
384 }
385 template <typename Barrier>
386 inline bool IsAcquireOp(const Barrier &barrier) const {
387 return (IsTransferOp(barrier)) && (command_pool->queueFamilyIndex == barrier.dstQueueFamilyIndex);
Jeremy Gebbenefead332021-06-18 08:22:44 -0600388 }
389
Jeremy Gebben159b3cc2021-06-03 09:09:03 -0600390 protected:
391 void NotifyInvalidate(const LogObjectList &invalid_handles, bool unlink) override;
392};
Jeremy Gebben7ba56152021-06-18 10:40:10 -0600393
394// specializations for barriers that cannot do queue family ownership transfers
395template <>
396inline bool CMD_BUFFER_STATE::IsReleaseOp(const VkMemoryBarrier &barrier) const {
397 return false;
398}
399template <>
400inline bool CMD_BUFFER_STATE::IsReleaseOp(const VkMemoryBarrier2KHR &barrier) const {
401 return false;
402}
403template <>
404inline bool CMD_BUFFER_STATE::IsReleaseOp(const VkSubpassDependency2 &barrier) const {
405 return false;
406}
407template <>
408inline bool CMD_BUFFER_STATE::IsAcquireOp(const VkMemoryBarrier &barrier) const {
409 return false;
410}
411template <>
412inline bool CMD_BUFFER_STATE::IsAcquireOp(const VkMemoryBarrier2KHR &barrier) const {
413 return false;
414}
415template <>
416inline bool CMD_BUFFER_STATE::IsAcquireOp(const VkSubpassDependency2 &barrier) const {
417 return false;
418}