1 /*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 // The API layer of the loader defines Vulkan API and manages layers. The
18 // entrypoints are generated and defined in api_dispatch.cpp. Most of them
19 // simply find the dispatch table and jump.
20 //
21 // There are a few of them requiring manual code for things such as layer
22 // discovery or chaining. They call into functions defined in this file.
23
24 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
25
26 #include <stdlib.h>
27 #include <string.h>
28
29 #include <algorithm>
30 #include <mutex>
31 #include <new>
32 #include <string>
33 #include <unordered_set>
34 #include <utility>
35
36 #include <android-base/properties.h>
37 #include <android-base/strings.h>
38 #include <cutils/properties.h>
39 #include <log/log.h>
40 #include <utils/Trace.h>
41
42 #include <vulkan/vk_layer_interface.h>
43 #include <graphicsenv/GraphicsEnv.h>
44 #include "api.h"
45 #include "driver.h"
46 #include "layers_extensions.h"
47
48 #include <com_android_graphics_libvulkan_flags.h>
49
50 using namespace com::android::graphics::libvulkan;
51
52 namespace vulkan {
53 namespace api {
54
55 namespace {
56
57 // Provide overridden layer names when there are implicit layers. No effect
58 // otherwise.
59 class OverrideLayerNames {
60 public:
OverrideLayerNames(bool is_instance,const VkAllocationCallbacks & allocator)61 OverrideLayerNames(bool is_instance, const VkAllocationCallbacks& allocator)
62 : is_instance_(is_instance),
63 allocator_(allocator),
64 scope_(VK_SYSTEM_ALLOCATION_SCOPE_COMMAND),
65 names_(nullptr),
66 name_count_(0),
67 implicit_layers_() {
68 implicit_layers_.result = VK_SUCCESS;
69 }
70
~OverrideLayerNames()71 ~OverrideLayerNames() {
72 allocator_.pfnFree(allocator_.pUserData, names_);
73 allocator_.pfnFree(allocator_.pUserData, implicit_layers_.elements);
74 allocator_.pfnFree(allocator_.pUserData, implicit_layers_.name_pool);
75 }
76
Parse(const char * const * names,uint32_t count)77 VkResult Parse(const char* const* names, uint32_t count) {
78 AddImplicitLayers();
79
80 const auto& arr = implicit_layers_;
81 if (arr.result != VK_SUCCESS)
82 return arr.result;
83
84 // no need to override when there is no implicit layer
85 if (!arr.count)
86 return VK_SUCCESS;
87
88 names_ = AllocateNameArray(arr.count + count);
89 if (!names_)
90 return VK_ERROR_OUT_OF_HOST_MEMORY;
91
92 // add implicit layer names
93 for (uint32_t i = 0; i < arr.count; i++)
94 names_[i] = GetImplicitLayerName(i);
95
96 name_count_ = arr.count;
97
98 // add explicit layer names
99 for (uint32_t i = 0; i < count; i++) {
100 // ignore explicit layers that are also implicit
101 if (IsImplicitLayer(names[i]))
102 continue;
103
104 names_[name_count_++] = names[i];
105 }
106
107 return VK_SUCCESS;
108 }
109
Names() const110 const char* const* Names() const { return names_; }
111
Count() const112 uint32_t Count() const { return name_count_; }
113
114 private:
115 struct ImplicitLayer {
116 int priority;
117 size_t name_offset;
118 };
119
120 struct ImplicitLayerArray {
121 ImplicitLayer* elements;
122 uint32_t max_count;
123 uint32_t count;
124
125 char* name_pool;
126 size_t max_pool_size;
127 size_t pool_size;
128
129 VkResult result;
130 };
131
AddImplicitLayers()132 void AddImplicitLayers() {
133 if (!is_instance_)
134 return;
135
136 GetLayersFromSettings();
137
138 // If no layers specified via Settings, check legacy properties
139 if (implicit_layers_.count <= 0) {
140 ParseDebugVulkanLayers();
141 ParseDebugVulkanLayer();
142
143 // sort by priorities
144 auto& arr = implicit_layers_;
145 std::sort(arr.elements, arr.elements + arr.count,
146 [](const ImplicitLayer& a, const ImplicitLayer& b) {
147 return (a.priority < b.priority);
148 });
149 }
150 }
151
GetLayersFromSettings()152 void GetLayersFromSettings() {
153 // These will only be available if conditions are met in GraphicsEnvironment
154 // gpu_debug_layers = layer1:layer2:layerN
155 const std::string layers = android::GraphicsEnv::getInstance().getDebugLayers();
156 if (!layers.empty()) {
157 ALOGV("Debug layer list: %s", layers.c_str());
158 std::vector<std::string> paths = android::base::Split(layers, ":");
159 for (uint32_t i = 0; i < paths.size(); i++) {
160 AddImplicitLayer(int(i), paths[i].c_str(), paths[i].length());
161 }
162 }
163 }
164
ParseDebugVulkanLayers()165 void ParseDebugVulkanLayers() {
166 // debug.vulkan.layers specifies colon-separated layer names
167 char prop[PROPERTY_VALUE_MAX];
168 if (!property_get("debug.vulkan.layers", prop, ""))
169 return;
170
171 // assign negative/high priorities to them
172 int prio = -PROPERTY_VALUE_MAX;
173
174 const char* p = prop;
175 const char* delim;
176 while ((delim = strchr(p, ':'))) {
177 if (delim > p)
178 AddImplicitLayer(prio, p, static_cast<size_t>(delim - p));
179
180 prio++;
181 p = delim + 1;
182 }
183
184 if (p[0] != '\0')
185 AddImplicitLayer(prio, p, strlen(p));
186 }
187
ParseDebugVulkanLayer()188 void ParseDebugVulkanLayer() {
189 // Checks for consecutive debug.vulkan.layer.<priority> system
190 // properties after always checking an initial fixed range.
191 static const char prefix[] = "debug.vulkan.layer.";
192 static constexpr int kFixedRangeBeginInclusive = 0;
193 static constexpr int kFixedRangeEndInclusive = 9;
194
195 bool logged = false;
196
197 int priority = kFixedRangeBeginInclusive;
198 while (true) {
199 const std::string prop_key =
200 std::string(prefix) + std::to_string(priority);
201 const std::string prop_val =
202 android::base::GetProperty(prop_key, "");
203
204 if (!prop_val.empty()) {
205 if (!logged) {
206 ALOGI(
207 "Detected Vulkan layers configured with "
208 "debug.vulkan.layer.<priority>. Checking for "
209 "debug.vulkan.layer.<priority> in the range [%d, %d] "
210 "followed by a consecutive scan.",
211 kFixedRangeBeginInclusive, kFixedRangeEndInclusive);
212 logged = true;
213 }
214 AddImplicitLayer(priority, prop_val.c_str(), prop_val.length());
215 } else if (priority >= kFixedRangeEndInclusive) {
216 return;
217 }
218
219 ++priority;
220 }
221 }
222
AddImplicitLayer(int priority,const char * name,size_t len)223 void AddImplicitLayer(int priority, const char* name, size_t len) {
224 if (!GrowImplicitLayerArray(1, 0))
225 return;
226
227 auto& arr = implicit_layers_;
228 auto& layer = arr.elements[arr.count++];
229
230 layer.priority = priority;
231 layer.name_offset = AddImplicitLayerName(name, len);
232
233 ALOGV("Added implicit layer %s", GetImplicitLayerName(arr.count - 1));
234 }
235
AddImplicitLayerName(const char * name,size_t len)236 size_t AddImplicitLayerName(const char* name, size_t len) {
237 if (!GrowImplicitLayerArray(0, len + 1))
238 return 0;
239
240 // add the name to the pool
241 auto& arr = implicit_layers_;
242 size_t offset = arr.pool_size;
243 char* dst = arr.name_pool + offset;
244
245 std::copy(name, name + len, dst);
246 dst[len] = '\0';
247
248 arr.pool_size += len + 1;
249
250 return offset;
251 }
252
GrowImplicitLayerArray(uint32_t layer_count,size_t name_size)253 bool GrowImplicitLayerArray(uint32_t layer_count, size_t name_size) {
254 const uint32_t initial_max_count = 16;
255 const size_t initial_max_pool_size = 512;
256
257 auto& arr = implicit_layers_;
258
259 // grow the element array if needed
260 while (arr.count + layer_count > arr.max_count) {
261 uint32_t new_max_count =
262 (arr.max_count) ? (arr.max_count << 1) : initial_max_count;
263 void* new_mem = nullptr;
264
265 if (new_max_count > arr.max_count) {
266 new_mem = allocator_.pfnReallocation(
267 allocator_.pUserData, arr.elements,
268 sizeof(ImplicitLayer) * new_max_count,
269 alignof(ImplicitLayer), scope_);
270 }
271
272 if (!new_mem) {
273 arr.result = VK_ERROR_OUT_OF_HOST_MEMORY;
274 arr.count = 0;
275 return false;
276 }
277
278 arr.elements = reinterpret_cast<ImplicitLayer*>(new_mem);
279 arr.max_count = new_max_count;
280 }
281
282 // grow the name pool if needed
283 while (arr.pool_size + name_size > arr.max_pool_size) {
284 size_t new_max_pool_size = (arr.max_pool_size)
285 ? (arr.max_pool_size << 1)
286 : initial_max_pool_size;
287 void* new_mem = nullptr;
288
289 if (new_max_pool_size > arr.max_pool_size) {
290 new_mem = allocator_.pfnReallocation(
291 allocator_.pUserData, arr.name_pool, new_max_pool_size,
292 alignof(char), scope_);
293 }
294
295 if (!new_mem) {
296 arr.result = VK_ERROR_OUT_OF_HOST_MEMORY;
297 arr.pool_size = 0;
298 return false;
299 }
300
301 arr.name_pool = reinterpret_cast<char*>(new_mem);
302 arr.max_pool_size = new_max_pool_size;
303 }
304
305 return true;
306 }
307
GetImplicitLayerName(uint32_t index) const308 const char* GetImplicitLayerName(uint32_t index) const {
309 const auto& arr = implicit_layers_;
310
311 // this may return nullptr when arr.result is not VK_SUCCESS
312 return implicit_layers_.name_pool + arr.elements[index].name_offset;
313 }
314
IsImplicitLayer(const char * name) const315 bool IsImplicitLayer(const char* name) const {
316 const auto& arr = implicit_layers_;
317
318 for (uint32_t i = 0; i < arr.count; i++) {
319 if (strcmp(name, GetImplicitLayerName(i)) == 0)
320 return true;
321 }
322
323 return false;
324 }
325
AllocateNameArray(uint32_t count) const326 const char** AllocateNameArray(uint32_t count) const {
327 return reinterpret_cast<const char**>(allocator_.pfnAllocation(
328 allocator_.pUserData, sizeof(const char*) * count,
329 alignof(const char*), scope_));
330 }
331
332 const bool is_instance_;
333 const VkAllocationCallbacks& allocator_;
334 const VkSystemAllocationScope scope_;
335
336 const char** names_;
337 uint32_t name_count_;
338
339 ImplicitLayerArray implicit_layers_;
340 };
341
342 // Provide overridden extension names when there are implicit extensions.
343 // No effect otherwise.
344 //
345 // This is used only to enable VK_EXT_debug_report.
346 class OverrideExtensionNames {
347 public:
OverrideExtensionNames(bool is_instance,const VkAllocationCallbacks & allocator)348 OverrideExtensionNames(bool is_instance,
349 const VkAllocationCallbacks& allocator)
350 : is_instance_(is_instance),
351 allocator_(allocator),
352 scope_(VK_SYSTEM_ALLOCATION_SCOPE_COMMAND),
353 names_(nullptr),
354 name_count_(0),
355 install_debug_callback_(false) {}
356
~OverrideExtensionNames()357 ~OverrideExtensionNames() {
358 allocator_.pfnFree(allocator_.pUserData, names_);
359 }
360
Parse(const char * const * names,uint32_t count)361 VkResult Parse(const char* const* names, uint32_t count) {
362 // this is only for debug.vulkan.enable_callback
363 if (!EnableDebugCallback())
364 return VK_SUCCESS;
365
366 names_ = AllocateNameArray(count + 1);
367 if (!names_)
368 return VK_ERROR_OUT_OF_HOST_MEMORY;
369
370 std::copy(names, names + count, names_);
371
372 name_count_ = count;
373 names_[name_count_++] = "VK_EXT_debug_report";
374
375 install_debug_callback_ = true;
376
377 return VK_SUCCESS;
378 }
379
Names() const380 const char* const* Names() const { return names_; }
381
Count() const382 uint32_t Count() const { return name_count_; }
383
InstallDebugCallback() const384 bool InstallDebugCallback() const { return install_debug_callback_; }
385
386 private:
EnableDebugCallback() const387 bool EnableDebugCallback() const {
388 return (is_instance_ &&
389 android::GraphicsEnv::getInstance().isDebuggable() &&
390 property_get_bool("debug.vulkan.enable_callback", false));
391 }
392
AllocateNameArray(uint32_t count) const393 const char** AllocateNameArray(uint32_t count) const {
394 return reinterpret_cast<const char**>(allocator_.pfnAllocation(
395 allocator_.pUserData, sizeof(const char*) * count,
396 alignof(const char*), scope_));
397 }
398
399 const bool is_instance_;
400 const VkAllocationCallbacks& allocator_;
401 const VkSystemAllocationScope scope_;
402
403 const char** names_;
404 uint32_t name_count_;
405 bool install_debug_callback_;
406 };
407
408 // vkCreateInstance and vkCreateDevice helpers with support for layer
409 // chaining.
410 class LayerChain {
411 public:
412 struct ActiveLayer {
413 LayerRef ref;
414 union {
415 VkLayerInstanceLink instance_link;
416 VkLayerDeviceLink device_link;
417 };
418 };
419
420 static VkResult CreateInstance(const VkInstanceCreateInfo* create_info,
421 const VkAllocationCallbacks* allocator,
422 VkInstance* instance_out);
423
424 static VkResult CreateDevice(VkPhysicalDevice physical_dev,
425 const VkDeviceCreateInfo* create_info,
426 const VkAllocationCallbacks* allocator,
427 VkDevice* dev_out);
428
429 static void DestroyInstance(VkInstance instance,
430 const VkAllocationCallbacks* allocator);
431
432 static void DestroyDevice(VkDevice dev,
433 const VkAllocationCallbacks* allocator);
434
435 static const ActiveLayer* GetActiveLayers(VkPhysicalDevice physical_dev,
436 uint32_t& count);
437
438 private:
439 LayerChain(bool is_instance,
440 const driver::DebugReportLogger& logger,
441 const VkAllocationCallbacks& allocator);
442 ~LayerChain();
443
444 VkResult ActivateLayers(const char* const* layer_names,
445 uint32_t layer_count,
446 const char* const* extension_names,
447 uint32_t extension_count);
448 VkResult ActivateLayers(VkPhysicalDevice physical_dev,
449 const char* const* layer_names,
450 uint32_t layer_count,
451 const char* const* extension_names,
452 uint32_t extension_count);
453 ActiveLayer* AllocateLayerArray(uint32_t count) const;
454 VkResult LoadLayer(ActiveLayer& layer, const char* name);
455 void SetupLayerLinks();
456
457 bool Empty() const;
458 void ModifyCreateInfo(VkInstanceCreateInfo& info);
459 void ModifyCreateInfo(VkDeviceCreateInfo& info);
460
461 VkResult Create(const VkInstanceCreateInfo* create_info,
462 const VkAllocationCallbacks* allocator,
463 VkInstance* instance_out);
464
465 VkResult Create(VkPhysicalDevice physical_dev,
466 const VkDeviceCreateInfo* create_info,
467 const VkAllocationCallbacks* allocator,
468 VkDevice* dev_out);
469
470 VkResult ValidateExtensions(const char* const* extension_names,
471 uint32_t extension_count);
472 VkResult ValidateExtensions(VkPhysicalDevice physical_dev,
473 const char* const* extension_names,
474 uint32_t extension_count);
475 VkExtensionProperties* AllocateDriverExtensionArray(uint32_t count) const;
476 bool IsLayerExtension(const char* name) const;
477 bool IsDriverExtension(const char* name) const;
478
479 template <typename DataType>
480 void StealLayers(DataType& data);
481
482 static void DestroyLayers(ActiveLayer* layers,
483 uint32_t count,
484 const VkAllocationCallbacks& allocator);
485
486 static VKAPI_ATTR VkResult SetInstanceLoaderData(VkInstance instance,
487 void* object);
488 static VKAPI_ATTR VkResult SetDeviceLoaderData(VkDevice device,
489 void* object);
490
491 static VKAPI_ATTR VkBool32
492 DebugReportCallback(VkDebugReportFlagsEXT flags,
493 VkDebugReportObjectTypeEXT obj_type,
494 uint64_t obj,
495 size_t location,
496 int32_t msg_code,
497 const char* layer_prefix,
498 const char* msg,
499 void* user_data);
500
501 const bool is_instance_;
502 const driver::DebugReportLogger& logger_;
503 const VkAllocationCallbacks& allocator_;
504
505 OverrideLayerNames override_layers_;
506 OverrideExtensionNames override_extensions_;
507
508 ActiveLayer* layers_;
509 uint32_t layer_count_;
510
511 PFN_vkGetInstanceProcAddr get_instance_proc_addr_;
512 PFN_vkGetDeviceProcAddr get_device_proc_addr_;
513
514 union {
515 VkLayerInstanceCreateInfo instance_chain_info_[2];
516 VkLayerDeviceCreateInfo device_chain_info_[2];
517 };
518
519 VkExtensionProperties* driver_extensions_;
520 uint32_t driver_extension_count_;
521 std::bitset<driver::ProcHook::EXTENSION_COUNT> enabled_extensions_;
522 };
523
LayerChain(bool is_instance,const driver::DebugReportLogger & logger,const VkAllocationCallbacks & allocator)524 LayerChain::LayerChain(bool is_instance,
525 const driver::DebugReportLogger& logger,
526 const VkAllocationCallbacks& allocator)
527 : is_instance_(is_instance),
528 logger_(logger),
529 allocator_(allocator),
530 override_layers_(is_instance, allocator),
531 override_extensions_(is_instance, allocator),
532 layers_(nullptr),
533 layer_count_(0),
534 get_instance_proc_addr_(nullptr),
535 get_device_proc_addr_(nullptr),
536 driver_extensions_(nullptr),
537 driver_extension_count_(0) {
538 // advertise the loader supported core Vulkan API version at vulkan::api
539 for (uint32_t i = driver::ProcHook::EXTENSION_CORE_1_0;
540 i != driver::ProcHook::EXTENSION_COUNT; ++i) {
541 enabled_extensions_.set(i);
542 }
543 }
544
~LayerChain()545 LayerChain::~LayerChain() {
546 allocator_.pfnFree(allocator_.pUserData, driver_extensions_);
547 DestroyLayers(layers_, layer_count_, allocator_);
548 }
549
ActivateLayers(const char * const * layer_names,uint32_t layer_count,const char * const * extension_names,uint32_t extension_count)550 VkResult LayerChain::ActivateLayers(const char* const* layer_names,
551 uint32_t layer_count,
552 const char* const* extension_names,
553 uint32_t extension_count) {
554 VkResult result = override_layers_.Parse(layer_names, layer_count);
555 if (result != VK_SUCCESS)
556 return result;
557
558 result = override_extensions_.Parse(extension_names, extension_count);
559 if (result != VK_SUCCESS)
560 return result;
561
562 if (override_layers_.Count()) {
563 layer_names = override_layers_.Names();
564 layer_count = override_layers_.Count();
565 }
566
567 if (!layer_count) {
568 // point head of chain to the driver
569 get_instance_proc_addr_ = driver::GetInstanceProcAddr;
570
571 return VK_SUCCESS;
572 }
573
574 layers_ = AllocateLayerArray(layer_count);
575 if (!layers_)
576 return VK_ERROR_OUT_OF_HOST_MEMORY;
577
578 // load layers
579 for (uint32_t i = 0; i < layer_count; i++) {
580 result = LoadLayer(layers_[i], layer_names[i]);
581 if (result != VK_SUCCESS)
582 return result;
583
584 // count loaded layers for proper destructions on errors
585 layer_count_++;
586 }
587
588 SetupLayerLinks();
589
590 return VK_SUCCESS;
591 }
592
ActivateLayers(VkPhysicalDevice physical_dev,const char * const * layer_names,uint32_t layer_count,const char * const * extension_names,uint32_t extension_count)593 VkResult LayerChain::ActivateLayers(VkPhysicalDevice physical_dev,
594 const char* const* layer_names,
595 uint32_t layer_count,
596 const char* const* extension_names,
597 uint32_t extension_count) {
598 uint32_t instance_layer_count;
599 const ActiveLayer* instance_layers =
600 GetActiveLayers(physical_dev, instance_layer_count);
601
602 // log a message if the application device layer array is not empty nor an
603 // exact match of the instance layer array.
604 if (layer_count) {
605 bool exact_match = (instance_layer_count == layer_count);
606 if (exact_match) {
607 for (uint32_t i = 0; i < instance_layer_count; i++) {
608 const Layer& l = *instance_layers[i].ref;
609 if (strcmp(GetLayerProperties(l).layerName, layer_names[i])) {
610 exact_match = false;
611 break;
612 }
613 }
614 }
615
616 if (!exact_match) {
617 logger_.Warn(physical_dev,
618 "Device layers disagree with instance layers and are "
619 "overridden by instance layers");
620 }
621 }
622
623 VkResult result =
624 override_extensions_.Parse(extension_names, extension_count);
625 if (result != VK_SUCCESS)
626 return result;
627
628 if (!instance_layer_count) {
629 // point head of chain to the driver
630 get_instance_proc_addr_ = driver::GetInstanceProcAddr;
631 get_device_proc_addr_ = driver::GetDeviceProcAddr;
632
633 return VK_SUCCESS;
634 }
635
636 layers_ = AllocateLayerArray(instance_layer_count);
637 if (!layers_)
638 return VK_ERROR_OUT_OF_HOST_MEMORY;
639
640 for (uint32_t i = 0; i < instance_layer_count; i++) {
641 const Layer& l = *instance_layers[i].ref;
642
643 // no need to and cannot chain non-global layers
644 if (!IsLayerGlobal(l))
645 continue;
646
647 // this never fails
648 new (&layers_[layer_count_++]) ActiveLayer{GetLayerRef(l), {}};
649 }
650
651 // this may happen when all layers are non-global ones
652 if (!layer_count_) {
653 get_instance_proc_addr_ = driver::GetInstanceProcAddr;
654 get_device_proc_addr_ = driver::GetDeviceProcAddr;
655 return VK_SUCCESS;
656 }
657
658 SetupLayerLinks();
659
660 return VK_SUCCESS;
661 }
662
AllocateLayerArray(uint32_t count) const663 LayerChain::ActiveLayer* LayerChain::AllocateLayerArray(uint32_t count) const {
664 VkSystemAllocationScope scope = (is_instance_)
665 ? VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE
666 : VK_SYSTEM_ALLOCATION_SCOPE_COMMAND;
667
668 return reinterpret_cast<ActiveLayer*>(allocator_.pfnAllocation(
669 allocator_.pUserData, sizeof(ActiveLayer) * count, alignof(ActiveLayer),
670 scope));
671 }
672
LoadLayer(ActiveLayer & layer,const char * name)673 VkResult LayerChain::LoadLayer(ActiveLayer& layer, const char* name) {
674 const Layer* l = FindLayer(name);
675 if (!l) {
676 logger_.Err(VK_NULL_HANDLE, "Failed to find layer %s", name);
677 return VK_ERROR_LAYER_NOT_PRESENT;
678 }
679
680 new (&layer) ActiveLayer{GetLayerRef(*l), {}};
681 if (!layer.ref) {
682 ALOGW("Failed to open layer %s", name);
683 layer.ref.~LayerRef();
684 return VK_ERROR_LAYER_NOT_PRESENT;
685 }
686
687 if (!layer.ref.GetGetInstanceProcAddr()) {
688 ALOGW("Failed to locate vkGetInstanceProcAddr in layer %s", name);
689 layer.ref.~LayerRef();
690 return VK_ERROR_LAYER_NOT_PRESENT;
691 }
692
693 ALOGI("Loaded layer %s", name);
694
695 return VK_SUCCESS;
696 }
697
SetupLayerLinks()698 void LayerChain::SetupLayerLinks() {
699 if (is_instance_) {
700 for (uint32_t i = 0; i < layer_count_; i++) {
701 ActiveLayer& layer = layers_[i];
702
703 // point head of chain to the first layer
704 if (i == 0)
705 get_instance_proc_addr_ = layer.ref.GetGetInstanceProcAddr();
706
707 // point tail of chain to the driver
708 if (i == layer_count_ - 1) {
709 layer.instance_link.pNext = nullptr;
710 layer.instance_link.pfnNextGetInstanceProcAddr =
711 driver::GetInstanceProcAddr;
712 break;
713 }
714
715 const ActiveLayer& next = layers_[i + 1];
716
717 // const_cast as some naughty layers want to modify our links!
718 layer.instance_link.pNext =
719 const_cast<VkLayerInstanceLink*>(&next.instance_link);
720 layer.instance_link.pfnNextGetInstanceProcAddr =
721 next.ref.GetGetInstanceProcAddr();
722 }
723 } else {
724 for (uint32_t i = 0; i < layer_count_; i++) {
725 ActiveLayer& layer = layers_[i];
726
727 // point head of chain to the first layer
728 if (i == 0) {
729 get_instance_proc_addr_ = layer.ref.GetGetInstanceProcAddr();
730 get_device_proc_addr_ = layer.ref.GetGetDeviceProcAddr();
731 }
732
733 // point tail of chain to the driver
734 if (i == layer_count_ - 1) {
735 layer.device_link.pNext = nullptr;
736 layer.device_link.pfnNextGetInstanceProcAddr =
737 driver::GetInstanceProcAddr;
738 layer.device_link.pfnNextGetDeviceProcAddr =
739 driver::GetDeviceProcAddr;
740 break;
741 }
742
743 const ActiveLayer& next = layers_[i + 1];
744
745 // const_cast as some naughty layers want to modify our links!
746 layer.device_link.pNext =
747 const_cast<VkLayerDeviceLink*>(&next.device_link);
748 layer.device_link.pfnNextGetInstanceProcAddr =
749 next.ref.GetGetInstanceProcAddr();
750 layer.device_link.pfnNextGetDeviceProcAddr =
751 next.ref.GetGetDeviceProcAddr();
752 }
753 }
754 }
755
Empty() const756 bool LayerChain::Empty() const {
757 return (!layer_count_ && !override_layers_.Count() &&
758 !override_extensions_.Count());
759 }
760
ModifyCreateInfo(VkInstanceCreateInfo & info)761 void LayerChain::ModifyCreateInfo(VkInstanceCreateInfo& info) {
762 if (layer_count_) {
763 auto& link_info = instance_chain_info_[1];
764 link_info.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
765 link_info.pNext = info.pNext;
766 link_info.function = VK_LAYER_FUNCTION_LINK;
767 link_info.u.pLayerInfo = &layers_[0].instance_link;
768
769 auto& cb_info = instance_chain_info_[0];
770 cb_info.sType = VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO;
771 cb_info.pNext = &link_info;
772 cb_info.function = VK_LAYER_FUNCTION_DATA_CALLBACK;
773 cb_info.u.pfnSetInstanceLoaderData = SetInstanceLoaderData;
774
775 info.pNext = &cb_info;
776 }
777
778 if (override_layers_.Count()) {
779 info.enabledLayerCount = override_layers_.Count();
780 info.ppEnabledLayerNames = override_layers_.Names();
781 }
782
783 if (override_extensions_.Count()) {
784 info.enabledExtensionCount = override_extensions_.Count();
785 info.ppEnabledExtensionNames = override_extensions_.Names();
786 }
787 }
788
ModifyCreateInfo(VkDeviceCreateInfo & info)789 void LayerChain::ModifyCreateInfo(VkDeviceCreateInfo& info) {
790 if (layer_count_) {
791 auto& link_info = device_chain_info_[1];
792 link_info.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
793 link_info.pNext = info.pNext;
794 link_info.function = VK_LAYER_FUNCTION_LINK;
795 link_info.u.pLayerInfo = &layers_[0].device_link;
796
797 auto& cb_info = device_chain_info_[0];
798 cb_info.sType = VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO;
799 cb_info.pNext = &link_info;
800 cb_info.function = VK_LAYER_FUNCTION_DATA_CALLBACK;
801 cb_info.u.pfnSetDeviceLoaderData = SetDeviceLoaderData;
802
803 info.pNext = &cb_info;
804 }
805
806 if (override_layers_.Count()) {
807 info.enabledLayerCount = override_layers_.Count();
808 info.ppEnabledLayerNames = override_layers_.Names();
809 }
810
811 if (override_extensions_.Count()) {
812 info.enabledExtensionCount = override_extensions_.Count();
813 info.ppEnabledExtensionNames = override_extensions_.Names();
814 }
815 }
816
Create(const VkInstanceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkInstance * instance_out)817 VkResult LayerChain::Create(const VkInstanceCreateInfo* create_info,
818 const VkAllocationCallbacks* allocator,
819 VkInstance* instance_out) {
820 VkResult result = ValidateExtensions(create_info->ppEnabledExtensionNames,
821 create_info->enabledExtensionCount);
822 if (result != VK_SUCCESS)
823 return result;
824
825 // call down the chain
826 PFN_vkCreateInstance create_instance =
827 reinterpret_cast<PFN_vkCreateInstance>(
828 get_instance_proc_addr_(VK_NULL_HANDLE, "vkCreateInstance"));
829 VkInstance instance;
830 result = create_instance(create_info, allocator, &instance);
831 if (result != VK_SUCCESS)
832 return result;
833
834 // initialize InstanceData
835 InstanceData& data = GetData(instance);
836
837 if (!InitDispatchTable(instance, get_instance_proc_addr_,
838 enabled_extensions_)) {
839 if (data.dispatch.DestroyInstance)
840 data.dispatch.DestroyInstance(instance, allocator);
841
842 return VK_ERROR_INITIALIZATION_FAILED;
843 }
844
845 // install debug report callback
846 if (override_extensions_.InstallDebugCallback()) {
847 PFN_vkCreateDebugReportCallbackEXT create_debug_report_callback =
848 reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
849 get_instance_proc_addr_(instance,
850 "vkCreateDebugReportCallbackEXT"));
851 data.destroy_debug_callback =
852 reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
853 get_instance_proc_addr_(instance,
854 "vkDestroyDebugReportCallbackEXT"));
855 if (!create_debug_report_callback || !data.destroy_debug_callback) {
856 ALOGE("Broken VK_EXT_debug_report support");
857 data.dispatch.DestroyInstance(instance, allocator);
858 return VK_ERROR_INITIALIZATION_FAILED;
859 }
860
861 VkDebugReportCallbackCreateInfoEXT debug_callback_info = {};
862 debug_callback_info.sType =
863 VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
864 debug_callback_info.flags =
865 VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
866 debug_callback_info.pfnCallback = DebugReportCallback;
867
868 VkDebugReportCallbackEXT debug_callback;
869 result = create_debug_report_callback(instance, &debug_callback_info,
870 nullptr, &debug_callback);
871 if (result != VK_SUCCESS) {
872 ALOGE("Failed to install debug report callback");
873 data.dispatch.DestroyInstance(instance, allocator);
874 return VK_ERROR_INITIALIZATION_FAILED;
875 }
876
877 data.debug_callback = debug_callback;
878
879 ALOGI("Installed debug report callback");
880 }
881
882 StealLayers(data);
883
884 *instance_out = instance;
885
886 return VK_SUCCESS;
887 }
888
Create(VkPhysicalDevice physical_dev,const VkDeviceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkDevice * dev_out)889 VkResult LayerChain::Create(VkPhysicalDevice physical_dev,
890 const VkDeviceCreateInfo* create_info,
891 const VkAllocationCallbacks* allocator,
892 VkDevice* dev_out) {
893 VkResult result =
894 ValidateExtensions(physical_dev, create_info->ppEnabledExtensionNames,
895 create_info->enabledExtensionCount);
896 if (result != VK_SUCCESS)
897 return result;
898
899 // call down the chain
900 PFN_vkCreateDevice create_device =
901 GetData(physical_dev).dispatch.CreateDevice;
902 VkDevice dev;
903 result = create_device(physical_dev, create_info, allocator, &dev);
904 if (result != VK_SUCCESS)
905 return result;
906
907 // initialize DeviceData
908 DeviceData& data = GetData(dev);
909
910 if (!InitDispatchTable(dev, get_device_proc_addr_, enabled_extensions_)) {
911 if (data.dispatch.DestroyDevice)
912 data.dispatch.DestroyDevice(dev, allocator);
913
914 return VK_ERROR_INITIALIZATION_FAILED;
915 }
916
917 // no StealLayers so that active layers are destroyed with this
918 // LayerChain
919 *dev_out = dev;
920
921 return VK_SUCCESS;
922 }
923
ValidateExtensions(const char * const * extension_names,uint32_t extension_count)924 VkResult LayerChain::ValidateExtensions(const char* const* extension_names,
925 uint32_t extension_count) {
926 if (!extension_count)
927 return VK_SUCCESS;
928
929 // query driver instance extensions
930 uint32_t count;
931 VkResult result =
932 EnumerateInstanceExtensionProperties(nullptr, &count, nullptr);
933 if (result == VK_SUCCESS && count) {
934 driver_extensions_ = AllocateDriverExtensionArray(count);
935 result = (driver_extensions_) ? EnumerateInstanceExtensionProperties(
936 nullptr, &count, driver_extensions_)
937 : VK_ERROR_OUT_OF_HOST_MEMORY;
938 }
939 if (result != VK_SUCCESS)
940 return result;
941
942 driver_extension_count_ = count;
943
944 for (uint32_t i = 0; i < extension_count; i++) {
945 const char* name = extension_names[i];
946 if (!IsLayerExtension(name) && !IsDriverExtension(name)) {
947 logger_.Err(VK_NULL_HANDLE,
948 "Failed to enable missing instance extension %s", name);
949 return VK_ERROR_EXTENSION_NOT_PRESENT;
950 }
951
952 auto ext_bit = driver::GetProcHookExtension(name);
953 if (ext_bit != driver::ProcHook::EXTENSION_UNKNOWN)
954 enabled_extensions_.set(ext_bit);
955 }
956
957 return VK_SUCCESS;
958 }
959
ValidateExtensions(VkPhysicalDevice physical_dev,const char * const * extension_names,uint32_t extension_count)960 VkResult LayerChain::ValidateExtensions(VkPhysicalDevice physical_dev,
961 const char* const* extension_names,
962 uint32_t extension_count) {
963 if (!extension_count)
964 return VK_SUCCESS;
965
966 // query driver device extensions
967 uint32_t count;
968 VkResult result = EnumerateDeviceExtensionProperties(physical_dev, nullptr,
969 &count, nullptr);
970 if (result == VK_SUCCESS && count) {
971 // Work-around a race condition during Android start-up, that can result
972 // in the second call to EnumerateDeviceExtensionProperties having
973 // another extension. That causes the second call to return
974 // VK_INCOMPLETE. A work-around is to add 1 to "count" and ask for one
975 // more extension property. See: http://anglebug.com/6715 and
976 // internal-to-Google b/206733351.
977 count++;
978 driver_extensions_ = AllocateDriverExtensionArray(count);
979 result = (driver_extensions_)
980 ? EnumerateDeviceExtensionProperties(
981 physical_dev, nullptr, &count, driver_extensions_)
982 : VK_ERROR_OUT_OF_HOST_MEMORY;
983 }
984 if (result != VK_SUCCESS)
985 return result;
986
987 driver_extension_count_ = count;
988
989 for (uint32_t i = 0; i < extension_count; i++) {
990 const char* name = extension_names[i];
991 if (!IsLayerExtension(name) && !IsDriverExtension(name)) {
992 logger_.Err(physical_dev,
993 "Failed to enable missing device extension %s", name);
994 return VK_ERROR_EXTENSION_NOT_PRESENT;
995 }
996
997 auto ext_bit = driver::GetProcHookExtension(name);
998 if (ext_bit != driver::ProcHook::EXTENSION_UNKNOWN)
999 enabled_extensions_.set(ext_bit);
1000 }
1001
1002 return VK_SUCCESS;
1003 }
1004
AllocateDriverExtensionArray(uint32_t count) const1005 VkExtensionProperties* LayerChain::AllocateDriverExtensionArray(
1006 uint32_t count) const {
1007 return reinterpret_cast<VkExtensionProperties*>(allocator_.pfnAllocation(
1008 allocator_.pUserData, sizeof(VkExtensionProperties) * count,
1009 alignof(VkExtensionProperties), VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
1010 }
1011
IsLayerExtension(const char * name) const1012 bool LayerChain::IsLayerExtension(const char* name) const {
1013 if (is_instance_) {
1014 for (uint32_t i = 0; i < layer_count_; i++) {
1015 const ActiveLayer& layer = layers_[i];
1016 if (FindLayerInstanceExtension(*layer.ref, name))
1017 return true;
1018 }
1019 } else {
1020 for (uint32_t i = 0; i < layer_count_; i++) {
1021 const ActiveLayer& layer = layers_[i];
1022 if (FindLayerDeviceExtension(*layer.ref, name))
1023 return true;
1024 }
1025 }
1026
1027 return false;
1028 }
1029
IsDriverExtension(const char * name) const1030 bool LayerChain::IsDriverExtension(const char* name) const {
1031 for (uint32_t i = 0; i < driver_extension_count_; i++) {
1032 if (strcmp(driver_extensions_[i].extensionName, name) == 0)
1033 return true;
1034 }
1035
1036 return false;
1037 }
1038
1039 template <typename DataType>
StealLayers(DataType & data)1040 void LayerChain::StealLayers(DataType& data) {
1041 data.layers = layers_;
1042 data.layer_count = layer_count_;
1043
1044 layers_ = nullptr;
1045 layer_count_ = 0;
1046 }
1047
DestroyLayers(ActiveLayer * layers,uint32_t count,const VkAllocationCallbacks & allocator)1048 void LayerChain::DestroyLayers(ActiveLayer* layers,
1049 uint32_t count,
1050 const VkAllocationCallbacks& allocator) {
1051 for (uint32_t i = 0; i < count; i++)
1052 layers[i].ref.~LayerRef();
1053
1054 allocator.pfnFree(allocator.pUserData, layers);
1055 }
1056
SetInstanceLoaderData(VkInstance instance,void * object)1057 VkResult LayerChain::SetInstanceLoaderData(VkInstance instance, void* object) {
1058 driver::InstanceDispatchable dispatchable =
1059 reinterpret_cast<driver::InstanceDispatchable>(object);
1060
1061 return (driver::SetDataInternal(dispatchable, &driver::GetData(instance)))
1062 ? VK_SUCCESS
1063 : VK_ERROR_INITIALIZATION_FAILED;
1064 }
1065
SetDeviceLoaderData(VkDevice device,void * object)1066 VkResult LayerChain::SetDeviceLoaderData(VkDevice device, void* object) {
1067 driver::DeviceDispatchable dispatchable =
1068 reinterpret_cast<driver::DeviceDispatchable>(object);
1069
1070 return (driver::SetDataInternal(dispatchable, &driver::GetData(device)))
1071 ? VK_SUCCESS
1072 : VK_ERROR_INITIALIZATION_FAILED;
1073 }
1074
DebugReportCallback(VkDebugReportFlagsEXT flags,VkDebugReportObjectTypeEXT obj_type,uint64_t obj,size_t location,int32_t msg_code,const char * layer_prefix,const char * msg,void * user_data)1075 VkBool32 LayerChain::DebugReportCallback(VkDebugReportFlagsEXT flags,
1076 VkDebugReportObjectTypeEXT obj_type,
1077 uint64_t obj,
1078 size_t location,
1079 int32_t msg_code,
1080 const char* layer_prefix,
1081 const char* msg,
1082 void* user_data) {
1083 int prio;
1084
1085 if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
1086 prio = ANDROID_LOG_ERROR;
1087 else if (flags & (VK_DEBUG_REPORT_WARNING_BIT_EXT |
1088 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT))
1089 prio = ANDROID_LOG_WARN;
1090 else if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT)
1091 prio = ANDROID_LOG_INFO;
1092 else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT)
1093 prio = ANDROID_LOG_DEBUG;
1094 else
1095 prio = ANDROID_LOG_UNKNOWN;
1096
1097 LOG_PRI(prio, LOG_TAG, "[%s] Code %d : %s", layer_prefix, msg_code, msg);
1098
1099 (void)obj_type;
1100 (void)obj;
1101 (void)location;
1102 (void)user_data;
1103
1104 return false;
1105 }
1106
CreateInstance(const VkInstanceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkInstance * instance_out)1107 VkResult LayerChain::CreateInstance(const VkInstanceCreateInfo* create_info,
1108 const VkAllocationCallbacks* allocator,
1109 VkInstance* instance_out) {
1110 const driver::DebugReportLogger logger(*create_info);
1111 LayerChain chain(true, logger,
1112 (allocator) ? *allocator : driver::GetDefaultAllocator());
1113
1114 VkResult result = chain.ActivateLayers(create_info->ppEnabledLayerNames,
1115 create_info->enabledLayerCount,
1116 create_info->ppEnabledExtensionNames,
1117 create_info->enabledExtensionCount);
1118 if (result != VK_SUCCESS)
1119 return result;
1120
1121 // use a local create info when the chain is not empty
1122 VkInstanceCreateInfo local_create_info;
1123 if (!chain.Empty()) {
1124 local_create_info = *create_info;
1125 chain.ModifyCreateInfo(local_create_info);
1126 create_info = &local_create_info;
1127 }
1128
1129 return chain.Create(create_info, allocator, instance_out);
1130 }
1131
CreateDevice(VkPhysicalDevice physical_dev,const VkDeviceCreateInfo * create_info,const VkAllocationCallbacks * allocator,VkDevice * dev_out)1132 VkResult LayerChain::CreateDevice(VkPhysicalDevice physical_dev,
1133 const VkDeviceCreateInfo* create_info,
1134 const VkAllocationCallbacks* allocator,
1135 VkDevice* dev_out) {
1136 const driver::DebugReportLogger logger = driver::Logger(physical_dev);
1137 LayerChain chain(
1138 false, logger,
1139 (allocator) ? *allocator : driver::GetData(physical_dev).allocator);
1140
1141 VkResult result = chain.ActivateLayers(
1142 physical_dev, create_info->ppEnabledLayerNames,
1143 create_info->enabledLayerCount, create_info->ppEnabledExtensionNames,
1144 create_info->enabledExtensionCount);
1145 if (result != VK_SUCCESS)
1146 return result;
1147
1148 // use a local create info when the chain is not empty
1149 VkDeviceCreateInfo local_create_info;
1150 if (!chain.Empty()) {
1151 local_create_info = *create_info;
1152 chain.ModifyCreateInfo(local_create_info);
1153 create_info = &local_create_info;
1154 }
1155
1156 return chain.Create(physical_dev, create_info, allocator, dev_out);
1157 }
1158
DestroyInstance(VkInstance instance,const VkAllocationCallbacks * allocator)1159 void LayerChain::DestroyInstance(VkInstance instance,
1160 const VkAllocationCallbacks* allocator) {
1161 InstanceData& data = GetData(instance);
1162
1163 if (data.debug_callback != VK_NULL_HANDLE)
1164 data.destroy_debug_callback(instance, data.debug_callback, allocator);
1165
1166 ActiveLayer* layers = reinterpret_cast<ActiveLayer*>(data.layers);
1167 uint32_t layer_count = data.layer_count;
1168
1169 VkAllocationCallbacks local_allocator;
1170 if (!allocator)
1171 local_allocator = driver::GetData(instance).allocator;
1172
1173 // this also destroys InstanceData
1174 data.dispatch.DestroyInstance(instance, allocator);
1175
1176 DestroyLayers(layers, layer_count,
1177 (allocator) ? *allocator : local_allocator);
1178 }
1179
DestroyDevice(VkDevice device,const VkAllocationCallbacks * allocator)1180 void LayerChain::DestroyDevice(VkDevice device,
1181 const VkAllocationCallbacks* allocator) {
1182 DeviceData& data = GetData(device);
1183 // this also destroys DeviceData
1184 data.dispatch.DestroyDevice(device, allocator);
1185 }
1186
GetActiveLayers(VkPhysicalDevice physical_dev,uint32_t & count)1187 const LayerChain::ActiveLayer* LayerChain::GetActiveLayers(
1188 VkPhysicalDevice physical_dev,
1189 uint32_t& count) {
1190 count = GetData(physical_dev).layer_count;
1191 return reinterpret_cast<const ActiveLayer*>(GetData(physical_dev).layers);
1192 }
1193
1194 // ----------------------------------------------------------------------------
1195
EnsureInitialized()1196 bool EnsureInitialized() {
1197 static bool initialized = false;
1198 static pid_t init_attempted_for_pid = 0;
1199 static std::mutex init_lock;
1200
1201 std::lock_guard<std::mutex> lock(init_lock);
1202 if (init_attempted_for_pid == getpid())
1203 return initialized;
1204
1205 init_attempted_for_pid = getpid();
1206 if (driver::OpenHAL()) {
1207 DiscoverLayers();
1208 initialized = true;
1209 }
1210
1211 return initialized;
1212 }
1213
1214 template <typename Functor>
ForEachLayerFromSettings(Functor functor)1215 void ForEachLayerFromSettings(Functor functor) {
1216 const std::string layersSetting =
1217 android::GraphicsEnv::getInstance().getDebugLayers();
1218 if (!layersSetting.empty()) {
1219 std::vector<std::string> layers =
1220 android::base::Split(layersSetting, ":");
1221 for (uint32_t i = 0; i < layers.size(); i++) {
1222 const Layer* layer = FindLayer(layers[i].c_str());
1223 if (!layer) {
1224 continue;
1225 }
1226 functor(layer);
1227 }
1228 }
1229 }
1230
1231 } // anonymous namespace
1232
CreateInstance(const VkInstanceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkInstance * pInstance)1233 VkResult CreateInstance(const VkInstanceCreateInfo* pCreateInfo,
1234 const VkAllocationCallbacks* pAllocator,
1235 VkInstance* pInstance) {
1236 ATRACE_CALL();
1237
1238 if (!EnsureInitialized())
1239 return VK_ERROR_INITIALIZATION_FAILED;
1240
1241 return LayerChain::CreateInstance(pCreateInfo, pAllocator, pInstance);
1242 }
1243
DestroyInstance(VkInstance instance,const VkAllocationCallbacks * pAllocator)1244 void DestroyInstance(VkInstance instance,
1245 const VkAllocationCallbacks* pAllocator) {
1246 ATRACE_CALL();
1247
1248 if (instance != VK_NULL_HANDLE)
1249 LayerChain::DestroyInstance(instance, pAllocator);
1250 }
1251
CreateDevice(VkPhysicalDevice physicalDevice,const VkDeviceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkDevice * pDevice)1252 VkResult CreateDevice(VkPhysicalDevice physicalDevice,
1253 const VkDeviceCreateInfo* pCreateInfo,
1254 const VkAllocationCallbacks* pAllocator,
1255 VkDevice* pDevice) {
1256 ATRACE_CALL();
1257
1258 return LayerChain::CreateDevice(physicalDevice, pCreateInfo, pAllocator,
1259 pDevice);
1260 }
1261
DestroyDevice(VkDevice device,const VkAllocationCallbacks * pAllocator)1262 void DestroyDevice(VkDevice device, const VkAllocationCallbacks* pAllocator) {
1263 ATRACE_CALL();
1264
1265 if (device != VK_NULL_HANDLE)
1266 LayerChain::DestroyDevice(device, pAllocator);
1267 }
1268
EnumerateInstanceLayerProperties(uint32_t * pPropertyCount,VkLayerProperties * pProperties)1269 VkResult EnumerateInstanceLayerProperties(uint32_t* pPropertyCount,
1270 VkLayerProperties* pProperties) {
1271 ATRACE_CALL();
1272
1273 if (!EnsureInitialized())
1274 return VK_ERROR_OUT_OF_HOST_MEMORY;
1275
1276 uint32_t count = GetLayerCount();
1277
1278 if (!pProperties) {
1279 *pPropertyCount = count;
1280 return VK_SUCCESS;
1281 }
1282
1283 uint32_t copied = std::min(*pPropertyCount, count);
1284 for (uint32_t i = 0; i < copied; i++)
1285 pProperties[i] = GetLayerProperties(GetLayer(i));
1286 *pPropertyCount = copied;
1287
1288 return (copied == count) ? VK_SUCCESS : VK_INCOMPLETE;
1289 }
1290
EnumerateInstanceExtensionProperties(const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)1291 VkResult EnumerateInstanceExtensionProperties(
1292 const char* pLayerName,
1293 uint32_t* pPropertyCount,
1294 VkExtensionProperties* pProperties) {
1295 ATRACE_CALL();
1296
1297 if (!EnsureInitialized())
1298 return VK_ERROR_OUT_OF_HOST_MEMORY;
1299
1300 if (pLayerName) {
1301 const Layer* layer = FindLayer(pLayerName);
1302 if (!layer)
1303 return VK_ERROR_LAYER_NOT_PRESENT;
1304
1305 uint32_t count;
1306 const VkExtensionProperties* props =
1307 GetLayerInstanceExtensions(*layer, count);
1308
1309 if (!pProperties || *pPropertyCount > count)
1310 *pPropertyCount = count;
1311 if (pProperties)
1312 std::copy(props, props + *pPropertyCount, pProperties);
1313
1314 return *pPropertyCount < count ? VK_INCOMPLETE : VK_SUCCESS;
1315 }
1316
1317 // If the pLayerName is nullptr, we must advertise all instance extensions
1318 // from all implicitly enabled layers and the driver implementation. If
1319 // there are duplicates among layers and the driver implementation, always
1320 // only preserve the top layer closest to the application regardless of the
1321 // spec version.
1322 std::vector<VkExtensionProperties> properties;
1323 std::unordered_set<std::string> extensionNames;
1324
1325 // Expose extensions from implicitly enabled layers.
1326 ForEachLayerFromSettings([&](const Layer* layer) {
1327 uint32_t count = 0;
1328 const VkExtensionProperties* props =
1329 GetLayerInstanceExtensions(*layer, count);
1330 if (count > 0) {
1331 for (uint32_t i = 0; i < count; ++i) {
1332 if (extensionNames.emplace(props[i].extensionName).second) {
1333 properties.push_back(props[i]);
1334 }
1335 }
1336 }
1337 });
1338
1339 // TODO(b/143293104): Parse debug.vulkan.layers properties
1340
1341 // Expose extensions from driver implementation.
1342 {
1343 uint32_t count = 0;
1344 VkResult result = vulkan::driver::EnumerateInstanceExtensionProperties(
1345 nullptr, &count, nullptr);
1346 if (result == VK_SUCCESS && count > 0) {
1347 std::vector<VkExtensionProperties> props(count);
1348 result = vulkan::driver::EnumerateInstanceExtensionProperties(
1349 nullptr, &count, props.data());
1350 for (auto prop : props) {
1351 if (extensionNames.emplace(prop.extensionName).second) {
1352 properties.push_back(prop);
1353 }
1354 }
1355 }
1356 }
1357
1358 uint32_t totalCount = properties.size();
1359 if (!pProperties || *pPropertyCount > totalCount) {
1360 *pPropertyCount = totalCount;
1361 }
1362 if (pProperties) {
1363 std::copy(properties.data(), properties.data() + *pPropertyCount,
1364 pProperties);
1365 }
1366 return *pPropertyCount < totalCount ? VK_INCOMPLETE : VK_SUCCESS;
1367 }
1368
EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice,uint32_t * pPropertyCount,VkLayerProperties * pProperties)1369 VkResult EnumerateDeviceLayerProperties(VkPhysicalDevice physicalDevice,
1370 uint32_t* pPropertyCount,
1371 VkLayerProperties* pProperties) {
1372 ATRACE_CALL();
1373
1374 uint32_t count;
1375 const LayerChain::ActiveLayer* layers =
1376 LayerChain::GetActiveLayers(physicalDevice, count);
1377
1378 if (!pProperties) {
1379 *pPropertyCount = count;
1380 return VK_SUCCESS;
1381 }
1382
1383 uint32_t copied = std::min(*pPropertyCount, count);
1384 for (uint32_t i = 0; i < copied; i++)
1385 pProperties[i] = GetLayerProperties(*layers[i].ref);
1386 *pPropertyCount = copied;
1387
1388 return (copied == count) ? VK_SUCCESS : VK_INCOMPLETE;
1389 }
1390
EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)1391 VkResult EnumerateDeviceExtensionProperties(
1392 VkPhysicalDevice physicalDevice,
1393 const char* pLayerName,
1394 uint32_t* pPropertyCount,
1395 VkExtensionProperties* pProperties) {
1396 ATRACE_CALL();
1397
1398 if (pLayerName) {
1399 // EnumerateDeviceLayerProperties enumerates active layers for
1400 // backward compatibility. The extension query here should work for
1401 // all layers.
1402 const Layer* layer = FindLayer(pLayerName);
1403 if (!layer)
1404 return VK_ERROR_LAYER_NOT_PRESENT;
1405
1406 uint32_t count;
1407 const VkExtensionProperties* props =
1408 GetLayerDeviceExtensions(*layer, count);
1409
1410 if (!pProperties || *pPropertyCount > count)
1411 *pPropertyCount = count;
1412 if (pProperties)
1413 std::copy(props, props + *pPropertyCount, pProperties);
1414
1415 return *pPropertyCount < count ? VK_INCOMPLETE : VK_SUCCESS;
1416 }
1417
1418 // If the pLayerName is nullptr, we must advertise all device extensions
1419 // from all implicitly enabled layers and the driver implementation. If
1420 // there are duplicates among layers and the driver implementation, always
1421 // only preserve the top layer closest to the application regardless of the
1422 // spec version.
1423 std::vector<VkExtensionProperties> properties;
1424 std::unordered_set<std::string> extensionNames;
1425
1426 // Expose extensions from implicitly enabled layers.
1427 ForEachLayerFromSettings([&](const Layer* layer) {
1428 uint32_t count = 0;
1429 const VkExtensionProperties* props =
1430 GetLayerDeviceExtensions(*layer, count);
1431 if (count > 0) {
1432 for (uint32_t i = 0; i < count; ++i) {
1433 if (extensionNames.emplace(props[i].extensionName).second) {
1434 properties.push_back(props[i]);
1435 }
1436 }
1437 }
1438 });
1439
1440 // TODO(b/143293104): Parse debug.vulkan.layers properties
1441
1442 // Expose extensions from driver implementation.
1443 {
1444 const InstanceData& data = GetData(physicalDevice);
1445 uint32_t count = 0;
1446 VkResult result = data.dispatch.EnumerateDeviceExtensionProperties(
1447 physicalDevice, nullptr, &count, nullptr);
1448 if (result == VK_SUCCESS && count > 0) {
1449 std::vector<VkExtensionProperties> props(count);
1450 result = data.dispatch.EnumerateDeviceExtensionProperties(
1451 physicalDevice, nullptr, &count, props.data());
1452 for (auto prop : props) {
1453 if (extensionNames.emplace(prop.extensionName).second) {
1454 properties.push_back(prop);
1455 }
1456 }
1457 }
1458 }
1459
1460 uint32_t totalCount = properties.size();
1461 if (!pProperties || *pPropertyCount > totalCount) {
1462 *pPropertyCount = totalCount;
1463 }
1464 if (pProperties) {
1465 std::copy(properties.data(), properties.data() + *pPropertyCount,
1466 pProperties);
1467 }
1468 return *pPropertyCount < totalCount ? VK_INCOMPLETE : VK_SUCCESS;
1469 }
1470
EnumerateInstanceVersion(uint32_t * pApiVersion)1471 VkResult EnumerateInstanceVersion(uint32_t* pApiVersion) {
1472 ATRACE_CALL();
1473
1474 // Load the driver here if not done yet. This api will be used in Zygote
1475 // for Vulkan driver pre-loading because of the minimum overhead.
1476 if (!EnsureInitialized())
1477 return VK_ERROR_OUT_OF_HOST_MEMORY;
1478
1479 *pApiVersion = flags::vulkan_1_4_instance_api() ? VK_API_VERSION_1_4 : VK_API_VERSION_1_3;
1480 return VK_SUCCESS;
1481 }
1482
1483 } // namespace api
1484 } // namespace vulkan
1485