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