layers: Add support for VK_EXT_descriptor_indexing
[platform/upstream/Vulkan-LoaderAndValidationLayers.git] / layers / descriptor_sets.cpp
1 /* Copyright (c) 2015-2016 The Khronos Group Inc.
2  * Copyright (c) 2015-2016 Valve Corporation
3  * Copyright (c) 2015-2016 LunarG, Inc.
4  * Copyright (C) 2015-2016 Google Inc.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * Author: Tobin Ehlis <tobine@google.com>
19  *         John Zulauf <jzulauf@lunarg.com>
20  */
21
22 // Allow use of STL min and max functions in Windows
23 #define NOMINMAX
24
25 #include "descriptor_sets.h"
26 #include "hash_vk_types.h"
27 #include "vk_enum_string_helper.h"
28 #include "vk_safe_struct.h"
29 #include "vk_typemap_helper.h"
30 #include "buffer_validation.h"
31 #include <sstream>
32 #include <algorithm>
33 #include <memory>
34
35 // ExtendedBinding collects a VkDescriptorSetLayoutBinding and any extended
36 // state that comes from a different array/structure so they can stay together
37 // while being sorted by binding number.
38 struct ExtendedBinding {
39     ExtendedBinding(const VkDescriptorSetLayoutBinding *l, VkDescriptorBindingFlagsEXT f) : layout_binding(l), binding_flags(f) {}
40
41     const VkDescriptorSetLayoutBinding *layout_binding;
42     VkDescriptorBindingFlagsEXT binding_flags;
43 };
44
45 struct BindingNumCmp {
46     bool operator()(const ExtendedBinding &a, const ExtendedBinding &b) const {
47         return a.layout_binding->binding < b.layout_binding->binding;
48     }
49 };
50
51 using DescriptorSetLayoutDef = cvdescriptorset::DescriptorSetLayoutDef;
52 using DescriptorSetLayoutId = cvdescriptorset::DescriptorSetLayoutId;
53
54 // Canonical dictionary of DescriptorSetLayoutDef (without any handle/device specific information)
55 cvdescriptorset::DescriptorSetLayoutDict descriptor_set_layout_dict;
56
57 DescriptorSetLayoutId get_canonical_id(const VkDescriptorSetLayoutCreateInfo *p_create_info) {
58     return descriptor_set_layout_dict.look_up(DescriptorSetLayoutDef(p_create_info));
59 }
60
61 // Construct DescriptorSetLayout instance from given create info
62 // Proactively reserve and resize as possible, as the reallocation was visible in profiling
63 cvdescriptorset::DescriptorSetLayoutDef::DescriptorSetLayoutDef(const VkDescriptorSetLayoutCreateInfo *p_create_info)
64     : flags_(p_create_info->flags), binding_count_(0), descriptor_count_(0), dynamic_descriptor_count_(0) {
65     const auto *flags_create_info = lvl_find_in_chain<VkDescriptorSetLayoutBindingFlagsCreateInfoEXT>(p_create_info->pNext);
66
67     binding_type_stats_ = {0, 0, 0};
68     std::set<ExtendedBinding, BindingNumCmp> sorted_bindings;
69     const uint32_t input_bindings_count = p_create_info->bindingCount;
70     // Sort the input bindings in binding number order, eliminating duplicates
71     for (uint32_t i = 0; i < input_bindings_count; i++) {
72         VkDescriptorBindingFlagsEXT flags = 0;
73         if (flags_create_info && flags_create_info->bindingCount == p_create_info->bindingCount) {
74             flags = flags_create_info->pBindingFlags[i];
75         }
76         sorted_bindings.insert(ExtendedBinding(p_create_info->pBindings + i, flags));
77     }
78
79     // Store the create info in the sorted order from above
80     std::map<uint32_t, uint32_t> binding_to_dyn_count;
81     uint32_t index = 0;
82     binding_count_ = static_cast<uint32_t>(sorted_bindings.size());
83     bindings_.reserve(binding_count_);
84     binding_flags_.reserve(binding_count_);
85     binding_to_index_map_.reserve(binding_count_);
86     for (auto input_binding : sorted_bindings) {
87         // Add to binding and map, s.t. it is robust to invalid duplication of binding_num
88         const auto binding_num = input_binding.layout_binding->binding;
89         binding_to_index_map_[binding_num] = index++;
90         bindings_.emplace_back(input_binding.layout_binding);
91         auto &binding_info = bindings_.back();
92         binding_flags_.emplace_back(input_binding.binding_flags);
93
94         descriptor_count_ += binding_info.descriptorCount;
95         if (binding_info.descriptorCount > 0) {
96             non_empty_bindings_.insert(binding_num);
97         }
98
99         if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
100             binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
101             binding_to_dyn_count[binding_num] = binding_info.descriptorCount;
102             dynamic_descriptor_count_ += binding_info.descriptorCount;
103             binding_type_stats_.dynamic_buffer_count++;
104         } else if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) ||
105                    (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)) {
106             binding_type_stats_.non_dynamic_buffer_count++;
107         } else {
108             binding_type_stats_.image_sampler_count++;
109         }
110     }
111     assert(bindings_.size() == binding_count_);
112     assert(binding_flags_.size() == binding_count_);
113     uint32_t global_index = 0;
114     binding_to_global_index_range_map_.reserve(binding_count_);
115     // Vector order is finalized so create maps of bindings to descriptors and descriptors to indices
116     for (uint32_t i = 0; i < binding_count_; ++i) {
117         auto binding_num = bindings_[i].binding;
118         auto final_index = global_index + bindings_[i].descriptorCount;
119         binding_to_global_index_range_map_[binding_num] = IndexRange(global_index, final_index);
120         if (final_index != global_index) {
121             global_start_to_index_map_[global_index] = i;
122         }
123         global_index = final_index;
124     }
125
126     // Now create dyn offset array mapping for any dynamic descriptors
127     uint32_t dyn_array_idx = 0;
128     binding_to_dynamic_array_idx_map_.reserve(binding_to_dyn_count.size());
129     for (const auto &bc_pair : binding_to_dyn_count) {
130         binding_to_dynamic_array_idx_map_[bc_pair.first] = dyn_array_idx;
131         dyn_array_idx += bc_pair.second;
132     }
133 }
134
135 size_t cvdescriptorset::DescriptorSetLayoutDef::hash() const {
136     hash_util::HashCombiner hc;
137     hc << flags_;
138     hc.Combine(bindings_);
139     return hc.Value();
140 }
141 //
142
143 // Return valid index or "end" i.e. binding_count_;
144 // The asserts in "Get" are reduced to the set where no valid answer(like null or 0) could be given
145 // Common code for all binding lookups.
146 uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetIndexFromBinding(uint32_t binding) const {
147     const auto &bi_itr = binding_to_index_map_.find(binding);
148     if (bi_itr != binding_to_index_map_.cend()) return bi_itr->second;
149     return GetBindingCount();
150 }
151 VkDescriptorSetLayoutBinding const *cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorSetLayoutBindingPtrFromIndex(
152     const uint32_t index) const {
153     if (index >= bindings_.size()) return nullptr;
154     return bindings_[index].ptr();
155 }
156 // Return descriptorCount for given index, 0 if index is unavailable
157 uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorCountFromIndex(const uint32_t index) const {
158     if (index >= bindings_.size()) return 0;
159     return bindings_[index].descriptorCount;
160 }
161 // For the given index, return descriptorType
162 VkDescriptorType cvdescriptorset::DescriptorSetLayoutDef::GetTypeFromIndex(const uint32_t index) const {
163     assert(index < bindings_.size());
164     if (index < bindings_.size()) return bindings_[index].descriptorType;
165     return VK_DESCRIPTOR_TYPE_MAX_ENUM;
166 }
167 // For the given index, return stageFlags
168 VkShaderStageFlags cvdescriptorset::DescriptorSetLayoutDef::GetStageFlagsFromIndex(const uint32_t index) const {
169     assert(index < bindings_.size());
170     if (index < bindings_.size()) return bindings_[index].stageFlags;
171     return VkShaderStageFlags(0);
172 }
173 // Return binding flags for given index, 0 if index is unavailable
174 VkDescriptorBindingFlagsEXT cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorBindingFlagsFromIndex(
175     const uint32_t index) const {
176     if (index >= binding_flags_.size()) return 0;
177     return binding_flags_[index];
178 }
179
180 // For the given global index, return index
181 uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetIndexFromGlobalIndex(const uint32_t global_index) const {
182     auto start_it = global_start_to_index_map_.upper_bound(global_index);
183     uint32_t index = binding_count_;
184     assert(start_it != global_start_to_index_map_.cbegin());
185     if (start_it != global_start_to_index_map_.cbegin()) {
186         --start_it;
187         index = start_it->second;
188 #ifndef NDEBUG
189         const auto &range = GetGlobalIndexRangeFromBinding(bindings_[index].binding);
190         assert(range.start <= global_index && global_index < range.end);
191 #endif
192     }
193     return index;
194 }
195
196 // For the given binding, return the global index range
197 // As start and end are often needed in pairs, get both with a single hash lookup.
198 const cvdescriptorset::IndexRange &cvdescriptorset::DescriptorSetLayoutDef::GetGlobalIndexRangeFromBinding(
199     const uint32_t binding) const {
200     assert(binding_to_global_index_range_map_.count(binding));
201     // In error case max uint32_t so index is out of bounds to break ASAP
202     const static IndexRange kInvalidRange = {0xFFFFFFFF, 0xFFFFFFFF};
203     const auto &range_it = binding_to_global_index_range_map_.find(binding);
204     if (range_it != binding_to_global_index_range_map_.end()) {
205         return range_it->second;
206     }
207     return kInvalidRange;
208 }
209
210 // For given binding, return ptr to ImmutableSampler array
211 VkSampler const *cvdescriptorset::DescriptorSetLayoutDef::GetImmutableSamplerPtrFromBinding(const uint32_t binding) const {
212     const auto &bi_itr = binding_to_index_map_.find(binding);
213     if (bi_itr != binding_to_index_map_.end()) {
214         return bindings_[bi_itr->second].pImmutableSamplers;
215     }
216     return nullptr;
217 }
218 // Move to next valid binding having a non-zero binding count
219 uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetNextValidBinding(const uint32_t binding) const {
220     auto it = non_empty_bindings_.upper_bound(binding);
221     assert(it != non_empty_bindings_.cend());
222     if (it != non_empty_bindings_.cend()) return *it;
223     return GetMaxBinding() + 1;
224 }
225 // For given index, return ptr to ImmutableSampler array
226 VkSampler const *cvdescriptorset::DescriptorSetLayoutDef::GetImmutableSamplerPtrFromIndex(const uint32_t index) const {
227     if (index < bindings_.size()) {
228         return bindings_[index].pImmutableSamplers;
229     }
230     return nullptr;
231 }
232 // If our layout is compatible with rh_ds_layout, return true,
233 //  else return false and fill in error_msg will description of what causes incompatibility
234 bool cvdescriptorset::DescriptorSetLayout::IsCompatible(DescriptorSetLayout const *const rh_ds_layout,
235                                                         std::string *error_msg) const {
236     // Trivial case
237     if (layout_ == rh_ds_layout->GetDescriptorSetLayout()) return true;
238     if (get_layout_def() == rh_ds_layout->get_layout_def()) return true;
239     bool detailed_compat_check =
240         get_layout_def()->IsCompatible(layout_, rh_ds_layout->GetDescriptorSetLayout(), rh_ds_layout->get_layout_def(), error_msg);
241     // The detailed check should never tell us mismatching DSL are compatible
242     assert(!detailed_compat_check);
243     return detailed_compat_check;
244 }
245
246 // Do a detailed compatibility check of this def (referenced by ds_layout), vs. the rhs (layout and def)
247 // Should only be called if trivial accept has failed, and in that context should return false.
248 bool cvdescriptorset::DescriptorSetLayoutDef::IsCompatible(VkDescriptorSetLayout ds_layout, VkDescriptorSetLayout rh_ds_layout,
249                                                            DescriptorSetLayoutDef const *const rh_ds_layout_def,
250                                                            std::string *error_msg) const {
251     if (descriptor_count_ != rh_ds_layout_def->descriptor_count_) {
252         std::stringstream error_str;
253         error_str << "DescriptorSetLayout " << ds_layout << " has " << descriptor_count_ << " descriptors, but DescriptorSetLayout "
254                   << rh_ds_layout << ", which comes from pipelineLayout, has " << rh_ds_layout_def->descriptor_count_
255                   << " descriptors.";
256         *error_msg = error_str.str();
257         return false;  // trivial fail case
258     }
259
260     // Descriptor counts match so need to go through bindings one-by-one
261     //  and verify that type and stageFlags match
262     for (auto binding : bindings_) {
263         // TODO : Do we also need to check immutable samplers?
264         // VkDescriptorSetLayoutBinding *rh_binding;
265         if (binding.descriptorCount != rh_ds_layout_def->GetDescriptorCountFromBinding(binding.binding)) {
266             std::stringstream error_str;
267             error_str << "Binding " << binding.binding << " for DescriptorSetLayout " << ds_layout << " has a descriptorCount of "
268                       << binding.descriptorCount << " but binding " << binding.binding << " for DescriptorSetLayout "
269                       << rh_ds_layout << ", which comes from pipelineLayout, has a descriptorCount of "
270                       << rh_ds_layout_def->GetDescriptorCountFromBinding(binding.binding);
271             *error_msg = error_str.str();
272             return false;
273         } else if (binding.descriptorType != rh_ds_layout_def->GetTypeFromBinding(binding.binding)) {
274             std::stringstream error_str;
275             error_str << "Binding " << binding.binding << " for DescriptorSetLayout " << ds_layout << " is type '"
276                       << string_VkDescriptorType(binding.descriptorType) << "' but binding " << binding.binding
277                       << " for DescriptorSetLayout " << rh_ds_layout << ", which comes from pipelineLayout, is type '"
278                       << string_VkDescriptorType(rh_ds_layout_def->GetTypeFromBinding(binding.binding)) << "'";
279             *error_msg = error_str.str();
280             return false;
281         } else if (binding.stageFlags != rh_ds_layout_def->GetStageFlagsFromBinding(binding.binding)) {
282             std::stringstream error_str;
283             error_str << "Binding " << binding.binding << " for DescriptorSetLayout " << ds_layout << " has stageFlags "
284                       << binding.stageFlags << " but binding " << binding.binding << " for DescriptorSetLayout " << rh_ds_layout
285                       << ", which comes from pipelineLayout, has stageFlags "
286                       << rh_ds_layout_def->GetStageFlagsFromBinding(binding.binding);
287             *error_msg = error_str.str();
288             return false;
289         }
290     }
291     return true;
292 }
293
294 bool cvdescriptorset::DescriptorSetLayoutDef::IsNextBindingConsistent(const uint32_t binding) const {
295     if (!binding_to_index_map_.count(binding + 1)) return false;
296     auto const &bi_itr = binding_to_index_map_.find(binding);
297     if (bi_itr != binding_to_index_map_.end()) {
298         const auto &next_bi_itr = binding_to_index_map_.find(binding + 1);
299         if (next_bi_itr != binding_to_index_map_.end()) {
300             auto type = bindings_[bi_itr->second].descriptorType;
301             auto stage_flags = bindings_[bi_itr->second].stageFlags;
302             auto immut_samp = bindings_[bi_itr->second].pImmutableSamplers ? true : false;
303             auto flags = binding_flags_[bi_itr->second];
304             if ((type != bindings_[next_bi_itr->second].descriptorType) ||
305                 (stage_flags != bindings_[next_bi_itr->second].stageFlags) ||
306                 (immut_samp != (bindings_[next_bi_itr->second].pImmutableSamplers ? true : false)) ||
307                 (flags != binding_flags_[next_bi_itr->second])) {
308                 return false;
309             }
310             return true;
311         }
312     }
313     return false;
314 }
315 // Starting at offset descriptor of given binding, parse over update_count
316 //  descriptor updates and verify that for any binding boundaries that are crossed, the next binding(s) are all consistent
317 //  Consistency means that their type, stage flags, and whether or not they use immutable samplers matches
318 //  If so, return true. If not, fill in error_msg and return false
319 bool cvdescriptorset::DescriptorSetLayoutDef::VerifyUpdateConsistency(uint32_t current_binding, uint32_t offset,
320                                                                       uint32_t update_count, const char *type,
321                                                                       const VkDescriptorSet set, std::string *error_msg) const {
322     // Verify consecutive bindings match (if needed)
323     auto orig_binding = current_binding;
324     // Track count of descriptors in the current_bindings that are remaining to be updated
325     auto binding_remaining = GetDescriptorCountFromBinding(current_binding);
326     // First, it's legal to offset beyond your own binding so handle that case
327     //  Really this is just searching for the binding in which the update begins and adjusting offset accordingly
328     while (offset >= binding_remaining) {
329         // Advance to next binding, decrement offset by binding size
330         offset -= binding_remaining;
331         binding_remaining = GetDescriptorCountFromBinding(++current_binding);
332     }
333     binding_remaining -= offset;
334     while (update_count > binding_remaining) {  // While our updates overstep current binding
335         // Verify next consecutive binding matches type, stage flags & immutable sampler use
336         if (!IsNextBindingConsistent(current_binding++)) {
337             std::stringstream error_str;
338             error_str << "Attempting " << type << " descriptor set " << set << " binding #" << orig_binding << " with #"
339                       << update_count
340                       << " descriptors being updated but this update oversteps the bounds of this binding and the next binding is "
341                          "not consistent with current binding so this update is invalid.";
342             *error_msg = error_str.str();
343             return false;
344         }
345         // For sake of this check consider the bindings updated and grab count for next binding
346         update_count -= binding_remaining;
347         binding_remaining = GetDescriptorCountFromBinding(current_binding);
348     }
349     return true;
350 }
351
352 // The DescriptorSetLayout stores the per handle data for a descriptor set layout, and references the common defintion for the
353 // handle invariant portion
354 cvdescriptorset::DescriptorSetLayout::DescriptorSetLayout(const VkDescriptorSetLayoutCreateInfo *p_create_info,
355                                                           const VkDescriptorSetLayout layout)
356     : layout_(layout), layout_destroyed_(false), layout_id_(get_canonical_id(p_create_info)) {}
357
358 // Validate descriptor set layout create info
359 bool cvdescriptorset::DescriptorSetLayout::ValidateCreateInfo(
360     const debug_report_data *report_data, const VkDescriptorSetLayoutCreateInfo *create_info, const bool push_descriptor_ext,
361     const uint32_t max_push_descriptors, const bool descriptor_indexing_ext,
362     const VkPhysicalDeviceDescriptorIndexingFeaturesEXT *descriptor_indexing_features) {
363     bool skip = false;
364     std::unordered_set<uint32_t> bindings;
365     uint64_t total_descriptors = 0;
366
367     const auto *flags_create_info = lvl_find_in_chain<VkDescriptorSetLayoutBindingFlagsCreateInfoEXT>(create_info->pNext);
368
369     const bool push_descriptor_set = !!(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR);
370     if (push_descriptor_set && !push_descriptor_ext) {
371         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
372                         DRAWSTATE_EXTENSION_NOT_ENABLED,
373                         "Attemped to use %s in %s but its required extension %s has not been enabled.\n",
374                         "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR", "VkDescriptorSetLayoutCreateInfo::flags",
375                         VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME);
376     }
377
378     const bool update_after_bind_set = !!(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT);
379     if (update_after_bind_set && !descriptor_indexing_ext) {
380         skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
381                         DRAWSTATE_EXTENSION_NOT_ENABLED,
382                         "Attemped to use %s in %s but its required extension %s has not been enabled.\n",
383                         "VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT", "VkDescriptorSetLayoutCreateInfo::flags",
384                         VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME);
385     }
386
387     auto valid_type = [push_descriptor_set](const VkDescriptorType type) {
388         return !push_descriptor_set ||
389                ((type != VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) && (type != VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC));
390     };
391
392     uint32_t max_binding = 0;
393
394     for (uint32_t i = 0; i < create_info->bindingCount; ++i) {
395         const auto &binding_info = create_info->pBindings[i];
396         max_binding = std::max(max_binding, binding_info.binding);
397
398         if (!bindings.insert(binding_info.binding).second) {
399             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
400                             VALIDATION_ERROR_0500022e, "duplicated binding number in VkDescriptorSetLayoutBinding.");
401         }
402         if (!valid_type(binding_info.descriptorType)) {
403             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
404                             VALIDATION_ERROR_05000230,
405                             "invalid type %s ,for push descriptors in VkDescriptorSetLayoutBinding entry %" PRIu32 ".",
406                             string_VkDescriptorType(binding_info.descriptorType), i);
407         }
408         total_descriptors += binding_info.descriptorCount;
409     }
410
411     if (flags_create_info) {
412         if (flags_create_info->bindingCount != 0 && flags_create_info->bindingCount != create_info->bindingCount) {
413             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
414                             VALIDATION_ERROR_46a01774,
415                             "VkDescriptorSetLayoutCreateInfo::bindingCount (%d) != "
416                             "VkDescriptorSetLayoutBindingFlagsCreateInfoEXT::bindingCount (%d)",
417                             create_info->bindingCount, flags_create_info->bindingCount);
418         }
419
420         if (flags_create_info->bindingCount == create_info->bindingCount) {
421             for (uint32_t i = 0; i < create_info->bindingCount; ++i) {
422                 const auto &binding_info = create_info->pBindings[i];
423
424                 if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT) {
425                     if (!update_after_bind_set) {
426                         skip |=
427                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
428                                     VALIDATION_ERROR_05001770, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
429                     }
430
431                     if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER &&
432                         !descriptor_indexing_features->descriptorBindingUniformBufferUpdateAfterBind) {
433                         skip |=
434                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
435                                     VALIDATION_ERROR_46a0177a, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
436                     }
437                     if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER ||
438                          binding_info.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER ||
439                          binding_info.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) &&
440                         !descriptor_indexing_features->descriptorBindingSampledImageUpdateAfterBind) {
441                         skip |=
442                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
443                                     VALIDATION_ERROR_46a0177c, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
444                     }
445                     if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE &&
446                         !descriptor_indexing_features->descriptorBindingStorageImageUpdateAfterBind) {
447                         skip |=
448                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
449                                     VALIDATION_ERROR_46a0177e, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
450                     }
451                     if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER &&
452                         !descriptor_indexing_features->descriptorBindingStorageBufferUpdateAfterBind) {
453                         skip |=
454                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
455                                     VALIDATION_ERROR_46a01780, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
456                     }
457                     if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER &&
458                         !descriptor_indexing_features->descriptorBindingUniformTexelBufferUpdateAfterBind) {
459                         skip |=
460                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
461                                     VALIDATION_ERROR_46a01782, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
462                     }
463                     if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER &&
464                         !descriptor_indexing_features->descriptorBindingStorageTexelBufferUpdateAfterBind) {
465                         skip |=
466                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
467                                     VALIDATION_ERROR_46a01784, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
468                     }
469                     if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT ||
470                          binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
471                          binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {
472                         skip |=
473                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
474                                     VALIDATION_ERROR_46a01786, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
475                     }
476                 }
477
478                 if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT) {
479                     if (!descriptor_indexing_features->descriptorBindingUpdateUnusedWhilePending) {
480                         skip |=
481                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
482                                     VALIDATION_ERROR_46a01788, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
483                     }
484                 }
485
486                 if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT) {
487                     if (!descriptor_indexing_features->descriptorBindingPartiallyBound) {
488                         skip |=
489                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
490                                     VALIDATION_ERROR_46a0178a, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
491                     }
492                 }
493
494                 if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT) {
495                     if (binding_info.binding != max_binding) {
496                         skip |=
497                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
498                                     VALIDATION_ERROR_46a01778, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
499                     }
500
501                     if (!descriptor_indexing_features->descriptorBindingVariableDescriptorCount) {
502                         skip |=
503                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
504                                     VALIDATION_ERROR_46a0178c, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
505                     }
506                     if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
507                          binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {
508                         skip |=
509                             log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
510                                     VALIDATION_ERROR_46a0178e, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
511                     }
512                 }
513
514                 if (push_descriptor_set &&
515                     (flags_create_info->pBindingFlags[i] &
516                      (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT |
517                       VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT))) {
518                     skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
519                                     VALIDATION_ERROR_46a01776, "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i);
520                 }
521             }
522         }
523     }
524
525     if ((push_descriptor_set) && (total_descriptors > max_push_descriptors)) {
526         const char *undefined = push_descriptor_ext ? "" : " -- undefined";
527         skip |= log_msg(
528             report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, VALIDATION_ERROR_05000232,
529             "for push descriptor, total descriptor count in layout (%" PRIu64
530             ") must not be greater than VkPhysicalDevicePushDescriptorPropertiesKHR::maxPushDescriptors (%" PRIu32 "%s).",
531             total_descriptors, max_push_descriptors, undefined);
532     }
533
534     return skip;
535 }
536
537 cvdescriptorset::AllocateDescriptorSetsData::AllocateDescriptorSetsData(uint32_t count)
538     : required_descriptors_by_type{}, layout_nodes(count, nullptr) {}
539
540 cvdescriptorset::DescriptorSet::DescriptorSet(const VkDescriptorSet set, const VkDescriptorPool pool,
541                                               const std::shared_ptr<DescriptorSetLayout const> &layout, uint32_t variable_count,
542                                               layer_data *dev_data)
543     : some_update_(false),
544       set_(set),
545       pool_state_(nullptr),
546       p_layout_(layout),
547       device_data_(dev_data),
548       limits_(GetPhysDevProperties(dev_data)->properties.limits),
549       variable_count_(variable_count) {
550     pool_state_ = GetDescriptorPoolState(dev_data, pool);
551     // Foreach binding, create default descriptors of given type
552     descriptors_.reserve(p_layout_->GetTotalDescriptorCount());
553     for (uint32_t i = 0; i < p_layout_->GetBindingCount(); ++i) {
554         auto type = p_layout_->GetTypeFromIndex(i);
555         switch (type) {
556             case VK_DESCRIPTOR_TYPE_SAMPLER: {
557                 auto immut_sampler = p_layout_->GetImmutableSamplerPtrFromIndex(i);
558                 for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di) {
559                     if (immut_sampler) {
560                         descriptors_.emplace_back(new SamplerDescriptor(immut_sampler + di));
561                         some_update_ = true;  // Immutable samplers are updated at creation
562                     } else
563                         descriptors_.emplace_back(new SamplerDescriptor(nullptr));
564                 }
565                 break;
566             }
567             case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
568                 auto immut = p_layout_->GetImmutableSamplerPtrFromIndex(i);
569                 for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di) {
570                     if (immut) {
571                         descriptors_.emplace_back(new ImageSamplerDescriptor(immut + di));
572                         some_update_ = true;  // Immutable samplers are updated at creation
573                     } else
574                         descriptors_.emplace_back(new ImageSamplerDescriptor(nullptr));
575                 }
576                 break;
577             }
578             // ImageDescriptors
579             case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
580             case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
581             case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
582                 for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di)
583                     descriptors_.emplace_back(new ImageDescriptor(type));
584                 break;
585             case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
586             case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
587                 for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di)
588                     descriptors_.emplace_back(new TexelDescriptor(type));
589                 break;
590             case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
591             case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
592             case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
593             case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
594                 for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di)
595                     descriptors_.emplace_back(new BufferDescriptor(type));
596                 break;
597             default:
598                 assert(0);  // Bad descriptor type specified
599                 break;
600         }
601     }
602 }
603
604 cvdescriptorset::DescriptorSet::~DescriptorSet() { InvalidateBoundCmdBuffers(); }
605
606 static std::string string_descriptor_req_view_type(descriptor_req req) {
607     std::string result("");
608     for (unsigned i = 0; i <= VK_IMAGE_VIEW_TYPE_END_RANGE; i++) {
609         if (req & (1 << i)) {
610             if (result.size()) result += ", ";
611             result += string_VkImageViewType(VkImageViewType(i));
612         }
613     }
614
615     if (!result.size()) result = "(none)";
616
617     return result;
618 }
619
620 // Is this sets underlying layout compatible with passed in layout according to "Pipeline Layout Compatibility" in spec?
621 bool cvdescriptorset::DescriptorSet::IsCompatible(DescriptorSetLayout const *const layout, std::string *error) const {
622     return layout->IsCompatible(p_layout_.get(), error);
623 }
624
625 // Validate that the state of this set is appropriate for the given bindings and dynamic_offsets at Draw time
626 //  This includes validating that all descriptors in the given bindings are updated,
627 //  that any update buffers are valid, and that any dynamic offsets are within the bounds of their buffers.
628 // Return true if state is acceptable, or false and write an error message into error string
629 bool cvdescriptorset::DescriptorSet::ValidateDrawState(const std::map<uint32_t, descriptor_req> &bindings,
630                                                        const std::vector<uint32_t> &dynamic_offsets, GLOBAL_CB_NODE *cb_node,
631                                                        const char *caller, std::string *error) const {
632     for (auto binding_pair : bindings) {
633         auto binding = binding_pair.first;
634         if (!p_layout_->HasBinding(binding)) {
635             std::stringstream error_str;
636             error_str << "Attempting to validate DrawState for binding #" << binding
637                       << " which is an invalid binding for this descriptor set.";
638             *error = error_str.str();
639             return false;
640         }
641         IndexRange index_range = p_layout_->GetGlobalIndexRangeFromBinding(binding);
642         auto array_idx = 0;  // Track array idx if we're dealing with array descriptors
643
644         if (IsVariableDescriptorCount(binding)) {
645             // Only validate the first N descriptors if it uses variable_count
646             index_range.end = index_range.start + GetVariableDescriptorCount();
647         }
648
649         for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) {
650             if (p_layout_->GetDescriptorBindingFlagsFromBinding(binding) & VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT) {
651                 // Can't validate the descriptor because it may not have been updated,
652                 // or the view could have been destroyed
653                 continue;
654             } else if (!descriptors_[i]->updated) {
655                 std::stringstream error_str;
656                 error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
657                           << " is being used in draw but has not been updated.";
658                 *error = error_str.str();
659                 return false;
660             } else {
661                 auto descriptor_class = descriptors_[i]->GetClass();
662                 if (descriptor_class == GeneralBuffer) {
663                     // Verify that buffers are valid
664                     auto buffer = static_cast<BufferDescriptor *>(descriptors_[i].get())->GetBuffer();
665                     auto buffer_node = GetBufferState(device_data_, buffer);
666                     if (!buffer_node) {
667                         std::stringstream error_str;
668                         error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
669                                   << " references invalid buffer " << buffer << ".";
670                         *error = error_str.str();
671                         return false;
672                     } else if (!buffer_node->sparse) {
673                         for (auto mem_binding : buffer_node->GetBoundMemory()) {
674                             if (!GetMemObjInfo(device_data_, mem_binding)) {
675                                 std::stringstream error_str;
676                                 error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
677                                           << " uses buffer " << buffer << " that references invalid memory " << mem_binding << ".";
678                                 *error = error_str.str();
679                                 return false;
680                             }
681                         }
682                     } else {
683                         // Enqueue sparse resource validation, as these can only be validated at submit time
684                         auto device_data_copy = device_data_;  // Cannot capture members by value, so make capturable copy.
685                         std::function<bool(void)> function = [device_data_copy, caller, buffer_node]() {
686                             return core_validation::ValidateBufferMemoryIsValid(device_data_copy, buffer_node, caller);
687                         };
688                         cb_node->queue_submit_functions.push_back(function);
689                     }
690                     if (descriptors_[i]->IsDynamic()) {
691                         // Validate that dynamic offsets are within the buffer
692                         auto buffer_size = buffer_node->createInfo.size;
693                         auto range = static_cast<BufferDescriptor *>(descriptors_[i].get())->GetRange();
694                         auto desc_offset = static_cast<BufferDescriptor *>(descriptors_[i].get())->GetOffset();
695                         auto dyn_offset = dynamic_offsets[GetDynamicOffsetIndexFromBinding(binding) + array_idx];
696                         if (VK_WHOLE_SIZE == range) {
697                             if ((dyn_offset + desc_offset) > buffer_size) {
698                                 std::stringstream error_str;
699                                 error_str << "Dynamic descriptor in binding #" << binding << " at global descriptor index " << i
700                                           << " uses buffer " << buffer << " with update range of VK_WHOLE_SIZE has dynamic offset "
701                                           << dyn_offset << " combined with offset " << desc_offset
702                                           << " that oversteps the buffer size of " << buffer_size << ".";
703                                 *error = error_str.str();
704                                 return false;
705                             }
706                         } else {
707                             if ((dyn_offset + desc_offset + range) > buffer_size) {
708                                 std::stringstream error_str;
709                                 error_str << "Dynamic descriptor in binding #" << binding << " at global descriptor index " << i
710                                           << " uses buffer " << buffer << " with dynamic offset " << dyn_offset
711                                           << " combined with offset " << desc_offset << " and range " << range
712                                           << " that oversteps the buffer size of " << buffer_size << ".";
713                                 *error = error_str.str();
714                                 return false;
715                             }
716                         }
717                     }
718                 } else if (descriptor_class == ImageSampler || descriptor_class == Image) {
719                     VkImageView image_view;
720                     VkImageLayout image_layout;
721                     if (descriptor_class == ImageSampler) {
722                         image_view = static_cast<ImageSamplerDescriptor *>(descriptors_[i].get())->GetImageView();
723                         image_layout = static_cast<ImageSamplerDescriptor *>(descriptors_[i].get())->GetImageLayout();
724                     } else {
725                         image_view = static_cast<ImageDescriptor *>(descriptors_[i].get())->GetImageView();
726                         image_layout = static_cast<ImageDescriptor *>(descriptors_[i].get())->GetImageLayout();
727                     }
728                     auto reqs = binding_pair.second;
729
730                     auto image_view_state = GetImageViewState(device_data_, image_view);
731                     if (nullptr == image_view_state) {
732                         // Image view must have been destroyed since initial update. Could potentially flag the descriptor
733                         //  as "invalid" (updated = false) at DestroyImageView() time and detect this error at bind time
734                         std::stringstream error_str;
735                         error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
736                                   << " is using imageView " << image_view << " that has been destroyed.";
737                         *error = error_str.str();
738                         return false;
739                     }
740                     auto image_view_ci = image_view_state->create_info;
741
742                     if ((reqs & DESCRIPTOR_REQ_ALL_VIEW_TYPE_BITS) && (~reqs & (1 << image_view_ci.viewType))) {
743                         // bad view type
744                         std::stringstream error_str;
745                         error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
746                                   << " requires an image view of type " << string_descriptor_req_view_type(reqs) << " but got "
747                                   << string_VkImageViewType(image_view_ci.viewType) << ".";
748                         *error = error_str.str();
749                         return false;
750                     }
751
752                     auto image_node = GetImageState(device_data_, image_view_ci.image);
753                     assert(image_node);
754                     // Verify Image Layout
755                     // Copy first mip level into sub_layers and loop over each mip level to verify layout
756                     VkImageSubresourceLayers sub_layers;
757                     sub_layers.aspectMask = image_view_ci.subresourceRange.aspectMask;
758                     sub_layers.baseArrayLayer = image_view_ci.subresourceRange.baseArrayLayer;
759                     sub_layers.layerCount = image_view_ci.subresourceRange.layerCount;
760                     bool hit_error = false;
761                     for (auto cur_level = image_view_ci.subresourceRange.baseMipLevel;
762                          cur_level < image_view_ci.subresourceRange.levelCount; ++cur_level) {
763                         sub_layers.mipLevel = cur_level;
764                         VerifyImageLayout(device_data_, cb_node, image_node, sub_layers, image_layout, VK_IMAGE_LAYOUT_UNDEFINED,
765                                           caller, VALIDATION_ERROR_046002b0, &hit_error);
766                         if (hit_error) {
767                             *error =
768                                 "Image layout specified at vkUpdateDescriptorSets() time doesn't match actual image layout at time "
769                                 "descriptor is used. See previous error callback for specific details.";
770                             return false;
771                         }
772                     }
773                     // Verify Sample counts
774                     if ((reqs & DESCRIPTOR_REQ_SINGLE_SAMPLE) && image_node->createInfo.samples != VK_SAMPLE_COUNT_1_BIT) {
775                         std::stringstream error_str;
776                         error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
777                                   << " requires bound image to have VK_SAMPLE_COUNT_1_BIT but got "
778                                   << string_VkSampleCountFlagBits(image_node->createInfo.samples) << ".";
779                         *error = error_str.str();
780                         return false;
781                     }
782                     if ((reqs & DESCRIPTOR_REQ_MULTI_SAMPLE) && image_node->createInfo.samples == VK_SAMPLE_COUNT_1_BIT) {
783                         std::stringstream error_str;
784                         error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
785                                   << " requires bound image to have multiple samples, but got VK_SAMPLE_COUNT_1_BIT.";
786                         *error = error_str.str();
787                         return false;
788                     }
789                 }
790                 if (descriptor_class == ImageSampler || descriptor_class == PlainSampler) {
791                     // Verify Sampler still valid
792                     VkSampler sampler;
793                     if (descriptor_class == ImageSampler) {
794                         sampler = static_cast<ImageSamplerDescriptor *>(descriptors_[i].get())->GetSampler();
795                     } else {
796                         sampler = static_cast<SamplerDescriptor *>(descriptors_[i].get())->GetSampler();
797                     }
798                     if (!ValidateSampler(sampler, device_data_)) {
799                         std::stringstream error_str;
800                         error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i
801                                   << " is using sampler " << sampler << " that has been destroyed.";
802                         *error = error_str.str();
803                         return false;
804                     }
805                 }
806             }
807         }
808     }
809     return true;
810 }
811
812 // For given bindings, place any update buffers or images into the passed-in unordered_sets
813 uint32_t cvdescriptorset::DescriptorSet::GetStorageUpdates(const std::map<uint32_t, descriptor_req> &bindings,
814                                                            std::unordered_set<VkBuffer> *buffer_set,
815                                                            std::unordered_set<VkImageView> *image_set) const {
816     auto num_updates = 0;
817     for (auto binding_pair : bindings) {
818         auto binding = binding_pair.first;
819         // If a binding doesn't exist, skip it
820         if (!p_layout_->HasBinding(binding)) {
821             continue;
822         }
823         uint32_t start_idx = p_layout_->GetGlobalIndexRangeFromBinding(binding).start;
824         if (descriptors_[start_idx]->IsStorage()) {
825             if (Image == descriptors_[start_idx]->descriptor_class) {
826                 for (uint32_t i = 0; i < p_layout_->GetDescriptorCountFromBinding(binding); ++i) {
827                     if (descriptors_[start_idx + i]->updated) {
828                         image_set->insert(static_cast<ImageDescriptor *>(descriptors_[start_idx + i].get())->GetImageView());
829                         num_updates++;
830                     }
831                 }
832             } else if (TexelBuffer == descriptors_[start_idx]->descriptor_class) {
833                 for (uint32_t i = 0; i < p_layout_->GetDescriptorCountFromBinding(binding); ++i) {
834                     if (descriptors_[start_idx + i]->updated) {
835                         auto bufferview = static_cast<TexelDescriptor *>(descriptors_[start_idx + i].get())->GetBufferView();
836                         auto bv_state = GetBufferViewState(device_data_, bufferview);
837                         if (bv_state) {
838                             buffer_set->insert(bv_state->create_info.buffer);
839                             num_updates++;
840                         }
841                     }
842                 }
843             } else if (GeneralBuffer == descriptors_[start_idx]->descriptor_class) {
844                 for (uint32_t i = 0; i < p_layout_->GetDescriptorCountFromBinding(binding); ++i) {
845                     if (descriptors_[start_idx + i]->updated) {
846                         buffer_set->insert(static_cast<BufferDescriptor *>(descriptors_[start_idx + i].get())->GetBuffer());
847                         num_updates++;
848                     }
849                 }
850             }
851         }
852     }
853     return num_updates;
854 }
855 // Set is being deleted or updates so invalidate all bound cmd buffers
856 void cvdescriptorset::DescriptorSet::InvalidateBoundCmdBuffers() {
857     core_validation::invalidateCommandBuffers(device_data_, cb_bindings, {HandleToUint64(set_), kVulkanObjectTypeDescriptorSet});
858 }
859 // Perform write update in given update struct
860 void cvdescriptorset::DescriptorSet::PerformWriteUpdate(const VkWriteDescriptorSet *update) {
861     // Perform update on a per-binding basis as consecutive updates roll over to next binding
862     auto descriptors_remaining = update->descriptorCount;
863     auto binding_being_updated = update->dstBinding;
864     auto offset = update->dstArrayElement;
865     uint32_t update_index = 0;
866     while (descriptors_remaining) {
867         uint32_t update_count = std::min(descriptors_remaining, GetDescriptorCountFromBinding(binding_being_updated));
868         auto global_idx = p_layout_->GetGlobalIndexRangeFromBinding(binding_being_updated).start + offset;
869         // Loop over the updates for a single binding at a time
870         for (uint32_t di = 0; di < update_count; ++di, ++update_index) {
871             descriptors_[global_idx + di]->WriteUpdate(update, update_index);
872         }
873         // Roll over to next binding in case of consecutive update
874         descriptors_remaining -= update_count;
875         offset = 0;
876         binding_being_updated++;
877     }
878     if (update->descriptorCount) some_update_ = true;
879
880     if (!(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) &
881           (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) {
882         InvalidateBoundCmdBuffers();
883     }
884 }
885 // Validate Copy update
886 bool cvdescriptorset::DescriptorSet::ValidateCopyUpdate(const debug_report_data *report_data, const VkCopyDescriptorSet *update,
887                                                         const DescriptorSet *src_set, UNIQUE_VALIDATION_ERROR_CODE *error_code,
888                                                         std::string *error_msg) {
889     // Verify dst layout still valid
890     if (p_layout_->IsDestroyed()) {
891         *error_code = VALIDATION_ERROR_03207601;
892         string_sprintf(error_msg,
893                        "Cannot call vkUpdateDescriptorSets() to perform copy update on descriptor set dstSet 0x%" PRIxLEAST64
894                        " created with destroyed VkDescriptorSetLayout 0x%" PRIxLEAST64,
895                        HandleToUint64(set_), HandleToUint64(p_layout_->GetDescriptorSetLayout()));
896         return false;
897     }
898
899     // Verify src layout still valid
900     if (src_set->p_layout_->IsDestroyed()) {
901         *error_code = VALIDATION_ERROR_0322d201;
902         string_sprintf(
903             error_msg,
904             "Cannot call vkUpdateDescriptorSets() to perform copy update of dstSet 0x%" PRIxLEAST64
905             " from descriptor set srcSet 0x%" PRIxLEAST64 " created with destroyed VkDescriptorSetLayout 0x%" PRIxLEAST64,
906             HandleToUint64(set_), HandleToUint64(src_set->set_), HandleToUint64(src_set->p_layout_->GetDescriptorSetLayout()));
907         return false;
908     }
909
910     if (!p_layout_->HasBinding(update->dstBinding)) {
911         *error_code = VALIDATION_ERROR_032002b6;
912         std::stringstream error_str;
913         error_str << "DescriptorSet " << set_ << " does not have copy update dest binding of " << update->dstBinding;
914         *error_msg = error_str.str();
915         return false;
916     }
917     if (!src_set->HasBinding(update->srcBinding)) {
918         *error_code = VALIDATION_ERROR_032002b2;
919         std::stringstream error_str;
920         error_str << "DescriptorSet " << set_ << " does not have copy update src binding of " << update->srcBinding;
921         *error_msg = error_str.str();
922         return false;
923     }
924     // Verify idle ds
925     if (in_use.load() &&
926         !(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) &
927           (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) {
928         // TODO : Re-using Free Idle error code, need copy update idle error code
929         *error_code = VALIDATION_ERROR_2860026a;
930         std::stringstream error_str;
931         error_str << "Cannot call vkUpdateDescriptorSets() to perform copy update on descriptor set " << set_
932                   << " that is in use by a command buffer";
933         *error_msg = error_str.str();
934         return false;
935     }
936     // src & dst set bindings are valid
937     // Check bounds of src & dst
938     auto src_start_idx = src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start + update->srcArrayElement;
939     if ((src_start_idx + update->descriptorCount) > src_set->GetTotalDescriptorCount()) {
940         // SRC update out of bounds
941         *error_code = VALIDATION_ERROR_032002b4;
942         std::stringstream error_str;
943         error_str << "Attempting copy update from descriptorSet " << update->srcSet << " binding#" << update->srcBinding
944                   << " with offset index of " << src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start
945                   << " plus update array offset of " << update->srcArrayElement << " and update of " << update->descriptorCount
946                   << " descriptors oversteps total number of descriptors in set: " << src_set->GetTotalDescriptorCount();
947         *error_msg = error_str.str();
948         return false;
949     }
950     auto dst_start_idx = p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement;
951     if ((dst_start_idx + update->descriptorCount) > p_layout_->GetTotalDescriptorCount()) {
952         // DST update out of bounds
953         *error_code = VALIDATION_ERROR_032002b8;
954         std::stringstream error_str;
955         error_str << "Attempting copy update to descriptorSet " << set_ << " binding#" << update->dstBinding
956                   << " with offset index of " << p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start
957                   << " plus update array offset of " << update->dstArrayElement << " and update of " << update->descriptorCount
958                   << " descriptors oversteps total number of descriptors in set: " << p_layout_->GetTotalDescriptorCount();
959         *error_msg = error_str.str();
960         return false;
961     }
962     // Check that types match
963     // TODO : Base default error case going from here is VALIDATION_ERROR_0002b8012ba which covers all consistency issues, need more
964     // fine-grained error codes
965     *error_code = VALIDATION_ERROR_032002ba;
966     auto src_type = src_set->GetTypeFromBinding(update->srcBinding);
967     auto dst_type = p_layout_->GetTypeFromBinding(update->dstBinding);
968     if (src_type != dst_type) {
969         std::stringstream error_str;
970         error_str << "Attempting copy update to descriptorSet " << set_ << " binding #" << update->dstBinding << " with type "
971                   << string_VkDescriptorType(dst_type) << " from descriptorSet " << src_set->GetSet() << " binding #"
972                   << update->srcBinding << " with type " << string_VkDescriptorType(src_type) << ". Types do not match";
973         *error_msg = error_str.str();
974         return false;
975     }
976     // Verify consistency of src & dst bindings if update crosses binding boundaries
977     if ((!src_set->GetLayout()->VerifyUpdateConsistency(update->srcBinding, update->srcArrayElement, update->descriptorCount,
978                                                         "copy update from", src_set->GetSet(), error_msg)) ||
979         (!p_layout_->VerifyUpdateConsistency(update->dstBinding, update->dstArrayElement, update->descriptorCount, "copy update to",
980                                              set_, error_msg))) {
981         return false;
982     }
983
984     if ((src_set->GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT) &&
985         !(GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) {
986         *error_code = VALIDATION_ERROR_03200efc;
987         std::stringstream error_str;
988         error_str << "If pname:srcSet's (" << update->srcSet
989                   << ") layout was created with the "
990                      "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag "
991                      "set, then pname:dstSet's ("
992                   << update->dstSet
993                   << ") layout must: also have been created with the "
994                      "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag set";
995         *error_msg = error_str.str();
996         return false;
997     }
998
999     if (!(src_set->GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT) &&
1000         (GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) {
1001         *error_code = VALIDATION_ERROR_03200efe;
1002         std::stringstream error_str;
1003         error_str << "If pname:srcSet's (" << update->srcSet
1004                   << ") layout was created without the "
1005                      "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag "
1006                      "set, then pname:dstSet's ("
1007                   << update->dstSet
1008                   << ") layout must: also have been created without the "
1009                      "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag set";
1010         *error_msg = error_str.str();
1011         return false;
1012     }
1013
1014     if ((src_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT) &&
1015         !(GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT)) {
1016         *error_code = VALIDATION_ERROR_03200f00;
1017         std::stringstream error_str;
1018         error_str << "If the descriptor pool from which pname:srcSet (" << update->srcSet
1019                   << ") was allocated was created "
1020                      "with the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag "
1021                      "set, then the descriptor pool from which pname:dstSet ("
1022                   << update->dstSet
1023                   << ") was allocated must: "
1024                      "also have been created with the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag set";
1025         *error_msg = error_str.str();
1026         return false;
1027     }
1028
1029     if (!(src_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT) &&
1030         (GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT)) {
1031         *error_code = VALIDATION_ERROR_03200f02;
1032         std::stringstream error_str;
1033         error_str << "If the descriptor pool from which pname:srcSet (" << update->srcSet
1034                   << ") was allocated was created "
1035                      "without the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag "
1036                      "set, then the descriptor pool from which pname:dstSet ("
1037                   << update->dstSet
1038                   << ") was allocated must: "
1039                      "also have been created without the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag set";
1040         *error_msg = error_str.str();
1041         return false;
1042     }
1043
1044     // Update parameters all look good and descriptor updated so verify update contents
1045     if (!VerifyCopyUpdateContents(update, src_set, src_type, src_start_idx, error_code, error_msg)) return false;
1046
1047     // All checks passed so update is good
1048     return true;
1049 }
1050 // Perform Copy update
1051 void cvdescriptorset::DescriptorSet::PerformCopyUpdate(const VkCopyDescriptorSet *update, const DescriptorSet *src_set) {
1052     auto src_start_idx = src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start + update->srcArrayElement;
1053     auto dst_start_idx = p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement;
1054     // Update parameters all look good so perform update
1055     for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1056         auto src = src_set->descriptors_[src_start_idx + di].get();
1057         auto dst = descriptors_[dst_start_idx + di].get();
1058         if (src->updated) {
1059             dst->CopyUpdate(src);
1060             some_update_ = true;
1061         } else {
1062             dst->updated = false;
1063         }
1064     }
1065
1066     if (!(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) &
1067           (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) {
1068         InvalidateBoundCmdBuffers();
1069     }
1070 }
1071
1072 // Bind cb_node to this set and this set to cb_node.
1073 // Prereq: This should be called for a set that has been confirmed to be active for the given cb_node, meaning it's going
1074 //   to be used in a draw by the given cb_node
1075 void cvdescriptorset::DescriptorSet::BindCommandBuffer(GLOBAL_CB_NODE *cb_node,
1076                                                        const std::map<uint32_t, descriptor_req> &binding_req_map) {
1077     // bind cb to this descriptor set
1078     cb_bindings.insert(cb_node);
1079     // Add bindings for descriptor set, the set's pool, and individual objects in the set
1080     cb_node->object_bindings.insert({HandleToUint64(set_), kVulkanObjectTypeDescriptorSet});
1081     pool_state_->cb_bindings.insert(cb_node);
1082     cb_node->object_bindings.insert({HandleToUint64(pool_state_->pool), kVulkanObjectTypeDescriptorPool});
1083     // For the active slots, use set# to look up descriptorSet from boundDescriptorSets, and bind all of that descriptor set's
1084     // resources
1085     for (auto binding_req_pair : binding_req_map) {
1086         auto binding = binding_req_pair.first;
1087         auto range = p_layout_->GetGlobalIndexRangeFromBinding(binding);
1088         for (uint32_t i = range.start; i < range.end; ++i) {
1089             descriptors_[i]->BindCommandBuffer(device_data_, cb_node);
1090         }
1091     }
1092 }
1093 void cvdescriptorset::DescriptorSet::FilterAndTrackOneBindingReq(const BindingReqMap::value_type &binding_req_pair,
1094                                                                  const BindingReqMap &in_req, BindingReqMap *out_req,
1095                                                                  TrackedBindings *bindings) {
1096     assert(out_req);
1097     assert(bindings);
1098     const auto binding = binding_req_pair.first;
1099     // Use insert and look at the boolean ("was inserted") in the returned pair to see if this is a new set member.
1100     // Saves one hash lookup vs. find ... compare w/ end ... insert.
1101     const auto it_bool_pair = bindings->insert(binding);
1102     if (it_bool_pair.second) {
1103         out_req->emplace(binding_req_pair);
1104     }
1105 }
1106 void cvdescriptorset::DescriptorSet::FilterAndTrackOneBindingReq(const BindingReqMap::value_type &binding_req_pair,
1107                                                                  const BindingReqMap &in_req, BindingReqMap *out_req,
1108                                                                  TrackedBindings *bindings, uint32_t limit) {
1109     if (bindings->size() < limit) FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, bindings);
1110 }
1111
1112 void cvdescriptorset::DescriptorSet::FilterAndTrackBindingReqs(GLOBAL_CB_NODE *cb_state, const BindingReqMap &in_req,
1113                                                                BindingReqMap *out_req) {
1114     TrackedBindings &bound = cached_validation_[cb_state].command_binding_and_usage;
1115     if (bound.size() == GetBindingCount()) {
1116         return;  // All bindings are bound, out req is empty
1117     }
1118     for (const auto &binding_req_pair : in_req) {
1119         const auto binding = binding_req_pair.first;
1120         // If a binding doesn't exist, or has already been bound, skip it
1121         if (p_layout_->HasBinding(binding)) {
1122             FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, &bound);
1123         }
1124     }
1125 }
1126
1127 void cvdescriptorset::DescriptorSet::FilterAndTrackBindingReqs(GLOBAL_CB_NODE *cb_state, PIPELINE_STATE *pipeline,
1128                                                                const BindingReqMap &in_req, BindingReqMap *out_req) {
1129     auto &validated = cached_validation_[cb_state];
1130     auto &image_sample_val = validated.image_samplers[pipeline];
1131     auto *const dynamic_buffers = &validated.dynamic_buffers;
1132     auto *const non_dynamic_buffers = &validated.non_dynamic_buffers;
1133     const auto &stats = p_layout_->GetBindingTypeStats();
1134     for (const auto &binding_req_pair : in_req) {
1135         auto binding = binding_req_pair.first;
1136         VkDescriptorSetLayoutBinding const *layout_binding = p_layout_->GetDescriptorSetLayoutBindingPtrFromBinding(binding);
1137         if (!layout_binding) {
1138             continue;
1139         }
1140         // Caching criteria differs per type.
1141         // If image_layout have changed , the image descriptors need to be validated against them.
1142         if ((layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) ||
1143             (layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) {
1144             FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, dynamic_buffers, stats.dynamic_buffer_count);
1145         } else if ((layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) ||
1146                    (layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)) {
1147             FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, non_dynamic_buffers, stats.non_dynamic_buffer_count);
1148         } else {
1149             // This is rather crude, as the changed layouts may not impact the bound descriptors,
1150             // but the simple "versioning" is a simple "dirt" test.
1151             auto &version = image_sample_val[binding];  // Take advantage of default construtor zero initialzing new entries
1152             if (version != cb_state->image_layout_change_count) {
1153                 version = cb_state->image_layout_change_count;
1154                 out_req->emplace(binding_req_pair);
1155             }
1156         }
1157     }
1158 }
1159
1160 cvdescriptorset::SamplerDescriptor::SamplerDescriptor(const VkSampler *immut) : sampler_(VK_NULL_HANDLE), immutable_(false) {
1161     updated = false;
1162     descriptor_class = PlainSampler;
1163     if (immut) {
1164         sampler_ = *immut;
1165         immutable_ = true;
1166         updated = true;
1167     }
1168 }
1169 // Validate given sampler. Currently this only checks to make sure it exists in the samplerMap
1170 bool cvdescriptorset::ValidateSampler(const VkSampler sampler, const layer_data *dev_data) {
1171     return (GetSamplerState(dev_data, sampler) != nullptr);
1172 }
1173
1174 bool cvdescriptorset::ValidateImageUpdate(VkImageView image_view, VkImageLayout image_layout, VkDescriptorType type,
1175                                           const layer_data *dev_data, UNIQUE_VALIDATION_ERROR_CODE *error_code,
1176                                           std::string *error_msg) {
1177     // TODO : Defaulting to 00943 for all cases here. Need to create new error codes for various cases.
1178     *error_code = VALIDATION_ERROR_15c0028c;
1179     auto iv_state = GetImageViewState(dev_data, image_view);
1180     if (!iv_state) {
1181         std::stringstream error_str;
1182         error_str << "Invalid VkImageView: " << image_view;
1183         *error_msg = error_str.str();
1184         return false;
1185     }
1186     // Note that when an imageview is created, we validated that memory is bound so no need to re-check here
1187     // Validate that imageLayout is compatible with aspect_mask and image format
1188     //  and validate that image usage bits are correct for given usage
1189     VkImageAspectFlags aspect_mask = iv_state->create_info.subresourceRange.aspectMask;
1190     VkImage image = iv_state->create_info.image;
1191     VkFormat format = VK_FORMAT_MAX_ENUM;
1192     VkImageUsageFlags usage = 0;
1193     auto image_node = GetImageState(dev_data, image);
1194     if (image_node) {
1195         format = image_node->createInfo.format;
1196         usage = image_node->createInfo.usage;
1197         // Validate that memory is bound to image
1198         // TODO: This should have its own valid usage id apart from 2524 which is from CreateImageView case. The only
1199         //  the error here occurs is if memory bound to a created imageView has been freed.
1200         if (ValidateMemoryIsBoundToImage(dev_data, image_node, "vkUpdateDescriptorSets()", VALIDATION_ERROR_0ac007f8)) {
1201             *error_code = VALIDATION_ERROR_0ac007f8;
1202             *error_msg = "No memory bound to image.";
1203             return false;
1204         }
1205
1206         // KHR_maintenance1 allows rendering into 2D or 2DArray views which slice a 3D image,
1207         // but not binding them to descriptor sets.
1208         if (image_node->createInfo.imageType == VK_IMAGE_TYPE_3D &&
1209             (iv_state->create_info.viewType == VK_IMAGE_VIEW_TYPE_2D ||
1210              iv_state->create_info.viewType == VK_IMAGE_VIEW_TYPE_2D_ARRAY)) {
1211             *error_code = VALIDATION_ERROR_046002ae;
1212             *error_msg = "ImageView must not be a 2D or 2DArray view of a 3D image";
1213             return false;
1214         }
1215     }
1216     // First validate that format and layout are compatible
1217     if (format == VK_FORMAT_MAX_ENUM) {
1218         std::stringstream error_str;
1219         error_str << "Invalid image (" << image << ") in imageView (" << image_view << ").";
1220         *error_msg = error_str.str();
1221         return false;
1222     }
1223     // TODO : The various image aspect and format checks here are based on general spec language in 11.5 Image Views section under
1224     // vkCreateImageView(). What's the best way to create unique id for these cases?
1225     bool ds = FormatIsDepthOrStencil(format);
1226     switch (image_layout) {
1227         case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
1228             // Only Color bit must be set
1229             if ((aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) != VK_IMAGE_ASPECT_COLOR_BIT) {
1230                 std::stringstream error_str;
1231                 error_str
1232                     << "ImageView (" << image_view
1233                     << ") uses layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL but does not have VK_IMAGE_ASPECT_COLOR_BIT set.";
1234                 *error_msg = error_str.str();
1235                 return false;
1236             }
1237             // format must NOT be DS
1238             if (ds) {
1239                 std::stringstream error_str;
1240                 error_str << "ImageView (" << image_view
1241                           << ") uses layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL but the image format is "
1242                           << string_VkFormat(format) << " which is not a color format.";
1243                 *error_msg = error_str.str();
1244                 return false;
1245             }
1246             break;
1247         case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:
1248         case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL:
1249             // Depth or stencil bit must be set, but both must NOT be set
1250             if (aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1251                 if (aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1252                     // both  must NOT be set
1253                     std::stringstream error_str;
1254                     error_str << "ImageView (" << image_view << ") has both STENCIL and DEPTH aspects set";
1255                     *error_msg = error_str.str();
1256                     return false;
1257                 }
1258             } else if (!(aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT)) {
1259                 // Neither were set
1260                 std::stringstream error_str;
1261                 error_str << "ImageView (" << image_view << ") has layout " << string_VkImageLayout(image_layout)
1262                           << " but does not have STENCIL or DEPTH aspects set";
1263                 *error_msg = error_str.str();
1264                 return false;
1265             }
1266             // format must be DS
1267             if (!ds) {
1268                 std::stringstream error_str;
1269                 error_str << "ImageView (" << image_view << ") has layout " << string_VkImageLayout(image_layout)
1270                           << " but the image format is " << string_VkFormat(format) << " which is not a depth/stencil format.";
1271                 *error_msg = error_str.str();
1272                 return false;
1273             }
1274             break;
1275         default:
1276             // For other layouts if the source is depth/stencil image, both aspect bits must not be set
1277             if (ds) {
1278                 if (aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) {
1279                     if (aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) {
1280                         // both  must NOT be set
1281                         std::stringstream error_str;
1282                         error_str << "ImageView (" << image_view << ") has layout " << string_VkImageLayout(image_layout)
1283                                   << " and is using depth/stencil image of format " << string_VkFormat(format)
1284                                   << " but it has both STENCIL and DEPTH aspects set, which is illegal. When using a depth/stencil "
1285                                      "image in a descriptor set, please only set either VK_IMAGE_ASPECT_DEPTH_BIT or "
1286                                      "VK_IMAGE_ASPECT_STENCIL_BIT depending on whether it will be used for depth reads or stencil "
1287                                      "reads respectively.";
1288                         *error_msg = error_str.str();
1289                         return false;
1290                     }
1291                 }
1292             }
1293             break;
1294     }
1295     // Now validate that usage flags are correctly set for given type of update
1296     //  As we're switching per-type, if any type has specific layout requirements, check those here as well
1297     // TODO : The various image usage bit requirements are in general spec language for VkImageUsageFlags bit block in 11.3 Images
1298     // under vkCreateImage()
1299     // TODO : Need to also validate case VALIDATION_ERROR_15c002a0 where STORAGE_IMAGE & INPUT_ATTACH types must have been created
1300     // with identify swizzle
1301     std::string error_usage_bit;
1302     switch (type) {
1303         case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
1304         case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
1305             if (!(usage & VK_IMAGE_USAGE_SAMPLED_BIT)) {
1306                 error_usage_bit = "VK_IMAGE_USAGE_SAMPLED_BIT";
1307             }
1308             break;
1309         }
1310         case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
1311             if (!(usage & VK_IMAGE_USAGE_STORAGE_BIT)) {
1312                 error_usage_bit = "VK_IMAGE_USAGE_STORAGE_BIT";
1313             } else if (VK_IMAGE_LAYOUT_GENERAL != image_layout) {
1314                 std::stringstream error_str;
1315                 // TODO : Need to create custom enum error codes for these cases
1316                 if (image_node->shared_presentable) {
1317                     if (VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR != image_layout) {
1318                         error_str << "ImageView (" << image_view
1319                                   << ") of VK_DESCRIPTOR_TYPE_STORAGE_IMAGE type with a front-buffered image is being updated with "
1320                                      "layout "
1321                                   << string_VkImageLayout(image_layout)
1322                                   << " but according to spec section 13.1 Descriptor Types, 'Front-buffered images that report "
1323                                      "support for VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT must be in the "
1324                                      "VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR layout.'";
1325                         *error_msg = error_str.str();
1326                         return false;
1327                     }
1328                 } else if (VK_IMAGE_LAYOUT_GENERAL != image_layout) {
1329                     error_str << "ImageView (" << image_view
1330                               << ") of VK_DESCRIPTOR_TYPE_STORAGE_IMAGE type is being updated with layout "
1331                               << string_VkImageLayout(image_layout)
1332                               << " but according to spec section 13.1 Descriptor Types, 'Load and store operations on storage "
1333                                  "images can only be done on images in VK_IMAGE_LAYOUT_GENERAL layout.'";
1334                     *error_msg = error_str.str();
1335                     return false;
1336                 }
1337             }
1338             break;
1339         }
1340         case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: {
1341             if (!(usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
1342                 error_usage_bit = "VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT";
1343             }
1344             break;
1345         }
1346         default:
1347             break;
1348     }
1349     if (!error_usage_bit.empty()) {
1350         std::stringstream error_str;
1351         error_str << "ImageView (" << image_view << ") with usage mask 0x" << usage
1352                   << " being used for a descriptor update of type " << string_VkDescriptorType(type) << " does not have "
1353                   << error_usage_bit << " set.";
1354         *error_msg = error_str.str();
1355         return false;
1356     }
1357     return true;
1358 }
1359
1360 void cvdescriptorset::SamplerDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) {
1361     sampler_ = update->pImageInfo[index].sampler;
1362     updated = true;
1363 }
1364
1365 void cvdescriptorset::SamplerDescriptor::CopyUpdate(const Descriptor *src) {
1366     if (!immutable_) {
1367         auto update_sampler = static_cast<const SamplerDescriptor *>(src)->sampler_;
1368         sampler_ = update_sampler;
1369     }
1370     updated = true;
1371 }
1372
1373 void cvdescriptorset::SamplerDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) {
1374     if (!immutable_) {
1375         auto sampler_state = GetSamplerState(dev_data, sampler_);
1376         if (sampler_state) core_validation::AddCommandBufferBindingSampler(cb_node, sampler_state);
1377     }
1378 }
1379
1380 cvdescriptorset::ImageSamplerDescriptor::ImageSamplerDescriptor(const VkSampler *immut)
1381     : sampler_(VK_NULL_HANDLE), immutable_(false), image_view_(VK_NULL_HANDLE), image_layout_(VK_IMAGE_LAYOUT_UNDEFINED) {
1382     updated = false;
1383     descriptor_class = ImageSampler;
1384     if (immut) {
1385         sampler_ = *immut;
1386         immutable_ = true;
1387     }
1388 }
1389
1390 void cvdescriptorset::ImageSamplerDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) {
1391     updated = true;
1392     const auto &image_info = update->pImageInfo[index];
1393     sampler_ = image_info.sampler;
1394     image_view_ = image_info.imageView;
1395     image_layout_ = image_info.imageLayout;
1396 }
1397
1398 void cvdescriptorset::ImageSamplerDescriptor::CopyUpdate(const Descriptor *src) {
1399     if (!immutable_) {
1400         auto update_sampler = static_cast<const ImageSamplerDescriptor *>(src)->sampler_;
1401         sampler_ = update_sampler;
1402     }
1403     auto image_view = static_cast<const ImageSamplerDescriptor *>(src)->image_view_;
1404     auto image_layout = static_cast<const ImageSamplerDescriptor *>(src)->image_layout_;
1405     updated = true;
1406     image_view_ = image_view;
1407     image_layout_ = image_layout;
1408 }
1409
1410 void cvdescriptorset::ImageSamplerDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) {
1411     // First add binding for any non-immutable sampler
1412     if (!immutable_) {
1413         auto sampler_state = GetSamplerState(dev_data, sampler_);
1414         if (sampler_state) core_validation::AddCommandBufferBindingSampler(cb_node, sampler_state);
1415     }
1416     // Add binding for image
1417     auto iv_state = GetImageViewState(dev_data, image_view_);
1418     if (iv_state) {
1419         core_validation::AddCommandBufferBindingImageView(dev_data, cb_node, iv_state);
1420     }
1421 }
1422
1423 cvdescriptorset::ImageDescriptor::ImageDescriptor(const VkDescriptorType type)
1424     : storage_(false), image_view_(VK_NULL_HANDLE), image_layout_(VK_IMAGE_LAYOUT_UNDEFINED) {
1425     updated = false;
1426     descriptor_class = Image;
1427     if (VK_DESCRIPTOR_TYPE_STORAGE_IMAGE == type) storage_ = true;
1428 }
1429
1430 void cvdescriptorset::ImageDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) {
1431     updated = true;
1432     const auto &image_info = update->pImageInfo[index];
1433     image_view_ = image_info.imageView;
1434     image_layout_ = image_info.imageLayout;
1435 }
1436
1437 void cvdescriptorset::ImageDescriptor::CopyUpdate(const Descriptor *src) {
1438     auto image_view = static_cast<const ImageDescriptor *>(src)->image_view_;
1439     auto image_layout = static_cast<const ImageDescriptor *>(src)->image_layout_;
1440     updated = true;
1441     image_view_ = image_view;
1442     image_layout_ = image_layout;
1443 }
1444
1445 void cvdescriptorset::ImageDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) {
1446     // Add binding for image
1447     auto iv_state = GetImageViewState(dev_data, image_view_);
1448     if (iv_state) {
1449         core_validation::AddCommandBufferBindingImageView(dev_data, cb_node, iv_state);
1450     }
1451 }
1452
1453 cvdescriptorset::BufferDescriptor::BufferDescriptor(const VkDescriptorType type)
1454     : storage_(false), dynamic_(false), buffer_(VK_NULL_HANDLE), offset_(0), range_(0) {
1455     updated = false;
1456     descriptor_class = GeneralBuffer;
1457     if (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC == type) {
1458         dynamic_ = true;
1459     } else if (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER == type) {
1460         storage_ = true;
1461     } else if (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC == type) {
1462         dynamic_ = true;
1463         storage_ = true;
1464     }
1465 }
1466 void cvdescriptorset::BufferDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) {
1467     updated = true;
1468     const auto &buffer_info = update->pBufferInfo[index];
1469     buffer_ = buffer_info.buffer;
1470     offset_ = buffer_info.offset;
1471     range_ = buffer_info.range;
1472 }
1473
1474 void cvdescriptorset::BufferDescriptor::CopyUpdate(const Descriptor *src) {
1475     auto buff_desc = static_cast<const BufferDescriptor *>(src);
1476     updated = true;
1477     buffer_ = buff_desc->buffer_;
1478     offset_ = buff_desc->offset_;
1479     range_ = buff_desc->range_;
1480 }
1481
1482 void cvdescriptorset::BufferDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) {
1483     auto buffer_node = GetBufferState(dev_data, buffer_);
1484     if (buffer_node) core_validation::AddCommandBufferBindingBuffer(dev_data, cb_node, buffer_node);
1485 }
1486
1487 cvdescriptorset::TexelDescriptor::TexelDescriptor(const VkDescriptorType type) : buffer_view_(VK_NULL_HANDLE), storage_(false) {
1488     updated = false;
1489     descriptor_class = TexelBuffer;
1490     if (VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER == type) storage_ = true;
1491 }
1492
1493 void cvdescriptorset::TexelDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) {
1494     updated = true;
1495     buffer_view_ = update->pTexelBufferView[index];
1496 }
1497
1498 void cvdescriptorset::TexelDescriptor::CopyUpdate(const Descriptor *src) {
1499     updated = true;
1500     buffer_view_ = static_cast<const TexelDescriptor *>(src)->buffer_view_;
1501 }
1502
1503 void cvdescriptorset::TexelDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) {
1504     auto bv_state = GetBufferViewState(dev_data, buffer_view_);
1505     if (bv_state) {
1506         core_validation::AddCommandBufferBindingBufferView(dev_data, cb_node, bv_state);
1507     }
1508 }
1509
1510 // This is a helper function that iterates over a set of Write and Copy updates, pulls the DescriptorSet* for updated
1511 //  sets, and then calls their respective Validate[Write|Copy]Update functions.
1512 // If the update hits an issue for which the callback returns "true", meaning that the call down the chain should
1513 //  be skipped, then true is returned.
1514 // If there is no issue with the update, then false is returned.
1515 bool cvdescriptorset::ValidateUpdateDescriptorSets(const debug_report_data *report_data, const layer_data *dev_data,
1516                                                    uint32_t write_count, const VkWriteDescriptorSet *p_wds, uint32_t copy_count,
1517                                                    const VkCopyDescriptorSet *p_cds) {
1518     bool skip = false;
1519     // Validate Write updates
1520     for (uint32_t i = 0; i < write_count; i++) {
1521         auto dest_set = p_wds[i].dstSet;
1522         auto set_node = core_validation::GetSetNode(dev_data, dest_set);
1523         if (!set_node) {
1524             skip |=
1525                 log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
1526                         HandleToUint64(dest_set), DRAWSTATE_INVALID_DESCRIPTOR_SET,
1527                         "Cannot call vkUpdateDescriptorSets() on descriptor set 0x%" PRIxLEAST64 " that has not been allocated.",
1528                         HandleToUint64(dest_set));
1529         } else {
1530             UNIQUE_VALIDATION_ERROR_CODE error_code;
1531             std::string error_str;
1532             if (!set_node->ValidateWriteUpdate(report_data, &p_wds[i], &error_code, &error_str)) {
1533                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
1534                                 HandleToUint64(dest_set), error_code,
1535                                 "vkUpdateDescriptorSets() failed write update validation for Descriptor Set 0x%" PRIx64
1536                                 " with error: %s.",
1537                                 HandleToUint64(dest_set), error_str.c_str());
1538             }
1539         }
1540     }
1541     // Now validate copy updates
1542     for (uint32_t i = 0; i < copy_count; ++i) {
1543         auto dst_set = p_cds[i].dstSet;
1544         auto src_set = p_cds[i].srcSet;
1545         auto src_node = core_validation::GetSetNode(dev_data, src_set);
1546         auto dst_node = core_validation::GetSetNode(dev_data, dst_set);
1547         // Object_tracker verifies that src & dest descriptor set are valid
1548         assert(src_node);
1549         assert(dst_node);
1550         UNIQUE_VALIDATION_ERROR_CODE error_code;
1551         std::string error_str;
1552         if (!dst_node->ValidateCopyUpdate(report_data, &p_cds[i], src_node, &error_code, &error_str)) {
1553             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT,
1554                             HandleToUint64(dst_set), error_code,
1555                             "vkUpdateDescriptorSets() failed copy update from Descriptor Set 0x%" PRIx64
1556                             " to Descriptor Set 0x%" PRIx64 " with error: %s.",
1557                             HandleToUint64(src_set), HandleToUint64(dst_set), error_str.c_str());
1558         }
1559     }
1560     return skip;
1561 }
1562 // This is a helper function that iterates over a set of Write and Copy updates, pulls the DescriptorSet* for updated
1563 //  sets, and then calls their respective Perform[Write|Copy]Update functions.
1564 // Prerequisite : ValidateUpdateDescriptorSets() should be called and return "false" prior to calling PerformUpdateDescriptorSets()
1565 //  with the same set of updates.
1566 // This is split from the validate code to allow validation prior to calling down the chain, and then update after
1567 //  calling down the chain.
1568 void cvdescriptorset::PerformUpdateDescriptorSets(const layer_data *dev_data, uint32_t write_count,
1569                                                   const VkWriteDescriptorSet *p_wds, uint32_t copy_count,
1570                                                   const VkCopyDescriptorSet *p_cds) {
1571     // Write updates first
1572     uint32_t i = 0;
1573     for (i = 0; i < write_count; ++i) {
1574         auto dest_set = p_wds[i].dstSet;
1575         auto set_node = core_validation::GetSetNode(dev_data, dest_set);
1576         if (set_node) {
1577             set_node->PerformWriteUpdate(&p_wds[i]);
1578         }
1579     }
1580     // Now copy updates
1581     for (i = 0; i < copy_count; ++i) {
1582         auto dst_set = p_cds[i].dstSet;
1583         auto src_set = p_cds[i].srcSet;
1584         auto src_node = core_validation::GetSetNode(dev_data, src_set);
1585         auto dst_node = core_validation::GetSetNode(dev_data, dst_set);
1586         if (src_node && dst_node) {
1587             dst_node->PerformCopyUpdate(&p_cds[i], src_node);
1588         }
1589     }
1590 }
1591 // This helper function carries out the state updates for descriptor updates peformed via update templates. It basically collects
1592 // data and leverages the PerformUpdateDescriptor helper functions to do this.
1593 void cvdescriptorset::PerformUpdateDescriptorSetsWithTemplateKHR(layer_data *device_data, VkDescriptorSet descriptorSet,
1594                                                                  std::unique_ptr<TEMPLATE_STATE> const &template_state,
1595                                                                  const void *pData) {
1596     auto const &create_info = template_state->create_info;
1597
1598     // Create a vector of write structs
1599     std::vector<VkWriteDescriptorSet> desc_writes;
1600     auto layout_obj = GetDescriptorSetLayout(device_data, create_info.descriptorSetLayout);
1601
1602     // Create a WriteDescriptorSet struct for each template update entry
1603     for (uint32_t i = 0; i < create_info.descriptorUpdateEntryCount; i++) {
1604         auto binding_count = layout_obj->GetDescriptorCountFromBinding(create_info.pDescriptorUpdateEntries[i].dstBinding);
1605         auto binding_being_updated = create_info.pDescriptorUpdateEntries[i].dstBinding;
1606         auto dst_array_element = create_info.pDescriptorUpdateEntries[i].dstArrayElement;
1607
1608         desc_writes.reserve(desc_writes.size() + create_info.pDescriptorUpdateEntries[i].descriptorCount);
1609         for (uint32_t j = 0; j < create_info.pDescriptorUpdateEntries[i].descriptorCount; j++) {
1610             desc_writes.emplace_back();
1611             auto &write_entry = desc_writes.back();
1612
1613             size_t offset = create_info.pDescriptorUpdateEntries[i].offset + j * create_info.pDescriptorUpdateEntries[i].stride;
1614             char *update_entry = (char *)(pData) + offset;
1615
1616             if (dst_array_element >= binding_count) {
1617                 dst_array_element = 0;
1618                 binding_being_updated = layout_obj->GetNextValidBinding(binding_being_updated);
1619             }
1620
1621             write_entry.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1622             write_entry.pNext = NULL;
1623             write_entry.dstSet = descriptorSet;
1624             write_entry.dstBinding = binding_being_updated;
1625             write_entry.dstArrayElement = dst_array_element;
1626             write_entry.descriptorCount = 1;
1627             write_entry.descriptorType = create_info.pDescriptorUpdateEntries[i].descriptorType;
1628
1629             switch (create_info.pDescriptorUpdateEntries[i].descriptorType) {
1630                 case VK_DESCRIPTOR_TYPE_SAMPLER:
1631                 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
1632                 case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
1633                 case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
1634                 case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
1635                     write_entry.pImageInfo = reinterpret_cast<VkDescriptorImageInfo *>(update_entry);
1636                     break;
1637
1638                 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
1639                 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
1640                 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
1641                 case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
1642                     write_entry.pBufferInfo = reinterpret_cast<VkDescriptorBufferInfo *>(update_entry);
1643                     break;
1644
1645                 case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
1646                 case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
1647                     write_entry.pTexelBufferView = reinterpret_cast<VkBufferView *>(update_entry);
1648                     break;
1649                 default:
1650                     assert(0);
1651                     break;
1652             }
1653             dst_array_element++;
1654         }
1655     }
1656     PerformUpdateDescriptorSets(device_data, static_cast<uint32_t>(desc_writes.size()), desc_writes.data(), 0, NULL);
1657 }
1658 // Validate the state for a given write update but don't actually perform the update
1659 //  If an error would occur for this update, return false and fill in details in error_msg string
1660 bool cvdescriptorset::DescriptorSet::ValidateWriteUpdate(const debug_report_data *report_data, const VkWriteDescriptorSet *update,
1661                                                          UNIQUE_VALIDATION_ERROR_CODE *error_code, std::string *error_msg) {
1662     // Verify dst layout still valid
1663     if (p_layout_->IsDestroyed()) {
1664         *error_code = VALIDATION_ERROR_15c00280;
1665         string_sprintf(error_msg,
1666                        "Cannot call vkUpdateDescriptorSets() to perform write update on descriptor set 0x%" PRIxLEAST64
1667                        " created with destroyed VkDescriptorSetLayout 0x%" PRIxLEAST64,
1668                        HandleToUint64(set_), HandleToUint64(p_layout_->GetDescriptorSetLayout()));
1669         return false;
1670     }
1671     // Verify dst binding exists
1672     if (!p_layout_->HasBinding(update->dstBinding)) {
1673         *error_code = VALIDATION_ERROR_15c00276;
1674         std::stringstream error_str;
1675         error_str << "DescriptorSet " << set_ << " does not have binding " << update->dstBinding;
1676         *error_msg = error_str.str();
1677         return false;
1678     } else {
1679         // Make sure binding isn't empty
1680         if (0 == p_layout_->GetDescriptorCountFromBinding(update->dstBinding)) {
1681             *error_code = VALIDATION_ERROR_15c00278;
1682             std::stringstream error_str;
1683             error_str << "DescriptorSet " << set_ << " cannot updated binding " << update->dstBinding << " that has 0 descriptors";
1684             *error_msg = error_str.str();
1685             return false;
1686         }
1687     }
1688     // Verify idle ds
1689     if (in_use.load() &&
1690         !(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) &
1691           (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) {
1692         // TODO : Re-using Free Idle error code, need write update idle error code
1693         *error_code = VALIDATION_ERROR_2860026a;
1694         std::stringstream error_str;
1695         error_str << "Cannot call vkUpdateDescriptorSets() to perform write update on descriptor set " << set_
1696                   << " that is in use by a command buffer";
1697         *error_msg = error_str.str();
1698         return false;
1699     }
1700     // We know that binding is valid, verify update and do update on each descriptor
1701     auto start_idx = p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement;
1702     auto type = p_layout_->GetTypeFromBinding(update->dstBinding);
1703     if (type != update->descriptorType) {
1704         *error_code = VALIDATION_ERROR_15c0027e;
1705         std::stringstream error_str;
1706         error_str << "Attempting write update to descriptor set " << set_ << " binding #" << update->dstBinding << " with type "
1707                   << string_VkDescriptorType(type) << " but update type is " << string_VkDescriptorType(update->descriptorType);
1708         *error_msg = error_str.str();
1709         return false;
1710     }
1711     if (update->descriptorCount > (descriptors_.size() - start_idx)) {
1712         *error_code = VALIDATION_ERROR_15c00282;
1713         std::stringstream error_str;
1714         error_str << "Attempting write update to descriptor set " << set_ << " binding #" << update->dstBinding << " with "
1715                   << descriptors_.size() - start_idx
1716                   << " descriptors in that binding and all successive bindings of the set, but update of "
1717                   << update->descriptorCount << " descriptors combined with update array element offset of "
1718                   << update->dstArrayElement << " oversteps the available number of consecutive descriptors";
1719         *error_msg = error_str.str();
1720         return false;
1721     }
1722     // Verify consecutive bindings match (if needed)
1723     if (!p_layout_->VerifyUpdateConsistency(update->dstBinding, update->dstArrayElement, update->descriptorCount, "write update to",
1724                                             set_, error_msg)) {
1725         // TODO : Should break out "consecutive binding updates" language into valid usage statements
1726         *error_code = VALIDATION_ERROR_15c00282;
1727         return false;
1728     }
1729     // Update is within bounds and consistent so last step is to validate update contents
1730     if (!VerifyWriteUpdateContents(update, start_idx, error_code, error_msg)) {
1731         std::stringstream error_str;
1732         error_str << "Write update to descriptor in set " << set_ << " binding #" << update->dstBinding
1733                   << " failed with error message: " << error_msg->c_str();
1734         *error_msg = error_str.str();
1735         return false;
1736     }
1737     // All checks passed, update is clean
1738     return true;
1739 }
1740 // For the given buffer, verify that its creation parameters are appropriate for the given type
1741 //  If there's an error, update the error_msg string with details and return false, else return true
1742 bool cvdescriptorset::DescriptorSet::ValidateBufferUsage(BUFFER_STATE const *buffer_node, VkDescriptorType type,
1743                                                          UNIQUE_VALIDATION_ERROR_CODE *error_code, std::string *error_msg) const {
1744     // Verify that usage bits set correctly for given type
1745     auto usage = buffer_node->createInfo.usage;
1746     std::string error_usage_bit;
1747     switch (type) {
1748         case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
1749             if (!(usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT)) {
1750                 *error_code = VALIDATION_ERROR_15c0029c;
1751                 error_usage_bit = "VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT";
1752             }
1753             break;
1754         case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
1755             if (!(usage & VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT)) {
1756                 *error_code = VALIDATION_ERROR_15c0029e;
1757                 error_usage_bit = "VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT";
1758             }
1759             break;
1760         case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
1761         case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
1762             if (!(usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)) {
1763                 *error_code = VALIDATION_ERROR_15c00292;
1764                 error_usage_bit = "VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT";
1765             }
1766             break;
1767         case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
1768         case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
1769             if (!(usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)) {
1770                 *error_code = VALIDATION_ERROR_15c00296;
1771                 error_usage_bit = "VK_BUFFER_USAGE_STORAGE_BUFFER_BIT";
1772             }
1773             break;
1774         default:
1775             break;
1776     }
1777     if (!error_usage_bit.empty()) {
1778         std::stringstream error_str;
1779         error_str << "Buffer (" << buffer_node->buffer << ") with usage mask 0x" << usage
1780                   << " being used for a descriptor update of type " << string_VkDescriptorType(type) << " does not have "
1781                   << error_usage_bit << " set.";
1782         *error_msg = error_str.str();
1783         return false;
1784     }
1785     return true;
1786 }
1787 // For buffer descriptor updates, verify the buffer usage and VkDescriptorBufferInfo struct which includes:
1788 //  1. buffer is valid
1789 //  2. buffer was created with correct usage flags
1790 //  3. offset is less than buffer size
1791 //  4. range is either VK_WHOLE_SIZE or falls in (0, (buffer size - offset)]
1792 //  5. range and offset are within the device's limits
1793 // If there's an error, update the error_msg string with details and return false, else return true
1794 bool cvdescriptorset::DescriptorSet::ValidateBufferUpdate(VkDescriptorBufferInfo const *buffer_info, VkDescriptorType type,
1795                                                           UNIQUE_VALIDATION_ERROR_CODE *error_code, std::string *error_msg) const {
1796     // First make sure that buffer is valid
1797     auto buffer_node = GetBufferState(device_data_, buffer_info->buffer);
1798     // Any invalid buffer should already be caught by object_tracker
1799     assert(buffer_node);
1800     if (ValidateMemoryIsBoundToBuffer(device_data_, buffer_node, "vkUpdateDescriptorSets()", VALIDATION_ERROR_15c00294)) {
1801         *error_code = VALIDATION_ERROR_15c00294;
1802         *error_msg = "No memory bound to buffer.";
1803         return false;
1804     }
1805     // Verify usage bits
1806     if (!ValidateBufferUsage(buffer_node, type, error_code, error_msg)) {
1807         // error_msg will have been updated by ValidateBufferUsage()
1808         return false;
1809     }
1810     // offset must be less than buffer size
1811     if (buffer_info->offset >= buffer_node->createInfo.size) {
1812         *error_code = VALIDATION_ERROR_044002a8;
1813         std::stringstream error_str;
1814         error_str << "VkDescriptorBufferInfo offset of " << buffer_info->offset << " is greater than or equal to buffer "
1815                   << buffer_node->buffer << " size of " << buffer_node->createInfo.size;
1816         *error_msg = error_str.str();
1817         return false;
1818     }
1819     if (buffer_info->range != VK_WHOLE_SIZE) {
1820         // Range must be VK_WHOLE_SIZE or > 0
1821         if (!buffer_info->range) {
1822             *error_code = VALIDATION_ERROR_044002aa;
1823             std::stringstream error_str;
1824             error_str << "VkDescriptorBufferInfo range is not VK_WHOLE_SIZE and is zero, which is not allowed.";
1825             *error_msg = error_str.str();
1826             return false;
1827         }
1828         // Range must be VK_WHOLE_SIZE or <= (buffer size - offset)
1829         if (buffer_info->range > (buffer_node->createInfo.size - buffer_info->offset)) {
1830             *error_code = VALIDATION_ERROR_044002ac;
1831             std::stringstream error_str;
1832             error_str << "VkDescriptorBufferInfo range is " << buffer_info->range << " which is greater than buffer size ("
1833                       << buffer_node->createInfo.size << ") minus requested offset of " << buffer_info->offset;
1834             *error_msg = error_str.str();
1835             return false;
1836         }
1837     }
1838     // Check buffer update sizes against device limits
1839     if (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER == type || VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC == type) {
1840         auto max_ub_range = limits_.maxUniformBufferRange;
1841         // TODO : If range is WHOLE_SIZE, need to make sure underlying buffer size doesn't exceed device max
1842         if (buffer_info->range != VK_WHOLE_SIZE && buffer_info->range > max_ub_range) {
1843             *error_code = VALIDATION_ERROR_15c00298;
1844             std::stringstream error_str;
1845             error_str << "VkDescriptorBufferInfo range is " << buffer_info->range
1846                       << " which is greater than this device's maxUniformBufferRange (" << max_ub_range << ")";
1847             *error_msg = error_str.str();
1848             return false;
1849         }
1850     } else if (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER == type || VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC == type) {
1851         auto max_sb_range = limits_.maxStorageBufferRange;
1852         // TODO : If range is WHOLE_SIZE, need to make sure underlying buffer size doesn't exceed device max
1853         if (buffer_info->range != VK_WHOLE_SIZE && buffer_info->range > max_sb_range) {
1854             *error_code = VALIDATION_ERROR_15c0029a;
1855             std::stringstream error_str;
1856             error_str << "VkDescriptorBufferInfo range is " << buffer_info->range
1857                       << " which is greater than this device's maxStorageBufferRange (" << max_sb_range << ")";
1858             *error_msg = error_str.str();
1859             return false;
1860         }
1861     }
1862     return true;
1863 }
1864
1865 // Verify that the contents of the update are ok, but don't perform actual update
1866 bool cvdescriptorset::DescriptorSet::VerifyWriteUpdateContents(const VkWriteDescriptorSet *update, const uint32_t index,
1867                                                                UNIQUE_VALIDATION_ERROR_CODE *error_code,
1868                                                                std::string *error_msg) const {
1869     switch (update->descriptorType) {
1870         case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: {
1871             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1872                 // Validate image
1873                 auto image_view = update->pImageInfo[di].imageView;
1874                 auto image_layout = update->pImageInfo[di].imageLayout;
1875                 if (!ValidateImageUpdate(image_view, image_layout, update->descriptorType, device_data_, error_code, error_msg)) {
1876                     std::stringstream error_str;
1877                     error_str << "Attempted write update to combined image sampler descriptor failed due to: "
1878                               << error_msg->c_str();
1879                     *error_msg = error_str.str();
1880                     return false;
1881                 }
1882             }
1883             // Intentional fall-through to validate sampler
1884         }
1885         case VK_DESCRIPTOR_TYPE_SAMPLER: {
1886             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1887                 if (!descriptors_[index + di].get()->IsImmutableSampler()) {
1888                     if (!ValidateSampler(update->pImageInfo[di].sampler, device_data_)) {
1889                         *error_code = VALIDATION_ERROR_15c0028a;
1890                         std::stringstream error_str;
1891                         error_str << "Attempted write update to sampler descriptor with invalid sampler: "
1892                                   << update->pImageInfo[di].sampler << ".";
1893                         *error_msg = error_str.str();
1894                         return false;
1895                     }
1896                 } else {
1897                     // TODO : Warn here
1898                 }
1899             }
1900             break;
1901         }
1902         case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
1903         case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
1904         case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: {
1905             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1906                 auto image_view = update->pImageInfo[di].imageView;
1907                 auto image_layout = update->pImageInfo[di].imageLayout;
1908                 if (!ValidateImageUpdate(image_view, image_layout, update->descriptorType, device_data_, error_code, error_msg)) {
1909                     std::stringstream error_str;
1910                     error_str << "Attempted write update to image descriptor failed due to: " << error_msg->c_str();
1911                     *error_msg = error_str.str();
1912                     return false;
1913                 }
1914             }
1915             break;
1916         }
1917         case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
1918         case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: {
1919             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1920                 auto buffer_view = update->pTexelBufferView[di];
1921                 auto bv_state = GetBufferViewState(device_data_, buffer_view);
1922                 if (!bv_state) {
1923                     *error_code = VALIDATION_ERROR_15c00286;
1924                     std::stringstream error_str;
1925                     error_str << "Attempted write update to texel buffer descriptor with invalid buffer view: " << buffer_view;
1926                     *error_msg = error_str.str();
1927                     return false;
1928                 }
1929                 auto buffer = bv_state->create_info.buffer;
1930                 auto buffer_state = GetBufferState(device_data_, buffer);
1931                 // Verify that buffer underlying the view hasn't been destroyed prematurely
1932                 if (!buffer_state) {
1933                     *error_code = VALIDATION_ERROR_15c00286;
1934                     std::stringstream error_str;
1935                     error_str << "Attempted write update to texel buffer descriptor failed because underlying buffer (" << buffer
1936                               << ") has been destroyed: " << error_msg->c_str();
1937                     *error_msg = error_str.str();
1938                     return false;
1939                 } else if (!ValidateBufferUsage(buffer_state, update->descriptorType, error_code, error_msg)) {
1940                     std::stringstream error_str;
1941                     error_str << "Attempted write update to texel buffer descriptor failed due to: " << error_msg->c_str();
1942                     *error_msg = error_str.str();
1943                     return false;
1944                 }
1945             }
1946             break;
1947         }
1948         case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
1949         case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
1950         case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
1951         case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: {
1952             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1953                 if (!ValidateBufferUpdate(update->pBufferInfo + di, update->descriptorType, error_code, error_msg)) {
1954                     std::stringstream error_str;
1955                     error_str << "Attempted write update to buffer descriptor failed due to: " << error_msg->c_str();
1956                     *error_msg = error_str.str();
1957                     return false;
1958                 }
1959             }
1960             break;
1961         }
1962         default:
1963             assert(0);  // We've already verified update type so should never get here
1964             break;
1965     }
1966     // All checks passed so update contents are good
1967     return true;
1968 }
1969 // Verify that the contents of the update are ok, but don't perform actual update
1970 bool cvdescriptorset::DescriptorSet::VerifyCopyUpdateContents(const VkCopyDescriptorSet *update, const DescriptorSet *src_set,
1971                                                               VkDescriptorType type, uint32_t index,
1972                                                               UNIQUE_VALIDATION_ERROR_CODE *error_code,
1973                                                               std::string *error_msg) const {
1974     // Note : Repurposing some Write update error codes here as specific details aren't called out for copy updates like they are
1975     // for write updates
1976     switch (src_set->descriptors_[index]->descriptor_class) {
1977         case PlainSampler: {
1978             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1979                 const auto src_desc = src_set->descriptors_[index + di].get();
1980                 if (!src_desc->updated) continue;
1981                 if (!src_desc->IsImmutableSampler()) {
1982                     auto update_sampler = static_cast<SamplerDescriptor *>(src_desc)->GetSampler();
1983                     if (!ValidateSampler(update_sampler, device_data_)) {
1984                         *error_code = VALIDATION_ERROR_15c0028a;
1985                         std::stringstream error_str;
1986                         error_str << "Attempted copy update to sampler descriptor with invalid sampler: " << update_sampler << ".";
1987                         *error_msg = error_str.str();
1988                         return false;
1989                     }
1990                 } else {
1991                     // TODO : Warn here
1992                 }
1993             }
1994             break;
1995         }
1996         case ImageSampler: {
1997             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
1998                 const auto src_desc = src_set->descriptors_[index + di].get();
1999                 if (!src_desc->updated) continue;
2000                 auto img_samp_desc = static_cast<const ImageSamplerDescriptor *>(src_desc);
2001                 // First validate sampler
2002                 if (!img_samp_desc->IsImmutableSampler()) {
2003                     auto update_sampler = img_samp_desc->GetSampler();
2004                     if (!ValidateSampler(update_sampler, device_data_)) {
2005                         *error_code = VALIDATION_ERROR_15c0028a;
2006                         std::stringstream error_str;
2007                         error_str << "Attempted copy update to sampler descriptor with invalid sampler: " << update_sampler << ".";
2008                         *error_msg = error_str.str();
2009                         return false;
2010                     }
2011                 } else {
2012                     // TODO : Warn here
2013                 }
2014                 // Validate image
2015                 auto image_view = img_samp_desc->GetImageView();
2016                 auto image_layout = img_samp_desc->GetImageLayout();
2017                 if (!ValidateImageUpdate(image_view, image_layout, type, device_data_, error_code, error_msg)) {
2018                     std::stringstream error_str;
2019                     error_str << "Attempted copy update to combined image sampler descriptor failed due to: " << error_msg->c_str();
2020                     *error_msg = error_str.str();
2021                     return false;
2022                 }
2023             }
2024             break;
2025         }
2026         case Image: {
2027             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
2028                 const auto src_desc = src_set->descriptors_[index + di].get();
2029                 if (!src_desc->updated) continue;
2030                 auto img_desc = static_cast<const ImageDescriptor *>(src_desc);
2031                 auto image_view = img_desc->GetImageView();
2032                 auto image_layout = img_desc->GetImageLayout();
2033                 if (!ValidateImageUpdate(image_view, image_layout, type, device_data_, error_code, error_msg)) {
2034                     std::stringstream error_str;
2035                     error_str << "Attempted copy update to image descriptor failed due to: " << error_msg->c_str();
2036                     *error_msg = error_str.str();
2037                     return false;
2038                 }
2039             }
2040             break;
2041         }
2042         case TexelBuffer: {
2043             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
2044                 const auto src_desc = src_set->descriptors_[index + di].get();
2045                 if (!src_desc->updated) continue;
2046                 auto buffer_view = static_cast<TexelDescriptor *>(src_desc)->GetBufferView();
2047                 auto bv_state = GetBufferViewState(device_data_, buffer_view);
2048                 if (!bv_state) {
2049                     *error_code = VALIDATION_ERROR_15c00286;
2050                     std::stringstream error_str;
2051                     error_str << "Attempted copy update to texel buffer descriptor with invalid buffer view: " << buffer_view;
2052                     *error_msg = error_str.str();
2053                     return false;
2054                 }
2055                 auto buffer = bv_state->create_info.buffer;
2056                 if (!ValidateBufferUsage(GetBufferState(device_data_, buffer), type, error_code, error_msg)) {
2057                     std::stringstream error_str;
2058                     error_str << "Attempted copy update to texel buffer descriptor failed due to: " << error_msg->c_str();
2059                     *error_msg = error_str.str();
2060                     return false;
2061                 }
2062             }
2063             break;
2064         }
2065         case GeneralBuffer: {
2066             for (uint32_t di = 0; di < update->descriptorCount; ++di) {
2067                 const auto src_desc = src_set->descriptors_[index + di].get();
2068                 if (!src_desc->updated) continue;
2069                 auto buffer = static_cast<BufferDescriptor *>(src_desc)->GetBuffer();
2070                 if (!ValidateBufferUsage(GetBufferState(device_data_, buffer), type, error_code, error_msg)) {
2071                     std::stringstream error_str;
2072                     error_str << "Attempted copy update to buffer descriptor failed due to: " << error_msg->c_str();
2073                     *error_msg = error_str.str();
2074                     return false;
2075                 }
2076             }
2077             break;
2078         }
2079         default:
2080             assert(0);  // We've already verified update type so should never get here
2081             break;
2082     }
2083     // All checks passed so update contents are good
2084     return true;
2085 }
2086 // Update the common AllocateDescriptorSetsData
2087 void cvdescriptorset::UpdateAllocateDescriptorSetsData(const layer_data *dev_data, const VkDescriptorSetAllocateInfo *p_alloc_info,
2088                                                        AllocateDescriptorSetsData *ds_data) {
2089     for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) {
2090         auto layout = GetDescriptorSetLayout(dev_data, p_alloc_info->pSetLayouts[i]);
2091         if (layout) {
2092             ds_data->layout_nodes[i] = layout;
2093             // Count total descriptors required per type
2094             for (uint32_t j = 0; j < layout->GetBindingCount(); ++j) {
2095                 const auto &binding_layout = layout->GetDescriptorSetLayoutBindingPtrFromIndex(j);
2096                 uint32_t typeIndex = static_cast<uint32_t>(binding_layout->descriptorType);
2097                 ds_data->required_descriptors_by_type[typeIndex] += binding_layout->descriptorCount;
2098             }
2099         }
2100         // Any unknown layouts will be flagged as errors during ValidateAllocateDescriptorSets() call
2101     }
2102 }
2103 // Verify that the state at allocate time is correct, but don't actually allocate the sets yet
2104 bool cvdescriptorset::ValidateAllocateDescriptorSets(const core_validation::layer_data *dev_data,
2105                                                      const VkDescriptorSetAllocateInfo *p_alloc_info,
2106                                                      const AllocateDescriptorSetsData *ds_data) {
2107     bool skip = false;
2108     auto report_data = core_validation::GetReportData(dev_data);
2109     auto pool_state = GetDescriptorPoolState(dev_data, p_alloc_info->descriptorPool);
2110
2111     for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) {
2112         auto layout = GetDescriptorSetLayout(dev_data, p_alloc_info->pSetLayouts[i]);
2113         if (layout) {  // nullptr layout indicates no valid layout handle for this device, validated/logged in object_tracker
2114             if (layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR) {
2115                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT,
2116                                 HandleToUint64(p_alloc_info->pSetLayouts[i]), VALIDATION_ERROR_04c00268,
2117                                 "Layout 0x%" PRIxLEAST64 " specified at pSetLayouts[%" PRIu32
2118                                 "] in vkAllocateDescriptorSets() was created with invalid flag %s set.",
2119                                 HandleToUint64(p_alloc_info->pSetLayouts[i]), i,
2120                                 "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR");
2121             }
2122             if (layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT &&
2123                 !(pool_state->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT)) {
2124                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT,
2125                                 0, VALIDATION_ERROR_04c017c8,
2126                                 "Descriptor set layout create flags and pool create flags mismatch for index (%d)", i);
2127             }
2128         }
2129     }
2130     if (!GetDeviceExtensions(dev_data)->vk_khr_maintenance1) {
2131         // Track number of descriptorSets allowable in this pool
2132         if (pool_state->availableSets < p_alloc_info->descriptorSetCount) {
2133             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
2134                             HandleToUint64(pool_state->pool), VALIDATION_ERROR_04c00264,
2135                             "Unable to allocate %u descriptorSets from pool 0x%" PRIxLEAST64
2136                             ". This pool only has %d descriptorSets remaining.",
2137                             p_alloc_info->descriptorSetCount, HandleToUint64(pool_state->pool), pool_state->availableSets);
2138         }
2139         // Determine whether descriptor counts are satisfiable
2140         for (uint32_t i = 0; i < VK_DESCRIPTOR_TYPE_RANGE_SIZE; i++) {
2141             if (ds_data->required_descriptors_by_type[i] > pool_state->availableDescriptorTypeCount[i]) {
2142                 skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT,
2143                                 HandleToUint64(pool_state->pool), VALIDATION_ERROR_04c00266,
2144                                 "Unable to allocate %u descriptors of type %s from pool 0x%" PRIxLEAST64
2145                                 ". This pool only has %d descriptors of this type remaining.",
2146                                 ds_data->required_descriptors_by_type[i], string_VkDescriptorType(VkDescriptorType(i)),
2147                                 HandleToUint64(pool_state->pool), pool_state->availableDescriptorTypeCount[i]);
2148             }
2149         }
2150     }
2151
2152     const auto *count_allocate_info = lvl_find_in_chain<VkDescriptorSetVariableDescriptorCountAllocateInfoEXT>(p_alloc_info->pNext);
2153
2154     if (count_allocate_info) {
2155         if (count_allocate_info->descriptorSetCount != 0 &&
2156             count_allocate_info->descriptorSetCount != p_alloc_info->descriptorSetCount) {
2157             skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, 0,
2158                             VALIDATION_ERROR_46c017ca,
2159                             "VkDescriptorSetAllocateInfo::descriptorSetCount (%d) != "
2160                             "VkDescriptorSetVariableDescriptorCountAllocateInfoEXT::descriptorSetCount (%d)",
2161                             p_alloc_info->descriptorSetCount, count_allocate_info->descriptorSetCount);
2162         }
2163         if (count_allocate_info->descriptorSetCount == p_alloc_info->descriptorSetCount) {
2164             for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) {
2165                 auto layout = GetDescriptorSetLayout(dev_data, p_alloc_info->pSetLayouts[i]);
2166                 if (count_allocate_info->pDescriptorCounts[i] > layout->GetDescriptorCountFromBinding(layout->GetMaxBinding())) {
2167                     skip |= log_msg(
2168                         report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, 0,
2169                         VALIDATION_ERROR_46c017cc, "pDescriptorCounts[%d] = (%d), binding's descriptorCount = (%d)", i,
2170                         count_allocate_info->pDescriptorCounts[i], layout->GetDescriptorCountFromBinding(layout->GetMaxBinding()));
2171                 }
2172             }
2173         }
2174     }
2175
2176     return skip;
2177 }
2178 // Decrement allocated sets from the pool and insert new sets into set_map
2179 void cvdescriptorset::PerformAllocateDescriptorSets(const VkDescriptorSetAllocateInfo *p_alloc_info,
2180                                                     const VkDescriptorSet *descriptor_sets,
2181                                                     const AllocateDescriptorSetsData *ds_data,
2182                                                     std::unordered_map<VkDescriptorPool, DESCRIPTOR_POOL_STATE *> *pool_map,
2183                                                     std::unordered_map<VkDescriptorSet, cvdescriptorset::DescriptorSet *> *set_map,
2184                                                     layer_data *dev_data) {
2185     auto pool_state = (*pool_map)[p_alloc_info->descriptorPool];
2186     // Account for sets and individual descriptors allocated from pool
2187     pool_state->availableSets -= p_alloc_info->descriptorSetCount;
2188     for (uint32_t i = 0; i < VK_DESCRIPTOR_TYPE_RANGE_SIZE; i++) {
2189         pool_state->availableDescriptorTypeCount[i] -= ds_data->required_descriptors_by_type[i];
2190     }
2191
2192     const auto *variable_count_info = lvl_find_in_chain<VkDescriptorSetVariableDescriptorCountAllocateInfoEXT>(p_alloc_info->pNext);
2193     bool variable_count_valid = variable_count_info && variable_count_info->descriptorSetCount == p_alloc_info->descriptorSetCount;
2194
2195     // Create tracking object for each descriptor set; insert into global map and the pool's set.
2196     for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) {
2197         uint32_t variable_count = variable_count_valid ? variable_count_info->pDescriptorCounts[i] : 0;
2198
2199         auto new_ds = new cvdescriptorset::DescriptorSet(descriptor_sets[i], p_alloc_info->descriptorPool, ds_data->layout_nodes[i],
2200                                                          variable_count, dev_data);
2201
2202         pool_state->sets.insert(new_ds);
2203         new_ds->in_use.store(0);
2204         (*set_map)[descriptor_sets[i]] = new_ds;
2205     }
2206 }
2207
2208 cvdescriptorset::PrefilterBindRequestMap::PrefilterBindRequestMap(cvdescriptorset::DescriptorSet &ds, const BindingReqMap &in_map,
2209                                                                   GLOBAL_CB_NODE *cb_state)
2210     : filtered_map_(), orig_map_(in_map) {
2211     if (ds.GetTotalDescriptorCount() > kManyDescriptors_) {
2212         filtered_map_.reset(new std::map<uint32_t, descriptor_req>());
2213         ds.FilterAndTrackBindingReqs(cb_state, orig_map_, filtered_map_.get());
2214     }
2215 }
2216 cvdescriptorset::PrefilterBindRequestMap::PrefilterBindRequestMap(cvdescriptorset::DescriptorSet &ds, const BindingReqMap &in_map,
2217                                                                   GLOBAL_CB_NODE *cb_state, PIPELINE_STATE *pipeline)
2218     : filtered_map_(), orig_map_(in_map) {
2219     if (ds.GetTotalDescriptorCount() > kManyDescriptors_) {
2220         filtered_map_.reset(new std::map<uint32_t, descriptor_req>());
2221         ds.FilterAndTrackBindingReqs(cb_state, pipeline, orig_map_, filtered_map_.get());
2222     }
2223 }