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 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18 
19 #include <malloc.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <sys/prctl.h>
23 
24 #include <dlfcn.h>
25 #include <algorithm>
26 #include <array>
27 #include <climits>
28 #include <new>
29 #include <sstream>
30 #include <string>
31 
32 #include <log/log.h>
33 
34 #include <android/dlext.h>
35 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
36 #include <configstore/Utils.h>
37 #include <cutils/properties.h>
38 #include <graphicsenv/GraphicsEnv.h>
39 #include <utils/Timers.h>
40 #include <utils/Trace.h>
41 #include <utils/Vector.h>
42 
43 #include "android-base/properties.h"
44 
45 #include "driver.h"
46 #include "stubhal.h"
47 
48 using namespace android::hardware::configstore;
49 using namespace android::hardware::configstore::V1_0;
50 
51 // TODO(b/37049319) Get this from a header once one exists
52 extern "C" {
53 android_namespace_t* android_get_exported_namespace(const char*);
54 }
55 
56 // #define ENABLE_ALLOC_CALLSTACKS 1
57 #if ENABLE_ALLOC_CALLSTACKS
58 #include <utils/CallStack.h>
59 #define ALOGD_CALLSTACK(...)                             \
60     do {                                                 \
61         ALOGD(__VA_ARGS__);                              \
62         android::CallStack callstack;                    \
63         callstack.update();                              \
64         callstack.log(LOG_TAG, ANDROID_LOG_DEBUG, "  "); \
65     } while (false)
66 #else
67 #define ALOGD_CALLSTACK(...) \
68     do {                     \
69     } while (false)
70 #endif
71 
72 namespace vulkan {
73 namespace driver {
74 
75 namespace {
76 
77 class Hal {
78    public:
79     static bool Open();
80 
Get()81     static const Hal& Get() { return hal_; }
Device()82     static const hwvulkan_device_t& Device() { return *Get().dev_; }
83 
GetDebugReportIndex() const84     int GetDebugReportIndex() const { return debug_report_index_; }
85 
86    private:
Hal()87     Hal() : dev_(nullptr), debug_report_index_(-1) {}
88     Hal(const Hal&) = delete;
89     Hal& operator=(const Hal&) = delete;
90 
91     bool InitDebugReportIndex();
92 
93     static Hal hal_;
94 
95     const hwvulkan_device_t* dev_;
96     int debug_report_index_;
97 };
98 
99 class CreateInfoWrapper {
100    public:
101     CreateInfoWrapper(const VkInstanceCreateInfo& create_info,
102                       const VkAllocationCallbacks& allocator);
103     CreateInfoWrapper(VkPhysicalDevice physical_dev,
104                       const VkDeviceCreateInfo& create_info,
105                       const VkAllocationCallbacks& allocator);
106     ~CreateInfoWrapper();
107 
108     VkResult Validate();
109     void DowngradeApiVersion();
110     void UpgradeDeviceCoreApiVersion(uint32_t api_version);
111 
112     const std::bitset<ProcHook::EXTENSION_COUNT>& GetHookExtensions() const;
113     const std::bitset<ProcHook::EXTENSION_COUNT>& GetHalExtensions() const;
114 
115     explicit operator const VkInstanceCreateInfo*() const;
116     explicit operator const VkDeviceCreateInfo*() const;
117 
118    private:
119     struct ExtensionFilter {
120         VkExtensionProperties* exts;
121         uint32_t ext_count;
122 
123         const char** names;
124         uint32_t name_count;
125     };
126 
127     VkResult SanitizePNext();
128 
129     VkResult SanitizeLayers();
130     VkResult SanitizeExtensions();
131 
132     VkResult QueryExtensionCount(uint32_t& count) const;
133     VkResult EnumerateExtensions(uint32_t& count,
134                                  VkExtensionProperties* props) const;
135     VkResult InitExtensionFilter();
136     void FilterExtension(const char* name);
137 
138     const bool is_instance_;
139     const VkAllocationCallbacks& allocator_;
140 
141     VkPhysicalDevice physical_dev_;
142 
143     union {
144         VkInstanceCreateInfo instance_info_;
145         VkDeviceCreateInfo dev_info_;
146     };
147 
148     VkApplicationInfo application_info_;
149 
150     ExtensionFilter extension_filter_;
151 
152     std::bitset<ProcHook::EXTENSION_COUNT> hook_extensions_;
153     std::bitset<ProcHook::EXTENSION_COUNT> hal_extensions_;
154 };
155 
156 Hal Hal::hal_;
157 
LoadLibrary(const android_dlextinfo & dlextinfo,const std::string_view subname)158 void* LoadLibrary(const android_dlextinfo& dlextinfo,
159                   const std::string_view subname) {
160     ATRACE_CALL();
161 
162     std::stringstream ss;
163     ss << "vulkan." << subname << ".so";
164     return android_dlopen_ext(ss.str().c_str(), RTLD_LOCAL | RTLD_NOW, &dlextinfo);
165 }
166 
167 const std::array<const char*, 2> HAL_SUBNAME_KEY_PROPERTIES = {{
168     "ro.hardware.vulkan",
169     "ro.board.platform",
170 }};
171 
LoadDriver(android_namespace_t * library_namespace,const hwvulkan_module_t ** module)172 int LoadDriver(android_namespace_t* library_namespace,
173                const hwvulkan_module_t** module) {
174     ATRACE_CALL();
175 
176     const android_dlextinfo dlextinfo = {
177         .flags = ANDROID_DLEXT_USE_NAMESPACE,
178         .library_namespace = library_namespace,
179     };
180     void* so = nullptr;
181     char prop[PROPERTY_VALUE_MAX];
182     for (auto key : HAL_SUBNAME_KEY_PROPERTIES) {
183         int prop_len = property_get(key, prop, nullptr);
184         if (prop_len > 0 && prop_len <= UINT_MAX) {
185             std::string_view lib_name(prop, static_cast<unsigned int>(prop_len));
186             so = LoadLibrary(dlextinfo, lib_name);
187             if (so)
188                 break;
189         }
190     }
191     if (!so)
192         return -ENOENT;
193 
194     auto hmi = static_cast<hw_module_t*>(dlsym(so, HAL_MODULE_INFO_SYM_AS_STR));
195     if (!hmi) {
196         ALOGE("couldn't find symbol '%s' in HAL library: %s", HAL_MODULE_INFO_SYM_AS_STR, dlerror());
197         dlclose(so);
198         return -EINVAL;
199     }
200     if (strcmp(hmi->id, HWVULKAN_HARDWARE_MODULE_ID) != 0) {
201         ALOGE("HAL id '%s' != '%s'", hmi->id, HWVULKAN_HARDWARE_MODULE_ID);
202         dlclose(so);
203         return -EINVAL;
204     }
205     hmi->dso = so;
206     *module = reinterpret_cast<const hwvulkan_module_t*>(hmi);
207     return 0;
208 }
209 
LoadBuiltinDriver(const hwvulkan_module_t ** module)210 int LoadBuiltinDriver(const hwvulkan_module_t** module) {
211     ATRACE_CALL();
212 
213     auto ns = android_get_exported_namespace("sphal");
214     if (!ns)
215         return -ENOENT;
216     android::GraphicsEnv::getInstance().setDriverToLoad(
217         android::GraphicsEnv::Driver::VULKAN);
218     return LoadDriver(ns, module);
219 }
220 
LoadUpdatedDriver(const hwvulkan_module_t ** module)221 int LoadUpdatedDriver(const hwvulkan_module_t** module) {
222     ATRACE_CALL();
223 
224     auto ns = android::GraphicsEnv::getInstance().getDriverNamespace();
225     if (!ns)
226         return -ENOENT;
227     android::GraphicsEnv::getInstance().setDriverToLoad(
228         android::GraphicsEnv::Driver::VULKAN_UPDATED);
229     return LoadDriver(ns, module);
230 }
231 
Open()232 bool Hal::Open() {
233     ATRACE_CALL();
234 
235     const nsecs_t openTime = systemTime();
236 
237     ALOG_ASSERT(!hal_.dev_, "OpenHAL called more than once");
238 
239     // Use a stub device unless we successfully open a real HAL device.
240     hal_.dev_ = &stubhal::kDevice;
241 
242     int result;
243     const hwvulkan_module_t* module = nullptr;
244 
245     result = LoadUpdatedDriver(&module);
246     if (result == -ENOENT) {
247         result = LoadBuiltinDriver(&module);
248         if (result != 0) {
249             // -ENOENT means the sphal namespace doesn't exist, not that there
250             // is a problem with the driver.
251             ALOGW_IF(
252                 result != -ENOENT,
253                 "Failed to load Vulkan driver into sphal namespace. This "
254                 "usually means the driver has forbidden library dependencies."
255                 "Please fix, this will soon stop working.");
256             result =
257                 hw_get_module(HWVULKAN_HARDWARE_MODULE_ID,
258                               reinterpret_cast<const hw_module_t**>(&module));
259         }
260     }
261     if (result != 0) {
262         android::GraphicsEnv::getInstance().setDriverLoaded(
263             android::GraphicsEnv::Api::API_VK, false, systemTime() - openTime);
264         ALOGV("unable to load Vulkan HAL, using stub HAL (result=%d)", result);
265         return true;
266     }
267 
268 
269     hwvulkan_device_t* device;
270     ATRACE_BEGIN("hwvulkan module open");
271     result =
272         module->common.methods->open(&module->common, HWVULKAN_DEVICE_0,
273                                      reinterpret_cast<hw_device_t**>(&device));
274     ATRACE_END();
275     if (result != 0) {
276         android::GraphicsEnv::getInstance().setDriverLoaded(
277             android::GraphicsEnv::Api::API_VK, false, systemTime() - openTime);
278         // Any device with a Vulkan HAL should be able to open the device.
279         ALOGE("failed to open Vulkan HAL device: %s (%d)", strerror(-result),
280               result);
281         return false;
282     }
283 
284     hal_.dev_ = device;
285 
286     hal_.InitDebugReportIndex();
287 
288     android::GraphicsEnv::getInstance().setDriverLoaded(
289         android::GraphicsEnv::Api::API_VK, true, systemTime() - openTime);
290 
291     return true;
292 }
293 
InitDebugReportIndex()294 bool Hal::InitDebugReportIndex() {
295     ATRACE_CALL();
296 
297     uint32_t count;
298     if (dev_->EnumerateInstanceExtensionProperties(nullptr, &count, nullptr) !=
299         VK_SUCCESS) {
300         ALOGE("failed to get HAL instance extension count");
301         return false;
302     }
303 
304     VkExtensionProperties* exts = reinterpret_cast<VkExtensionProperties*>(
305         malloc(sizeof(VkExtensionProperties) * count));
306     if (!exts) {
307         ALOGE("failed to allocate HAL instance extension array");
308         return false;
309     }
310 
311     if (dev_->EnumerateInstanceExtensionProperties(nullptr, &count, exts) !=
312         VK_SUCCESS) {
313         ALOGE("failed to enumerate HAL instance extensions");
314         free(exts);
315         return false;
316     }
317 
318     for (uint32_t i = 0; i < count; i++) {
319         if (strcmp(exts[i].extensionName, VK_EXT_DEBUG_REPORT_EXTENSION_NAME) ==
320             0) {
321             debug_report_index_ = static_cast<int>(i);
322             break;
323         }
324     }
325 
326     free(exts);
327 
328     return true;
329 }
330 
CreateInfoWrapper(const VkInstanceCreateInfo & create_info,const VkAllocationCallbacks & allocator)331 CreateInfoWrapper::CreateInfoWrapper(const VkInstanceCreateInfo& create_info,
332                                      const VkAllocationCallbacks& allocator)
333     : is_instance_(true),
334       allocator_(allocator),
335       physical_dev_(VK_NULL_HANDLE),
336       instance_info_(create_info),
337       extension_filter_() {
338     // instance core versions need to match the loader api version
339     for (uint32_t i = ProcHook::EXTENSION_CORE_1_0;
340          i != ProcHook::EXTENSION_COUNT; ++i) {
341         hook_extensions_.set(i);
342         hal_extensions_.set(i);
343     }
344 }
345 
CreateInfoWrapper(VkPhysicalDevice physical_dev,const VkDeviceCreateInfo & create_info,const VkAllocationCallbacks & allocator)346 CreateInfoWrapper::CreateInfoWrapper(VkPhysicalDevice physical_dev,
347                                      const VkDeviceCreateInfo& create_info,
348                                      const VkAllocationCallbacks& allocator)
349     : is_instance_(false),
350       allocator_(allocator),
351       physical_dev_(physical_dev),
352       dev_info_(create_info),
353       extension_filter_() {
354     // initialize with baseline core API version
355     hook_extensions_.set(ProcHook::EXTENSION_CORE_1_0);
356     hal_extensions_.set(ProcHook::EXTENSION_CORE_1_0);
357 }
358 
~CreateInfoWrapper()359 CreateInfoWrapper::~CreateInfoWrapper() {
360     allocator_.pfnFree(allocator_.pUserData, extension_filter_.exts);
361     allocator_.pfnFree(allocator_.pUserData, extension_filter_.names);
362 }
363 
Validate()364 VkResult CreateInfoWrapper::Validate() {
365     VkResult result = SanitizePNext();
366     if (result == VK_SUCCESS)
367         result = SanitizeLayers();
368     if (result == VK_SUCCESS)
369         result = SanitizeExtensions();
370 
371     return result;
372 }
373 
374 const std::bitset<ProcHook::EXTENSION_COUNT>&
GetHookExtensions() const375 CreateInfoWrapper::GetHookExtensions() const {
376     return hook_extensions_;
377 }
378 
379 const std::bitset<ProcHook::EXTENSION_COUNT>&
GetHalExtensions() const380 CreateInfoWrapper::GetHalExtensions() const {
381     return hal_extensions_;
382 }
383 
operator const VkInstanceCreateInfo*() const384 CreateInfoWrapper::operator const VkInstanceCreateInfo*() const {
385     return &instance_info_;
386 }
387 
operator const VkDeviceCreateInfo*() const388 CreateInfoWrapper::operator const VkDeviceCreateInfo*() const {
389     return &dev_info_;
390 }
391 
SanitizePNext()392 VkResult CreateInfoWrapper::SanitizePNext() {
393     const struct StructHeader {
394         VkStructureType type;
395         const void* next;
396     } * header;
397 
398     if (is_instance_) {
399         header = reinterpret_cast<const StructHeader*>(instance_info_.pNext);
400 
401         // skip leading VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFOs
402         while (header &&
403                header->type == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO)
404             header = reinterpret_cast<const StructHeader*>(header->next);
405 
406         instance_info_.pNext = header;
407     } else {
408         header = reinterpret_cast<const StructHeader*>(dev_info_.pNext);
409 
410         // skip leading VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFOs
411         while (header &&
412                header->type == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO)
413             header = reinterpret_cast<const StructHeader*>(header->next);
414 
415         dev_info_.pNext = header;
416     }
417 
418     return VK_SUCCESS;
419 }
420 
SanitizeLayers()421 VkResult CreateInfoWrapper::SanitizeLayers() {
422     auto& layer_names = (is_instance_) ? instance_info_.ppEnabledLayerNames
423                                        : dev_info_.ppEnabledLayerNames;
424     auto& layer_count = (is_instance_) ? instance_info_.enabledLayerCount
425                                        : dev_info_.enabledLayerCount;
426 
427     // remove all layers
428     layer_names = nullptr;
429     layer_count = 0;
430 
431     return VK_SUCCESS;
432 }
433 
SanitizeExtensions()434 VkResult CreateInfoWrapper::SanitizeExtensions() {
435     auto& ext_names = (is_instance_) ? instance_info_.ppEnabledExtensionNames
436                                      : dev_info_.ppEnabledExtensionNames;
437     auto& ext_count = (is_instance_) ? instance_info_.enabledExtensionCount
438                                      : dev_info_.enabledExtensionCount;
439     if (!ext_count)
440         return VK_SUCCESS;
441 
442     VkResult result = InitExtensionFilter();
443     if (result != VK_SUCCESS)
444         return result;
445 
446     for (uint32_t i = 0; i < ext_count; i++)
447         FilterExtension(ext_names[i]);
448 
449     // Enable device extensions that contain physical-device commands, so that
450     // vkGetInstanceProcAddr will return those physical-device commands.
451     if (is_instance_) {
452         hook_extensions_.set(ProcHook::KHR_swapchain);
453     }
454 
455     ext_names = extension_filter_.names;
456     ext_count = extension_filter_.name_count;
457 
458     return VK_SUCCESS;
459 }
460 
QueryExtensionCount(uint32_t & count) const461 VkResult CreateInfoWrapper::QueryExtensionCount(uint32_t& count) const {
462     if (is_instance_) {
463         return Hal::Device().EnumerateInstanceExtensionProperties(
464             nullptr, &count, nullptr);
465     } else {
466         const auto& driver = GetData(physical_dev_).driver;
467         return driver.EnumerateDeviceExtensionProperties(physical_dev_, nullptr,
468                                                          &count, nullptr);
469     }
470 }
471 
EnumerateExtensions(uint32_t & count,VkExtensionProperties * props) const472 VkResult CreateInfoWrapper::EnumerateExtensions(
473     uint32_t& count,
474     VkExtensionProperties* props) const {
475     if (is_instance_) {
476         return Hal::Device().EnumerateInstanceExtensionProperties(
477             nullptr, &count, props);
478     } else {
479         const auto& driver = GetData(physical_dev_).driver;
480         return driver.EnumerateDeviceExtensionProperties(physical_dev_, nullptr,
481                                                          &count, props);
482     }
483 }
484 
InitExtensionFilter()485 VkResult CreateInfoWrapper::InitExtensionFilter() {
486     // query extension count
487     uint32_t count;
488     VkResult result = QueryExtensionCount(count);
489     if (result != VK_SUCCESS || count == 0)
490         return result;
491 
492     auto& filter = extension_filter_;
493     filter.exts =
494         reinterpret_cast<VkExtensionProperties*>(allocator_.pfnAllocation(
495             allocator_.pUserData, sizeof(VkExtensionProperties) * count,
496             alignof(VkExtensionProperties),
497             VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
498     if (!filter.exts)
499         return VK_ERROR_OUT_OF_HOST_MEMORY;
500 
501     // enumerate extensions
502     result = EnumerateExtensions(count, filter.exts);
503     if (result != VK_SUCCESS && result != VK_INCOMPLETE)
504         return result;
505 
506     if (!count)
507         return VK_SUCCESS;
508 
509     filter.ext_count = count;
510 
511     // allocate name array
512     uint32_t enabled_ext_count = (is_instance_)
513                                      ? instance_info_.enabledExtensionCount
514                                      : dev_info_.enabledExtensionCount;
515     count = std::min(filter.ext_count, enabled_ext_count);
516     filter.names = reinterpret_cast<const char**>(allocator_.pfnAllocation(
517         allocator_.pUserData, sizeof(const char*) * count, alignof(const char*),
518         VK_SYSTEM_ALLOCATION_SCOPE_COMMAND));
519     if (!filter.names)
520         return VK_ERROR_OUT_OF_HOST_MEMORY;
521 
522     return VK_SUCCESS;
523 }
524 
FilterExtension(const char * name)525 void CreateInfoWrapper::FilterExtension(const char* name) {
526     auto& filter = extension_filter_;
527 
528     ProcHook::Extension ext_bit = GetProcHookExtension(name);
529     if (is_instance_) {
530         switch (ext_bit) {
531             case ProcHook::KHR_android_surface:
532             case ProcHook::KHR_surface:
533             case ProcHook::EXT_swapchain_colorspace:
534             case ProcHook::KHR_get_surface_capabilities2:
535                 hook_extensions_.set(ext_bit);
536                 // return now as these extensions do not require HAL support
537                 return;
538             case ProcHook::EXT_debug_report:
539                 // both we and HAL can take part in
540                 hook_extensions_.set(ext_bit);
541                 break;
542             case ProcHook::KHR_get_physical_device_properties2:
543             case ProcHook::EXTENSION_UNKNOWN:
544                 // Extensions we don't need to do anything about at this level
545                 break;
546 
547             case ProcHook::KHR_bind_memory2:
548             case ProcHook::KHR_incremental_present:
549             case ProcHook::KHR_shared_presentable_image:
550             case ProcHook::KHR_swapchain:
551             case ProcHook::EXT_hdr_metadata:
552             case ProcHook::ANDROID_external_memory_android_hardware_buffer:
553             case ProcHook::ANDROID_native_buffer:
554             case ProcHook::GOOGLE_display_timing:
555             case ProcHook::EXTENSION_CORE_1_0:
556             case ProcHook::EXTENSION_CORE_1_1:
557             case ProcHook::EXTENSION_COUNT:
558                 // Device and meta extensions. If we ever get here it's a bug in
559                 // our code. But enumerating them lets us avoid having a default
560                 // case, and default hides other bugs.
561                 ALOGE(
562                     "CreateInfoWrapper::FilterExtension: invalid instance "
563                     "extension '%s'. FIX ME",
564                     name);
565                 return;
566 
567             // Don't use a default case. Without it, -Wswitch will tell us
568             // at compile time if someone adds a new ProcHook extension but
569             // doesn't handle it above. That's a real bug that has
570             // not-immediately-obvious effects.
571             //
572             // default:
573             //     break;
574         }
575     } else {
576         switch (ext_bit) {
577             case ProcHook::KHR_swapchain:
578                 // map VK_KHR_swapchain to VK_ANDROID_native_buffer
579                 name = VK_ANDROID_NATIVE_BUFFER_EXTENSION_NAME;
580                 ext_bit = ProcHook::ANDROID_native_buffer;
581                 break;
582             case ProcHook::KHR_incremental_present:
583             case ProcHook::GOOGLE_display_timing:
584             case ProcHook::KHR_shared_presentable_image:
585                 hook_extensions_.set(ext_bit);
586                 // return now as these extensions do not require HAL support
587                 return;
588             case ProcHook::EXT_hdr_metadata:
589             case ProcHook::KHR_bind_memory2:
590                 hook_extensions_.set(ext_bit);
591                 break;
592             case ProcHook::ANDROID_external_memory_android_hardware_buffer:
593             case ProcHook::EXTENSION_UNKNOWN:
594                 // Extensions we don't need to do anything about at this level
595                 break;
596 
597             case ProcHook::KHR_android_surface:
598             case ProcHook::KHR_get_physical_device_properties2:
599             case ProcHook::KHR_get_surface_capabilities2:
600             case ProcHook::KHR_surface:
601             case ProcHook::EXT_debug_report:
602             case ProcHook::EXT_swapchain_colorspace:
603             case ProcHook::ANDROID_native_buffer:
604             case ProcHook::EXTENSION_CORE_1_0:
605             case ProcHook::EXTENSION_CORE_1_1:
606             case ProcHook::EXTENSION_COUNT:
607                 // Instance and meta extensions. If we ever get here it's a bug
608                 // in our code. But enumerating them lets us avoid having a
609                 // default case, and default hides other bugs.
610                 ALOGE(
611                     "CreateInfoWrapper::FilterExtension: invalid device "
612                     "extension '%s'. FIX ME",
613                     name);
614                 return;
615 
616             // Don't use a default case. Without it, -Wswitch will tell us
617             // at compile time if someone adds a new ProcHook extension but
618             // doesn't handle it above. That's a real bug that has
619             // not-immediately-obvious effects.
620             //
621             // default:
622             //     break;
623         }
624     }
625 
626     for (uint32_t i = 0; i < filter.ext_count; i++) {
627         const VkExtensionProperties& props = filter.exts[i];
628         // ignore unknown extensions
629         if (strcmp(name, props.extensionName) != 0)
630             continue;
631 
632         filter.names[filter.name_count++] = name;
633         if (ext_bit != ProcHook::EXTENSION_UNKNOWN) {
634             if (ext_bit == ProcHook::ANDROID_native_buffer)
635                 hook_extensions_.set(ProcHook::KHR_swapchain);
636 
637             hal_extensions_.set(ext_bit);
638         }
639 
640         break;
641     }
642 }
643 
DowngradeApiVersion()644 void CreateInfoWrapper::DowngradeApiVersion() {
645     // If pApplicationInfo is NULL, apiVersion is assumed to be 1.0:
646     if (instance_info_.pApplicationInfo) {
647         application_info_ = *instance_info_.pApplicationInfo;
648         instance_info_.pApplicationInfo = &application_info_;
649         application_info_.apiVersion = VK_API_VERSION_1_0;
650     }
651 }
652 
UpgradeDeviceCoreApiVersion(uint32_t api_version)653 void CreateInfoWrapper::UpgradeDeviceCoreApiVersion(uint32_t api_version) {
654     ALOG_ASSERT(!is_instance_, "Device only API called by instance wrapper.");
655 #pragma clang diagnostic push
656 #pragma clang diagnostic ignored "-Wold-style-cast"
657     api_version ^= VK_VERSION_PATCH(api_version);
658 #pragma clang diagnostic pop
659     // cap the API version to the loader supported highest version
660     if (api_version > VK_API_VERSION_1_1)
661         api_version = VK_API_VERSION_1_1;
662     switch (api_version) {
663         case VK_API_VERSION_1_1:
664             hook_extensions_.set(ProcHook::EXTENSION_CORE_1_1);
665             hal_extensions_.set(ProcHook::EXTENSION_CORE_1_1);
666             [[clang::fallthrough]];
667         case VK_API_VERSION_1_0:
668             break;
669         default:
670             ALOGD("Unknown upgrade API version[%u]", api_version);
671             break;
672     }
673 }
674 
DefaultAllocate(void *,size_t size,size_t alignment,VkSystemAllocationScope)675 VKAPI_ATTR void* DefaultAllocate(void*,
676                                  size_t size,
677                                  size_t alignment,
678                                  VkSystemAllocationScope) {
679     void* ptr = nullptr;
680     // Vulkan requires 'alignment' to be a power of two, but posix_memalign
681     // additionally requires that it be at least sizeof(void*).
682     int ret = posix_memalign(&ptr, std::max(alignment, sizeof(void*)), size);
683     ALOGD_CALLSTACK("Allocate: size=%zu align=%zu => (%d) %p", size, alignment,
684                     ret, ptr);
685     return ret == 0 ? ptr : nullptr;
686 }
687 
DefaultReallocate(void *,void * ptr,size_t size,size_t alignment,VkSystemAllocationScope)688 VKAPI_ATTR void* DefaultReallocate(void*,
689                                    void* ptr,
690                                    size_t size,
691                                    size_t alignment,
692                                    VkSystemAllocationScope) {
693     if (size == 0) {
694         free(ptr);
695         return nullptr;
696     }
697 
698     // TODO(jessehall): Right now we never shrink allocations; if the new
699     // request is smaller than the existing chunk, we just continue using it.
700     // Right now the loader never reallocs, so this doesn't matter. If that
701     // changes, or if this code is copied into some other project, this should
702     // probably have a heuristic to allocate-copy-free when doing so will save
703     // "enough" space.
704     size_t old_size = ptr ? malloc_usable_size(ptr) : 0;
705     if (size <= old_size)
706         return ptr;
707 
708     void* new_ptr = nullptr;
709     if (posix_memalign(&new_ptr, std::max(alignment, sizeof(void*)), size) != 0)
710         return nullptr;
711     if (ptr) {
712         memcpy(new_ptr, ptr, std::min(old_size, size));
713         free(ptr);
714     }
715     return new_ptr;
716 }
717 
DefaultFree(void *,void * ptr)718 VKAPI_ATTR void DefaultFree(void*, void* ptr) {
719     ALOGD_CALLSTACK("Free: %p", ptr);
720     free(ptr);
721 }
722 
AllocateInstanceData(const VkAllocationCallbacks & allocator)723 InstanceData* AllocateInstanceData(const VkAllocationCallbacks& allocator) {
724     void* data_mem = allocator.pfnAllocation(
725         allocator.pUserData, sizeof(InstanceData), alignof(InstanceData),
726         VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
727     if (!data_mem)
728         return nullptr;
729 
730     return new (data_mem) InstanceData(allocator);
731 }
732 
FreeInstanceData(InstanceData * data,const VkAllocationCallbacks & allocator)733 void FreeInstanceData(InstanceData* data,
734                       const VkAllocationCallbacks& allocator) {
735     data->~InstanceData();
736     allocator.pfnFree(allocator.pUserData, data);
737 }
738 
AllocateDeviceData(const VkAllocationCallbacks & allocator,const DebugReportCallbackList & debug_report_callbacks)739 DeviceData* AllocateDeviceData(
740     const VkAllocationCallbacks& allocator,
741     const DebugReportCallbackList& debug_report_callbacks) {
742     void* data_mem = allocator.pfnAllocation(
743         allocator.pUserData, sizeof(DeviceData), alignof(DeviceData),
744         VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
745     if (!data_mem)
746         return nullptr;
747 
748     return new (data_mem) DeviceData(allocator, debug_report_callbacks);
749 }
750 
FreeDeviceData(DeviceData * data,const VkAllocationCallbacks & allocator)751 void FreeDeviceData(DeviceData* data, const VkAllocationCallbacks& allocator) {
752     data->~DeviceData();
753     allocator.pfnFree(allocator.pUserData, data);
754 }
755 
756 }  // anonymous namespace
757 
OpenHAL()758 bool OpenHAL() {
759     return Hal::Open();
760 }
761 
GetDefaultAllocator()762 const VkAllocationCallbacks& GetDefaultAllocator() {
763     static const VkAllocationCallbacks kDefaultAllocCallbacks = {
764         .pUserData = nullptr,
765         .pfnAllocation = DefaultAllocate,
766         .pfnReallocation = DefaultReallocate,
767         .pfnFree = DefaultFree,
768     };
769 
770     return kDefaultAllocCallbacks;
771 }
772 
GetInstanceProcAddr(VkInstance instance,const char * pName)773 PFN_vkVoidFunction GetInstanceProcAddr(VkInstance instance, const char* pName) {
774     const ProcHook* hook = GetProcHook(pName);
775     if (!hook)
776         return Hal::Device().GetInstanceProcAddr(instance, pName);
777 
778     if (!instance) {
779         if (hook->type == ProcHook::GLOBAL)
780             return hook->proc;
781 
782         // v0 layers expect
783         //
784         //   vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkCreateDevice");
785         //
786         // to work.
787         if (strcmp(pName, "vkCreateDevice") == 0)
788             return hook->proc;
789 
790         ALOGE(
791             "internal vkGetInstanceProcAddr called for %s without an instance",
792             pName);
793 
794         return nullptr;
795     }
796 
797     PFN_vkVoidFunction proc;
798 
799     switch (hook->type) {
800         case ProcHook::INSTANCE:
801             proc = (GetData(instance).hook_extensions[hook->extension])
802                        ? hook->proc
803                        : nullptr;
804             break;
805         case ProcHook::DEVICE:
806             proc = (hook->extension == ProcHook::EXTENSION_CORE_1_0)
807                        ? hook->proc
808                        : hook->checked_proc;
809             break;
810         default:
811             ALOGE(
812                 "internal vkGetInstanceProcAddr called for %s with an instance",
813                 pName);
814             proc = nullptr;
815             break;
816     }
817 
818     return proc;
819 }
820 
GetDeviceProcAddr(VkDevice device,const char * pName)821 PFN_vkVoidFunction GetDeviceProcAddr(VkDevice device, const char* pName) {
822     const ProcHook* hook = GetProcHook(pName);
823     if (!hook)
824         return GetData(device).driver.GetDeviceProcAddr(device, pName);
825 
826     if (hook->type != ProcHook::DEVICE) {
827         ALOGE("internal vkGetDeviceProcAddr called for %s", pName);
828         return nullptr;
829     }
830 
831     return (GetData(device).hook_extensions[hook->extension]) ? hook->proc
832                                                               : nullptr;
833 }
834 
EnumerateInstanceExtensionProperties(const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)835 VkResult EnumerateInstanceExtensionProperties(
836     const char* pLayerName,
837     uint32_t* pPropertyCount,
838     VkExtensionProperties* pProperties) {
839 
840     android::Vector<VkExtensionProperties> loader_extensions;
841     loader_extensions.push_back({
842         VK_KHR_SURFACE_EXTENSION_NAME,
843         VK_KHR_SURFACE_SPEC_VERSION});
844     loader_extensions.push_back({
845         VK_KHR_ANDROID_SURFACE_EXTENSION_NAME,
846         VK_KHR_ANDROID_SURFACE_SPEC_VERSION});
847     loader_extensions.push_back({
848         VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME,
849         VK_EXT_SWAPCHAIN_COLOR_SPACE_SPEC_VERSION});
850     loader_extensions.push_back({
851         VK_KHR_GET_SURFACE_CAPABILITIES_2_EXTENSION_NAME,
852         VK_KHR_GET_SURFACE_CAPABILITIES_2_SPEC_VERSION});
853 
854     static const VkExtensionProperties loader_debug_report_extension = {
855         VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_EXT_DEBUG_REPORT_SPEC_VERSION,
856     };
857 
858     // enumerate our extensions first
859     if (!pLayerName && pProperties) {
860         uint32_t count = std::min(
861             *pPropertyCount, static_cast<uint32_t>(loader_extensions.size()));
862 
863         std::copy_n(loader_extensions.begin(), count, pProperties);
864 
865         if (count < loader_extensions.size()) {
866             *pPropertyCount = count;
867             return VK_INCOMPLETE;
868         }
869 
870         pProperties += count;
871         *pPropertyCount -= count;
872 
873         if (Hal::Get().GetDebugReportIndex() < 0) {
874             if (!*pPropertyCount) {
875                 *pPropertyCount = count;
876                 return VK_INCOMPLETE;
877             }
878 
879             pProperties[0] = loader_debug_report_extension;
880             pProperties += 1;
881             *pPropertyCount -= 1;
882         }
883     }
884 
885     ATRACE_BEGIN("driver.EnumerateInstanceExtensionProperties");
886     VkResult result = Hal::Device().EnumerateInstanceExtensionProperties(
887         pLayerName, pPropertyCount, pProperties);
888     ATRACE_END();
889 
890     if (!pLayerName && (result == VK_SUCCESS || result == VK_INCOMPLETE)) {
891         int idx = Hal::Get().GetDebugReportIndex();
892         if (idx < 0) {
893             *pPropertyCount += 1;
894         } else if (pProperties &&
895                    static_cast<uint32_t>(idx) < *pPropertyCount) {
896             pProperties[idx].specVersion =
897                 std::min(pProperties[idx].specVersion,
898                          loader_debug_report_extension.specVersion);
899         }
900 
901         *pPropertyCount += loader_extensions.size();
902     }
903 
904     return result;
905 }
906 
QueryPresentationProperties(VkPhysicalDevice physicalDevice,VkPhysicalDevicePresentationPropertiesANDROID * presentation_properties)907 bool QueryPresentationProperties(
908     VkPhysicalDevice physicalDevice,
909     VkPhysicalDevicePresentationPropertiesANDROID *presentation_properties)
910 {
911     const InstanceData& data = GetData(physicalDevice);
912 
913     // GPDP2 must be present and enabled on the instance.
914     if (!data.driver.GetPhysicalDeviceProperties2KHR &&
915         !data.driver.GetPhysicalDeviceProperties2)
916         return false;
917 
918     // Request the android-specific presentation properties via GPDP2
919     VkPhysicalDeviceProperties2KHR properties = {
920         VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR,
921         presentation_properties,
922         {}
923     };
924 
925 #pragma clang diagnostic push
926 #pragma clang diagnostic ignored "-Wold-style-cast"
927     presentation_properties->sType =
928         VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENTATION_PROPERTIES_ANDROID;
929 #pragma clang diagnostic pop
930     presentation_properties->pNext = nullptr;
931     presentation_properties->sharedImage = VK_FALSE;
932 
933     if (data.driver.GetPhysicalDeviceProperties2KHR) {
934         data.driver.GetPhysicalDeviceProperties2KHR(physicalDevice,
935                                                     &properties);
936     } else {
937         data.driver.GetPhysicalDeviceProperties2(physicalDevice, &properties);
938     }
939 
940     return true;
941 }
942 
EnumerateDeviceExtensionProperties(VkPhysicalDevice physicalDevice,const char * pLayerName,uint32_t * pPropertyCount,VkExtensionProperties * pProperties)943 VkResult EnumerateDeviceExtensionProperties(
944     VkPhysicalDevice physicalDevice,
945     const char* pLayerName,
946     uint32_t* pPropertyCount,
947     VkExtensionProperties* pProperties) {
948     const InstanceData& data = GetData(physicalDevice);
949     // extensions that are unconditionally exposed by the loader
950     android::Vector<VkExtensionProperties> loader_extensions;
951     loader_extensions.push_back({
952         VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME,
953         VK_KHR_INCREMENTAL_PRESENT_SPEC_VERSION});
954 
955     bool hdrBoardConfig =
956         getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasHDRDisplay>(
957             false);
958     if (hdrBoardConfig) {
959         loader_extensions.push_back({VK_EXT_HDR_METADATA_EXTENSION_NAME,
960                                      VK_EXT_HDR_METADATA_SPEC_VERSION});
961     }
962 
963     VkPhysicalDevicePresentationPropertiesANDROID presentation_properties;
964     if (QueryPresentationProperties(physicalDevice, &presentation_properties) &&
965         presentation_properties.sharedImage) {
966         loader_extensions.push_back({
967             VK_KHR_SHARED_PRESENTABLE_IMAGE_EXTENSION_NAME,
968             VK_KHR_SHARED_PRESENTABLE_IMAGE_SPEC_VERSION});
969     }
970 
971     // conditionally add VK_GOOGLE_display_timing if present timestamps are
972     // supported by the driver:
973     const std::string timestamp_property("service.sf.present_timestamp");
974     android::base::WaitForPropertyCreation(timestamp_property);
975     if (android::base::GetBoolProperty(timestamp_property, true)) {
976         loader_extensions.push_back({
977                 VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME,
978                 VK_GOOGLE_DISPLAY_TIMING_SPEC_VERSION});
979     }
980 
981     // enumerate our extensions first
982     if (!pLayerName && pProperties) {
983         uint32_t count = std::min(
984             *pPropertyCount, static_cast<uint32_t>(loader_extensions.size()));
985 
986         std::copy_n(loader_extensions.begin(), count, pProperties);
987 
988         if (count < loader_extensions.size()) {
989             *pPropertyCount = count;
990             return VK_INCOMPLETE;
991         }
992 
993         pProperties += count;
994         *pPropertyCount -= count;
995     }
996 
997     ATRACE_BEGIN("driver.EnumerateDeviceExtensionProperties");
998     VkResult result = data.driver.EnumerateDeviceExtensionProperties(
999         physicalDevice, pLayerName, pPropertyCount, pProperties);
1000     ATRACE_END();
1001 
1002     if (pProperties) {
1003         // map VK_ANDROID_native_buffer to VK_KHR_swapchain
1004         for (uint32_t i = 0; i < *pPropertyCount; i++) {
1005             auto& prop = pProperties[i];
1006 
1007             if (strcmp(prop.extensionName,
1008                        VK_ANDROID_NATIVE_BUFFER_EXTENSION_NAME) != 0)
1009                 continue;
1010 
1011             memcpy(prop.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME,
1012                    sizeof(VK_KHR_SWAPCHAIN_EXTENSION_NAME));
1013 
1014             if (prop.specVersion >= 8) {
1015                 prop.specVersion = VK_KHR_SWAPCHAIN_SPEC_VERSION;
1016             } else {
1017                 prop.specVersion = 68;
1018             }
1019         }
1020     }
1021 
1022     // restore loader extension count
1023     if (!pLayerName && (result == VK_SUCCESS || result == VK_INCOMPLETE)) {
1024         *pPropertyCount += loader_extensions.size();
1025     }
1026 
1027     return result;
1028 }
1029 
CreateInstance(const VkInstanceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkInstance * pInstance)1030 VkResult CreateInstance(const VkInstanceCreateInfo* pCreateInfo,
1031                         const VkAllocationCallbacks* pAllocator,
1032                         VkInstance* pInstance) {
1033     const VkAllocationCallbacks& data_allocator =
1034         (pAllocator) ? *pAllocator : GetDefaultAllocator();
1035 
1036     CreateInfoWrapper wrapper(*pCreateInfo, data_allocator);
1037     VkResult result = wrapper.Validate();
1038     if (result != VK_SUCCESS)
1039         return result;
1040 
1041     ATRACE_BEGIN("AllocateInstanceData");
1042     InstanceData* data = AllocateInstanceData(data_allocator);
1043     ATRACE_END();
1044     if (!data)
1045         return VK_ERROR_OUT_OF_HOST_MEMORY;
1046 
1047     data->hook_extensions |= wrapper.GetHookExtensions();
1048 
1049     ATRACE_BEGIN("autoDowngradeApiVersion");
1050 #pragma clang diagnostic push
1051 #pragma clang diagnostic ignored "-Wold-style-cast"
1052     uint32_t api_version = ((pCreateInfo->pApplicationInfo)
1053                                 ? pCreateInfo->pApplicationInfo->apiVersion
1054                                 : VK_API_VERSION_1_0);
1055     uint32_t api_major_version = VK_VERSION_MAJOR(api_version);
1056     uint32_t api_minor_version = VK_VERSION_MINOR(api_version);
1057     uint32_t icd_api_version;
1058     PFN_vkEnumerateInstanceVersion pfn_enumerate_instance_version =
1059         reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
1060             Hal::Device().GetInstanceProcAddr(nullptr,
1061                                               "vkEnumerateInstanceVersion"));
1062     if (!pfn_enumerate_instance_version) {
1063         icd_api_version = VK_API_VERSION_1_0;
1064     } else {
1065         ATRACE_BEGIN("pfn_enumerate_instance_version");
1066         result = (*pfn_enumerate_instance_version)(&icd_api_version);
1067         ATRACE_END();
1068     }
1069     uint32_t icd_api_major_version = VK_VERSION_MAJOR(icd_api_version);
1070     uint32_t icd_api_minor_version = VK_VERSION_MINOR(icd_api_version);
1071 
1072     if ((icd_api_major_version == 1) && (icd_api_minor_version == 0) &&
1073         ((api_major_version > 1) || (api_minor_version > 0))) {
1074         api_version = VK_API_VERSION_1_0;
1075         wrapper.DowngradeApiVersion();
1076     }
1077 #pragma clang diagnostic pop
1078     ATRACE_END();
1079 
1080     // call into the driver
1081     VkInstance instance;
1082     ATRACE_BEGIN("driver.CreateInstance");
1083     result = Hal::Device().CreateInstance(
1084         static_cast<const VkInstanceCreateInfo*>(wrapper), pAllocator,
1085         &instance);
1086     ATRACE_END();
1087     if (result != VK_SUCCESS) {
1088         FreeInstanceData(data, data_allocator);
1089         return result;
1090     }
1091 
1092     // initialize InstanceDriverTable
1093     if (!SetData(instance, *data) ||
1094         !InitDriverTable(instance, Hal::Device().GetInstanceProcAddr,
1095                          wrapper.GetHalExtensions())) {
1096         data->driver.DestroyInstance = reinterpret_cast<PFN_vkDestroyInstance>(
1097             Hal::Device().GetInstanceProcAddr(instance, "vkDestroyInstance"));
1098         if (data->driver.DestroyInstance)
1099             data->driver.DestroyInstance(instance, pAllocator);
1100 
1101         FreeInstanceData(data, data_allocator);
1102 
1103         return VK_ERROR_INCOMPATIBLE_DRIVER;
1104     }
1105 
1106     data->get_device_proc_addr = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
1107         Hal::Device().GetInstanceProcAddr(instance, "vkGetDeviceProcAddr"));
1108     if (!data->get_device_proc_addr) {
1109         data->driver.DestroyInstance(instance, pAllocator);
1110         FreeInstanceData(data, data_allocator);
1111 
1112         return VK_ERROR_INCOMPATIBLE_DRIVER;
1113     }
1114 
1115     *pInstance = instance;
1116 
1117     return VK_SUCCESS;
1118 }
1119 
DestroyInstance(VkInstance instance,const VkAllocationCallbacks * pAllocator)1120 void DestroyInstance(VkInstance instance,
1121                      const VkAllocationCallbacks* pAllocator) {
1122     InstanceData& data = GetData(instance);
1123     data.driver.DestroyInstance(instance, pAllocator);
1124 
1125     VkAllocationCallbacks local_allocator;
1126     if (!pAllocator) {
1127         local_allocator = data.allocator;
1128         pAllocator = &local_allocator;
1129     }
1130 
1131     FreeInstanceData(&data, *pAllocator);
1132 }
1133 
CreateDevice(VkPhysicalDevice physicalDevice,const VkDeviceCreateInfo * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkDevice * pDevice)1134 VkResult CreateDevice(VkPhysicalDevice physicalDevice,
1135                       const VkDeviceCreateInfo* pCreateInfo,
1136                       const VkAllocationCallbacks* pAllocator,
1137                       VkDevice* pDevice) {
1138     const InstanceData& instance_data = GetData(physicalDevice);
1139     const VkAllocationCallbacks& data_allocator =
1140         (pAllocator) ? *pAllocator : instance_data.allocator;
1141 
1142     CreateInfoWrapper wrapper(physicalDevice, *pCreateInfo, data_allocator);
1143     VkResult result = wrapper.Validate();
1144     if (result != VK_SUCCESS)
1145         return result;
1146 
1147     ATRACE_BEGIN("AllocateDeviceData");
1148     DeviceData* data = AllocateDeviceData(data_allocator,
1149                                           instance_data.debug_report_callbacks);
1150     ATRACE_END();
1151     if (!data)
1152         return VK_ERROR_OUT_OF_HOST_MEMORY;
1153 
1154     VkPhysicalDeviceProperties properties;
1155     ATRACE_BEGIN("driver.GetPhysicalDeviceProperties");
1156     instance_data.driver.GetPhysicalDeviceProperties(physicalDevice,
1157                                                      &properties);
1158     ATRACE_END();
1159 
1160     wrapper.UpgradeDeviceCoreApiVersion(properties.apiVersion);
1161     data->hook_extensions |= wrapper.GetHookExtensions();
1162 
1163     // call into the driver
1164     VkDevice dev;
1165     ATRACE_BEGIN("driver.CreateDevice");
1166     result = instance_data.driver.CreateDevice(
1167         physicalDevice, static_cast<const VkDeviceCreateInfo*>(wrapper),
1168         pAllocator, &dev);
1169     ATRACE_END();
1170     if (result != VK_SUCCESS) {
1171         FreeDeviceData(data, data_allocator);
1172         return result;
1173     }
1174 
1175     // initialize DeviceDriverTable
1176     if (!SetData(dev, *data) ||
1177         !InitDriverTable(dev, instance_data.get_device_proc_addr,
1178                          wrapper.GetHalExtensions())) {
1179         data->driver.DestroyDevice = reinterpret_cast<PFN_vkDestroyDevice>(
1180             instance_data.get_device_proc_addr(dev, "vkDestroyDevice"));
1181         if (data->driver.DestroyDevice)
1182             data->driver.DestroyDevice(dev, pAllocator);
1183 
1184         FreeDeviceData(data, data_allocator);
1185 
1186         return VK_ERROR_INCOMPATIBLE_DRIVER;
1187     }
1188 
1189     // sanity check ANDROID_native_buffer implementation, whose set of
1190     // entrypoints varies according to the spec version.
1191     if ((wrapper.GetHalExtensions()[ProcHook::ANDROID_native_buffer]) &&
1192         !data->driver.GetSwapchainGrallocUsageANDROID &&
1193         !data->driver.GetSwapchainGrallocUsage2ANDROID) {
1194         ALOGE("Driver's implementation of ANDROID_native_buffer is broken;"
1195               " must expose at least one of "
1196               "vkGetSwapchainGrallocUsageANDROID or "
1197               "vkGetSwapchainGrallocUsage2ANDROID");
1198 
1199         data->driver.DestroyDevice(dev, pAllocator);
1200         FreeDeviceData(data, data_allocator);
1201 
1202         return VK_ERROR_INCOMPATIBLE_DRIVER;
1203     }
1204 
1205     if (properties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU) {
1206         // Log that the app is hitting software Vulkan implementation
1207         android::GraphicsEnv::getInstance().setTargetStats(
1208             android::GraphicsEnv::Stats::CPU_VULKAN_IN_USE);
1209     }
1210 
1211     data->driver_device = dev;
1212     data->driver_version = properties.driverVersion;
1213 
1214     *pDevice = dev;
1215 
1216     return VK_SUCCESS;
1217 }
1218 
DestroyDevice(VkDevice device,const VkAllocationCallbacks * pAllocator)1219 void DestroyDevice(VkDevice device, const VkAllocationCallbacks* pAllocator) {
1220     DeviceData& data = GetData(device);
1221     data.driver.DestroyDevice(device, pAllocator);
1222 
1223     VkAllocationCallbacks local_allocator;
1224     if (!pAllocator) {
1225         local_allocator = data.allocator;
1226         pAllocator = &local_allocator;
1227     }
1228 
1229     FreeDeviceData(&data, *pAllocator);
1230 }
1231 
EnumeratePhysicalDevices(VkInstance instance,uint32_t * pPhysicalDeviceCount,VkPhysicalDevice * pPhysicalDevices)1232 VkResult EnumeratePhysicalDevices(VkInstance instance,
1233                                   uint32_t* pPhysicalDeviceCount,
1234                                   VkPhysicalDevice* pPhysicalDevices) {
1235     ATRACE_CALL();
1236 
1237     const auto& data = GetData(instance);
1238 
1239     VkResult result = data.driver.EnumeratePhysicalDevices(
1240         instance, pPhysicalDeviceCount, pPhysicalDevices);
1241     if ((result == VK_SUCCESS || result == VK_INCOMPLETE) && pPhysicalDevices) {
1242         for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++)
1243             SetData(pPhysicalDevices[i], data);
1244     }
1245 
1246     return result;
1247 }
1248 
EnumeratePhysicalDeviceGroups(VkInstance instance,uint32_t * pPhysicalDeviceGroupCount,VkPhysicalDeviceGroupProperties * pPhysicalDeviceGroupProperties)1249 VkResult EnumeratePhysicalDeviceGroups(
1250     VkInstance instance,
1251     uint32_t* pPhysicalDeviceGroupCount,
1252     VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties) {
1253     ATRACE_CALL();
1254 
1255     VkResult result = VK_SUCCESS;
1256     const auto& data = GetData(instance);
1257 
1258     if (!data.driver.EnumeratePhysicalDeviceGroups) {
1259         uint32_t device_count = 0;
1260         result = EnumeratePhysicalDevices(instance, &device_count, nullptr);
1261         if (result < 0)
1262             return result;
1263 
1264         if (!pPhysicalDeviceGroupProperties) {
1265             *pPhysicalDeviceGroupCount = device_count;
1266             return result;
1267         }
1268 
1269         if (!device_count) {
1270             *pPhysicalDeviceGroupCount = 0;
1271             return result;
1272         }
1273         device_count = std::min(device_count, *pPhysicalDeviceGroupCount);
1274         if (!device_count)
1275             return VK_INCOMPLETE;
1276 
1277         android::Vector<VkPhysicalDevice> devices;
1278         devices.resize(device_count);
1279         *pPhysicalDeviceGroupCount = device_count;
1280         result = EnumeratePhysicalDevices(instance, &device_count,
1281                                           devices.editArray());
1282         if (result < 0)
1283             return result;
1284 
1285         for (uint32_t i = 0; i < device_count; ++i) {
1286             pPhysicalDeviceGroupProperties[i].physicalDeviceCount = 1;
1287             pPhysicalDeviceGroupProperties[i].physicalDevices[0] = devices[i];
1288             pPhysicalDeviceGroupProperties[i].subsetAllocation = 0;
1289         }
1290     } else {
1291         result = data.driver.EnumeratePhysicalDeviceGroups(
1292             instance, pPhysicalDeviceGroupCount,
1293             pPhysicalDeviceGroupProperties);
1294         if ((result == VK_SUCCESS || result == VK_INCOMPLETE) &&
1295             *pPhysicalDeviceGroupCount && pPhysicalDeviceGroupProperties) {
1296             for (uint32_t i = 0; i < *pPhysicalDeviceGroupCount; i++) {
1297                 for (uint32_t j = 0;
1298                      j < pPhysicalDeviceGroupProperties[i].physicalDeviceCount;
1299                      j++) {
1300                     SetData(
1301                         pPhysicalDeviceGroupProperties[i].physicalDevices[j],
1302                         data);
1303                 }
1304             }
1305         }
1306     }
1307 
1308     return result;
1309 }
1310 
GetDeviceQueue(VkDevice device,uint32_t queueFamilyIndex,uint32_t queueIndex,VkQueue * pQueue)1311 void GetDeviceQueue(VkDevice device,
1312                     uint32_t queueFamilyIndex,
1313                     uint32_t queueIndex,
1314                     VkQueue* pQueue) {
1315     ATRACE_CALL();
1316 
1317     const auto& data = GetData(device);
1318 
1319     data.driver.GetDeviceQueue(device, queueFamilyIndex, queueIndex, pQueue);
1320     SetData(*pQueue, data);
1321 }
1322 
GetDeviceQueue2(VkDevice device,const VkDeviceQueueInfo2 * pQueueInfo,VkQueue * pQueue)1323 void GetDeviceQueue2(VkDevice device,
1324                      const VkDeviceQueueInfo2* pQueueInfo,
1325                      VkQueue* pQueue) {
1326     ATRACE_CALL();
1327 
1328     const auto& data = GetData(device);
1329 
1330     data.driver.GetDeviceQueue2(device, pQueueInfo, pQueue);
1331     if (*pQueue != VK_NULL_HANDLE) SetData(*pQueue, data);
1332 }
1333 
1334 VKAPI_ATTR VkResult
AllocateCommandBuffers(VkDevice device,const VkCommandBufferAllocateInfo * pAllocateInfo,VkCommandBuffer * pCommandBuffers)1335 AllocateCommandBuffers(VkDevice device,
1336                        const VkCommandBufferAllocateInfo* pAllocateInfo,
1337                        VkCommandBuffer* pCommandBuffers) {
1338     ATRACE_CALL();
1339 
1340     const auto& data = GetData(device);
1341 
1342     VkResult result = data.driver.AllocateCommandBuffers(device, pAllocateInfo,
1343                                                          pCommandBuffers);
1344     if (result == VK_SUCCESS) {
1345         for (uint32_t i = 0; i < pAllocateInfo->commandBufferCount; i++)
1346             SetData(pCommandBuffers[i], data);
1347     }
1348 
1349     return result;
1350 }
1351 
1352 }  // namespace driver
1353 }  // namespace vulkan
1354