blob: be39b247490ceba9ef8fbd745eb72fae292ff843 [file] [log] [blame]
Jesse Halld02edcb2015-09-08 07:44:48 -07001/*
2 * Copyright 2015 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
Michael Lentine9dbe67f2015-09-16 15:53:50 -050017//#define LOG_NDEBUG 0
18
Jesse Hall04f4f472015-08-16 19:51:04 -070019// module header
20#include "loader.h"
21// standard C headers
Michael Lentine03c64b02015-08-26 18:27:26 -050022#include <dirent.h>
23#include <dlfcn.h>
Jesse Hall04f4f472015-08-16 19:51:04 -070024#include <inttypes.h>
25#include <malloc.h>
26#include <pthread.h>
27#include <string.h>
28// standard C++ headers
29#include <algorithm>
30#include <mutex>
Michael Lentine03c64b02015-08-26 18:27:26 -050031#include <sstream>
32#include <string>
33#include <unordered_map>
34#include <vector>
Jesse Hall04f4f472015-08-16 19:51:04 -070035// platform/library headers
Michael Lentine03c64b02015-08-26 18:27:26 -050036#include <cutils/properties.h>
Jesse Hall04f4f472015-08-16 19:51:04 -070037#include <hardware/hwvulkan.h>
38#include <log/log.h>
Michael Lentinecd6cabf2015-09-14 17:32:59 -050039#include <vulkan/vk_debug_report_lunarg.h>
Michael Lentine1c69b9e2015-09-14 13:26:59 -050040#include <vulkan/vulkan_loader_data.h>
Jesse Hall04f4f472015-08-16 19:51:04 -070041
42using namespace vulkan;
43
44static const uint32_t kMaxPhysicalDevices = 4;
45
Michael Lentine03c64b02015-08-26 18:27:26 -050046namespace {
47
48// These definitions are taken from the LunarG Vulkan Loader. They are used to
49// enforce compatability between the Loader and Layers.
50typedef void* (*PFN_vkGetProcAddr)(void* obj, const char* pName);
51
52typedef struct VkLayerLinkedListElem_ {
53 PFN_vkGetProcAddr get_proc_addr;
54 void* next_element;
55 void* base_object;
56} VkLayerLinkedListElem;
57
58// Define Handle typedef to be void* as returned from dlopen.
59typedef void* SharedLibraryHandle;
60
61// Custom versions of std classes that use the vulkan alloc callback.
62template <class T>
63class CallbackAllocator {
64 public:
65 typedef T value_type;
66
67 CallbackAllocator(const VkAllocCallbacks* alloc_input)
68 : alloc(alloc_input) {}
69
70 template <class T2>
71 CallbackAllocator(const CallbackAllocator<T2>& other)
72 : alloc(other.alloc) {}
73
74 T* allocate(std::size_t n) {
75 void* mem = alloc->pfnAlloc(alloc->pUserData, n * sizeof(T), alignof(T),
76 VK_SYSTEM_ALLOC_TYPE_INTERNAL);
77 return static_cast<T*>(mem);
78 }
79
80 void deallocate(T* array, std::size_t /*n*/) {
81 alloc->pfnFree(alloc->pUserData, array);
82 }
83
84 const VkAllocCallbacks* alloc;
85};
86// These are needed in order to move Strings
87template <class T>
88bool operator==(const CallbackAllocator<T>& alloc1,
89 const CallbackAllocator<T>& alloc2) {
90 return alloc1.alloc == alloc2.alloc;
91}
92template <class T>
93bool operator!=(const CallbackAllocator<T>& alloc1,
94 const CallbackAllocator<T>& alloc2) {
95 return !(alloc1 == alloc2);
96}
97
98template <class Key,
99 class T,
100 class Hash = std::hash<Key>,
101 class Pred = std::equal_to<Key> >
102using UnorderedMap =
103 std::unordered_map<Key,
104 T,
105 Hash,
106 Pred,
107 CallbackAllocator<std::pair<const Key, T> > >;
108
109template <class T>
110using Vector = std::vector<T, CallbackAllocator<T> >;
111
112typedef std::basic_string<char,
113 std::char_traits<char>,
114 CallbackAllocator<char> > String;
115
116} // namespace
117
118// -----------------------------------------------------------------------------
119
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500120namespace {
121
122struct LayerData {
123 String path;
124 SharedLibraryHandle handle;
125 uint32_t ref_count;
126};
127
128typedef UnorderedMap<String, LayerData>::iterator LayerMapIterator;
129
130} // namespace
131
Jesse Hall04f4f472015-08-16 19:51:04 -0700132struct VkInstance_T {
133 VkInstance_T(const VkAllocCallbacks* alloc_callbacks)
Michael Lentine03c64b02015-08-26 18:27:26 -0500134 : vtbl(&vtbl_storage),
135 alloc(alloc_callbacks),
136 num_physical_devices(0),
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500137 layers(CallbackAllocator<std::pair<String, LayerData> >(alloc)),
138 active_layers(CallbackAllocator<String>(alloc)) {
139 pthread_mutex_init(&layer_lock, 0);
Jesse Hall04f4f472015-08-16 19:51:04 -0700140 memset(&vtbl_storage, 0, sizeof(vtbl_storage));
141 memset(physical_devices, 0, sizeof(physical_devices));
142 memset(&drv.vtbl, 0, sizeof(drv.vtbl));
143 drv.GetDeviceProcAddr = nullptr;
144 drv.num_physical_devices = 0;
145 }
146
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500147 ~VkInstance_T() { pthread_mutex_destroy(&layer_lock); }
148
Jesse Hall04f4f472015-08-16 19:51:04 -0700149 InstanceVtbl* vtbl;
150 InstanceVtbl vtbl_storage;
151
152 const VkAllocCallbacks* alloc;
153 uint32_t num_physical_devices;
154 VkPhysicalDevice physical_devices[kMaxPhysicalDevices];
155
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500156 pthread_mutex_t layer_lock;
157 // Map of layer names to layer data
158 UnorderedMap<String, LayerData> layers;
159 // Vector of layers active for this instance
160 Vector<LayerMapIterator> active_layers;
Michael Lentinecd6cabf2015-09-14 17:32:59 -0500161 VkDbgMsgCallback message;
Michael Lentine03c64b02015-08-26 18:27:26 -0500162
Jesse Hall04f4f472015-08-16 19:51:04 -0700163 struct Driver {
164 // Pointers to driver entry points. Used explicitly by the loader; not
165 // set as the dispatch table for any objects.
166 InstanceVtbl vtbl;
167
168 // Pointer to the driver's get_device_proc_addr, must be valid for any
169 // of the driver's physical devices. Not part of the InstanceVtbl since
170 // it's not an Instance/PhysicalDevice function.
171 PFN_vkGetDeviceProcAddr GetDeviceProcAddr;
172
173 // Number of physical devices owned by this driver.
174 uint32_t num_physical_devices;
175 } drv; // may eventually be an array
176};
177
178// -----------------------------------------------------------------------------
179
180namespace {
181
182typedef VkInstance_T Instance;
183
184struct Device {
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500185 Device(Instance* instance_input)
186 : instance(instance_input),
187 active_layers(CallbackAllocator<LayerMapIterator>(instance->alloc)) {
Jesse Hall04f4f472015-08-16 19:51:04 -0700188 memset(&vtbl_storage, 0, sizeof(vtbl_storage));
189 vtbl_storage.device = this;
190 }
191 DeviceVtbl vtbl_storage;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500192 Instance* instance;
193 // Vector of layers active for this device
194 Vector<LayerMapIterator> active_layers;
Jesse Hall04f4f472015-08-16 19:51:04 -0700195};
196
197// -----------------------------------------------------------------------------
198// Utility Code
199
200inline const InstanceVtbl* GetVtbl(VkPhysicalDevice physicalDevice) {
201 return *reinterpret_cast<InstanceVtbl**>(physicalDevice);
202}
203
204inline const DeviceVtbl* GetVtbl(VkDevice device) {
205 return *reinterpret_cast<DeviceVtbl**>(device);
206}
Jesse Halld7b994a2015-09-07 14:17:37 -0700207inline const DeviceVtbl* GetVtbl(VkQueue queue) {
208 return *reinterpret_cast<DeviceVtbl**>(queue);
209}
Jesse Hall04f4f472015-08-16 19:51:04 -0700210
211void* DefaultAlloc(void*, size_t size, size_t alignment, VkSystemAllocType) {
212 return memalign(alignment, size);
213}
214
215void DefaultFree(void*, void* pMem) {
216 free(pMem);
217}
218
219const VkAllocCallbacks kDefaultAllocCallbacks = {
220 .pUserData = nullptr,
221 .pfnAlloc = DefaultAlloc,
222 .pfnFree = DefaultFree,
223};
224
225hwvulkan_device_t* g_hwdevice;
226bool EnsureInitialized() {
227 static std::once_flag once_flag;
228 static const hwvulkan_module_t* module;
229
230 std::call_once(once_flag, []() {
231 int result;
232 result = hw_get_module("vulkan",
233 reinterpret_cast<const hw_module_t**>(&module));
234 if (result != 0) {
235 ALOGE("failed to load vulkan hal: %s (%d)", strerror(-result),
236 result);
237 return;
238 }
239 result = module->common.methods->open(
240 &module->common, HWVULKAN_DEVICE_0,
241 reinterpret_cast<hw_device_t**>(&g_hwdevice));
242 if (result != 0) {
243 ALOGE("failed to open vulkan driver: %s (%d)", strerror(-result),
244 result);
245 module = nullptr;
246 return;
247 }
248 });
249
250 return module != nullptr && g_hwdevice != nullptr;
251}
252
253void DestroyDevice(Device* device) {
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500254 const VkAllocCallbacks* alloc = device->instance->alloc;
Jesse Hall04f4f472015-08-16 19:51:04 -0700255 device->~Device();
256 alloc->pfnFree(alloc->pUserData, device);
257}
258
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500259void FindLayersInDirectory(Instance& instance, const String& dir_name) {
Michael Lentine03c64b02015-08-26 18:27:26 -0500260 DIR* directory;
261 struct dirent* entry;
262 if ((directory = opendir(dir_name.c_str()))) {
263 Vector<VkLayerProperties> properties(
264 CallbackAllocator<VkLayerProperties>(instance.alloc));
265 while ((entry = readdir(directory))) {
266 size_t length = strlen(entry->d_name);
267 if (strncmp(entry->d_name, "libVKLayer", 10) != 0 ||
268 strncmp(entry->d_name + length - 3, ".so", 3) != 0)
269 continue;
270 // Open so
271 SharedLibraryHandle layer_handle = dlopen(
272 (dir_name + entry->d_name).c_str(), RTLD_NOW | RTLD_LOCAL);
273 if (!layer_handle) {
274 ALOGE("%s failed to load with error %s; Skipping",
275 entry->d_name, dlerror());
276 continue;
277 }
278
279 // Get Layers in so
280 PFN_vkGetGlobalLayerProperties get_layer_properties =
281 reinterpret_cast<PFN_vkGetGlobalLayerProperties>(
282 dlsym(layer_handle, "vkGetGlobalLayerProperties"));
283 if (!get_layer_properties) {
284 ALOGE(
285 "%s failed to find vkGetGlobalLayerProperties with "
286 "error %s; Skipping",
287 entry->d_name, dlerror());
288 dlclose(layer_handle);
289 continue;
290 }
291 uint32_t count;
292 get_layer_properties(&count, nullptr);
293
294 properties.resize(count);
295 get_layer_properties(&count, &properties[0]);
296
297 // Add Layers to potential list
Michael Lentine03c64b02015-08-26 18:27:26 -0500298 for (uint32_t i = 0; i < count; ++i) {
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500299 String layer_name(properties[i].layerName,
300 CallbackAllocator<char>(instance.alloc));
301 LayerData layer_data = {dir_name + entry->d_name, 0, 0};
302 instance.layers.insert(std::make_pair(layer_name, layer_data));
Michael Lentine03c64b02015-08-26 18:27:26 -0500303 ALOGV("Found layer %s", properties[i].layerName);
304 }
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500305 dlclose(layer_handle);
Michael Lentine03c64b02015-08-26 18:27:26 -0500306 }
307 closedir(directory);
308 } else {
309 ALOGE("Failed to Open Directory %s: %s (%d)", dir_name.c_str(),
310 strerror(errno), errno);
311 }
312}
313
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500314template <class TObject>
315void ActivateLayer(TObject* object, Instance* instance, const String& name) {
316 // If object has layer, do nothing
317 auto element = instance->layers.find(name);
318 if (std::find(object->active_layers.begin(), object->active_layers.end(),
319 element) != object->active_layers.end()) {
320 ALOGW("Layer %s already activated; skipping", name.c_str());
321 return;
322 }
323 // If layer is not open, open it
324 LayerData& layer_data = element->second;
325 pthread_mutex_lock(&instance->layer_lock);
326 if (layer_data.ref_count == 0) {
327 SharedLibraryHandle layer_handle =
328 dlopen(layer_data.path.c_str(), RTLD_NOW | RTLD_LOCAL);
329 if (!layer_handle) {
330 pthread_mutex_unlock(&instance->layer_lock);
331 ALOGE("%s failed to load with error %s; Skipping",
332 layer_data.path.c_str(), dlerror());
333 return;
334 }
335 layer_data.handle = layer_handle;
336 }
337 layer_data.ref_count++;
338 pthread_mutex_unlock(&instance->layer_lock);
339 ALOGV("Activating layer %s", name.c_str());
340 object->active_layers.push_back(element);
341}
342
343template <class TObject>
344void DeactivateLayer(TObject* object,
345 Instance* instance,
346 Vector<LayerMapIterator>::iterator& element) {
347 LayerMapIterator& layer_map_data = *element;
348 object->active_layers.erase(element);
349 LayerData& layer_data = layer_map_data->second;
350 pthread_mutex_lock(&instance->layer_lock);
351 layer_data.ref_count--;
352 if (!layer_data.ref_count) {
353 dlclose(layer_data.handle);
354 }
355 pthread_mutex_unlock(&instance->layer_lock);
356}
357
Michael Lentine9da191b2015-10-13 11:08:45 -0500358struct InstanceNamesPair {
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500359 Instance* instance;
Michael Lentine9da191b2015-10-13 11:08:45 -0500360 Vector<String>* layer_names;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500361};
362
Michael Lentine9da191b2015-10-13 11:08:45 -0500363void SetLayerNamesFromProperty(const char* name,
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500364 const char* value,
365 void* data) {
366 const char prefix[] = "debug.vulkan.layer.";
367 const size_t prefixlen = sizeof(prefix) - 1;
368 if (value[0] == '\0' || strncmp(name, prefix, prefixlen) != 0)
369 return;
Michael Lentine9da191b2015-10-13 11:08:45 -0500370 const char* number_str = name + prefixlen;
371 long layer_number = strtol(number_str, nullptr, 10);
372 if (layer_number <= 0 || layer_number == LONG_MAX) {
373 ALOGW("Cannot use a layer at number %ld from string %s", layer_number,
374 number_str);
375 return;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500376 }
Michael Lentine9da191b2015-10-13 11:08:45 -0500377 auto instance_names_pair = static_cast<InstanceNamesPair*>(data);
378 Vector<String>* layer_names = instance_names_pair->layer_names;
379 Instance* instance = instance_names_pair->instance;
380 size_t layer_size = static_cast<size_t>(layer_number);
381 if (layer_size > layer_names->size()) {
382 layer_names->resize(layer_size,
383 String(CallbackAllocator<char>(instance->alloc)));
384 }
385 (*layer_names)[layer_size - 1] = value;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500386}
387
388template <class TInfo, class TObject>
389void ActivateAllLayers(TInfo create_info, Instance* instance, TObject* object) {
390 ALOG_ASSERT(create_info->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO ||
391 create_info->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
392 "Cannot activate layers for unknown object %p", object);
393 CallbackAllocator<char> string_allocator(instance->alloc);
394 // Load system layers
395 {
396 char layer_prop[PROPERTY_VALUE_MAX];
397 property_get("debug.vulkan.layers", layer_prop, "");
398 String layer_name(string_allocator);
399 String layer_prop_str(layer_prop, string_allocator);
400 size_t end, start = 0;
401 while ((end = layer_prop_str.find(':', start)) != std::string::npos) {
402 layer_name = layer_prop_str.substr(start, end - start);
403 auto element = instance->layers.find(layer_name);
404 if (element != instance->layers.end()) {
405 ActivateLayer(object, instance, layer_name);
406 }
407 start = end + 1;
408 }
Michael Lentine9da191b2015-10-13 11:08:45 -0500409 Vector<String> layer_names(CallbackAllocator<String>(instance->alloc));
410 InstanceNamesPair instance_names_pair = {.instance = instance,
411 .layer_names = &layer_names};
412 property_list(SetLayerNamesFromProperty,
413 static_cast<void*>(&instance_names_pair));
414 for (auto layer_name_element : layer_names) {
415 ActivateLayer(object, instance, layer_name_element);
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500416 }
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500417 }
418 // Load app layers
419 for (uint32_t i = 0; i < create_info->layerCount; ++i) {
420 String layer_name(create_info->ppEnabledLayerNames[i],
421 string_allocator);
422 auto element = instance->layers.find(layer_name);
423 if (element == instance->layers.end()) {
424 ALOGW("Cannot activate layer %s as it was not found.",
425 layer_name.c_str());
426 } else {
427 ActivateLayer(object, instance, layer_name);
428 }
429 }
430}
431
432template <class TCreateInfo>
433bool AddExtensionToCreateInfo(TCreateInfo& local_create_info,
434 const char* extension_name,
435 const VkAllocCallbacks* alloc) {
436 for (uint32_t i = 0; i < local_create_info.extensionCount; ++i) {
437 if (!strcmp(extension_name,
438 local_create_info.ppEnabledExtensionNames[i])) {
439 return false;
440 }
441 }
442 uint32_t extension_count = local_create_info.extensionCount;
443 local_create_info.extensionCount++;
444 void* mem = alloc->pfnAlloc(
445 alloc->pUserData, local_create_info.extensionCount * sizeof(char*),
446 alignof(char*), VK_SYSTEM_ALLOC_TYPE_INTERNAL);
447 if (mem) {
448 const char** enabled_extensions = static_cast<const char**>(mem);
449 for (uint32_t i = 0; i < extension_count; ++i) {
450 enabled_extensions[i] =
451 local_create_info.ppEnabledExtensionNames[i];
452 }
453 enabled_extensions[extension_count] = extension_name;
454 local_create_info.ppEnabledExtensionNames = enabled_extensions;
455 } else {
456 ALOGW("%s extension cannot be enabled: memory allocation failed",
457 extension_name);
458 local_create_info.extensionCount--;
459 return false;
460 }
461 return true;
462}
463
464template <class T>
465void FreeAllocatedCreateInfo(T& local_create_info,
466 const VkAllocCallbacks* alloc) {
467 alloc->pfnFree(
468 alloc->pUserData,
469 const_cast<char**>(local_create_info.ppEnabledExtensionNames));
470}
471
472void LogDebugMessageCallback(VkFlags message_flags,
473 VkDbgObjectType /*obj_type*/,
474 uint64_t /*src_object*/,
475 size_t /*location*/,
476 int32_t message_code,
477 const char* layer_prefix,
478 const char* message,
479 void* /*user_data*/) {
480 if (message_flags & VK_DBG_REPORT_ERROR_BIT) {
481 ALOGE("[%s] Code %d : %s", layer_prefix, message_code, message);
482 } else if (message_flags & VK_DBG_REPORT_WARN_BIT) {
483 ALOGW("[%s] Code %d : %s", layer_prefix, message_code, message);
484 }
Michael Lentine03c64b02015-08-26 18:27:26 -0500485}
486
487VkResult CreateDeviceNoop(VkPhysicalDevice,
488 const VkDeviceCreateInfo*,
489 VkDevice*) {
490 return VK_SUCCESS;
491}
492
493PFN_vkVoidFunction GetLayerDeviceProcAddr(VkDevice device, const char* name) {
494 if (strcmp(name, "vkGetDeviceProcAddr") == 0) {
495 return reinterpret_cast<PFN_vkVoidFunction>(GetLayerDeviceProcAddr);
496 }
497 if (strcmp(name, "vkCreateDevice") == 0) {
498 return reinterpret_cast<PFN_vkVoidFunction>(CreateDeviceNoop);
499 }
500 if (!device)
501 return GetGlobalDeviceProcAddr(name);
502 Device* loader_device = reinterpret_cast<Device*>(GetVtbl(device)->device);
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500503 return loader_device->instance->drv.GetDeviceProcAddr(device, name);
Michael Lentinecd6cabf2015-09-14 17:32:59 -0500504}
505
Jesse Hall04f4f472015-08-16 19:51:04 -0700506// -----------------------------------------------------------------------------
507// "Bottom" functions. These are called at the end of the instance dispatch
508// chain.
509
510VkResult DestroyInstanceBottom(VkInstance instance) {
511 // These checks allow us to call DestroyInstanceBottom from any error path
512 // in CreateInstanceBottom, before the driver instance is fully initialized.
513 if (instance->drv.vtbl.instance != VK_NULL_HANDLE &&
514 instance->drv.vtbl.DestroyInstance) {
515 instance->drv.vtbl.DestroyInstance(instance->drv.vtbl.instance);
516 }
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500517 for (auto it = instance->active_layers.begin();
518 it != instance->active_layers.end(); ++it) {
519 DeactivateLayer(instance, instance, it);
Michael Lentine03c64b02015-08-26 18:27:26 -0500520 }
Michael Lentinecd6cabf2015-09-14 17:32:59 -0500521 if (instance->message) {
522 PFN_vkDbgDestroyMsgCallback DebugDestroyMessageCallback;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500523 DebugDestroyMessageCallback =
524 reinterpret_cast<PFN_vkDbgDestroyMsgCallback>(
525 vkGetInstanceProcAddr(instance, "vkDbgDestroyMsgCallback"));
Michael Lentinecd6cabf2015-09-14 17:32:59 -0500526 DebugDestroyMessageCallback(instance, instance->message);
527 }
Jesse Hall04f4f472015-08-16 19:51:04 -0700528 const VkAllocCallbacks* alloc = instance->alloc;
529 instance->~VkInstance_T();
530 alloc->pfnFree(alloc->pUserData, instance);
531 return VK_SUCCESS;
532}
533
534VkResult CreateInstanceBottom(const VkInstanceCreateInfo* create_info,
535 VkInstance* instance_ptr) {
536 Instance* instance = *instance_ptr;
537 VkResult result;
538
539 result =
540 g_hwdevice->CreateInstance(create_info, &instance->drv.vtbl.instance);
541 if (result != VK_SUCCESS) {
542 DestroyInstanceBottom(instance);
543 return result;
544 }
545
Michael Lentine03c64b02015-08-26 18:27:26 -0500546 if (!LoadInstanceVtbl(
547 instance->drv.vtbl.instance, instance->drv.vtbl.instance,
548 g_hwdevice->GetInstanceProcAddr, instance->drv.vtbl)) {
Jesse Hall04f4f472015-08-16 19:51:04 -0700549 DestroyInstanceBottom(instance);
550 return VK_ERROR_INITIALIZATION_FAILED;
551 }
552
553 // vkGetDeviceProcAddr has a bootstrapping problem. We require that it be
554 // queryable from the Instance, and that the resulting function work for any
555 // VkDevice created from the instance.
556 instance->drv.GetDeviceProcAddr = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
557 g_hwdevice->GetInstanceProcAddr(instance->drv.vtbl.instance,
558 "vkGetDeviceProcAddr"));
559 if (!instance->drv.GetDeviceProcAddr) {
560 ALOGE("missing instance proc: \"%s\"", "vkGetDeviceProcAddr");
561 DestroyInstanceBottom(instance);
562 return VK_ERROR_INITIALIZATION_FAILED;
563 }
564
565 hwvulkan_dispatch_t* dispatch =
566 reinterpret_cast<hwvulkan_dispatch_t*>(instance->drv.vtbl.instance);
567 if (dispatch->magic == HWVULKAN_DISPATCH_MAGIC) {
568 // Skip setting dispatch->vtbl on the driver instance handle, since we
569 // never intentionally call through it; we go through Instance::drv.vtbl
570 // instead.
571 } else {
572 ALOGE("invalid VkInstance dispatch magic: 0x%" PRIxPTR,
573 dispatch->magic);
574 DestroyInstanceBottom(instance);
575 return VK_ERROR_INITIALIZATION_FAILED;
576 }
577
578 uint32_t num_physical_devices = 0;
579 result = instance->drv.vtbl.EnumeratePhysicalDevices(
580 instance->drv.vtbl.instance, &num_physical_devices, nullptr);
581 if (result != VK_SUCCESS) {
582 DestroyInstanceBottom(instance);
583 return VK_ERROR_INITIALIZATION_FAILED;
584 }
585 num_physical_devices = std::min(num_physical_devices, kMaxPhysicalDevices);
586 result = instance->drv.vtbl.EnumeratePhysicalDevices(
587 instance->drv.vtbl.instance, &num_physical_devices,
588 instance->physical_devices);
589 if (result != VK_SUCCESS) {
590 DestroyInstanceBottom(instance);
591 return VK_ERROR_INITIALIZATION_FAILED;
592 }
593 for (uint32_t i = 0; i < num_physical_devices; i++) {
594 dispatch = reinterpret_cast<hwvulkan_dispatch_t*>(
595 instance->physical_devices[i]);
596 if (dispatch->magic != HWVULKAN_DISPATCH_MAGIC) {
597 ALOGE("invalid VkPhysicalDevice dispatch magic: 0x%" PRIxPTR,
598 dispatch->magic);
599 DestroyInstanceBottom(instance);
600 return VK_ERROR_INITIALIZATION_FAILED;
601 }
602 dispatch->vtbl = instance->vtbl;
603 }
604 instance->drv.num_physical_devices = num_physical_devices;
605
606 instance->num_physical_devices = instance->drv.num_physical_devices;
607 return VK_SUCCESS;
608}
609
610VkResult EnumeratePhysicalDevicesBottom(VkInstance instance,
611 uint32_t* pdev_count,
612 VkPhysicalDevice* pdevs) {
613 uint32_t count = instance->num_physical_devices;
614 if (pdevs) {
615 count = std::min(count, *pdev_count);
616 std::copy(instance->physical_devices,
617 instance->physical_devices + count, pdevs);
618 }
619 *pdev_count = count;
620 return VK_SUCCESS;
621}
622
623VkResult GetPhysicalDeviceFeaturesBottom(VkPhysicalDevice pdev,
624 VkPhysicalDeviceFeatures* features) {
625 return GetVtbl(pdev)
626 ->instance->drv.vtbl.GetPhysicalDeviceFeatures(pdev, features);
627}
628
629VkResult GetPhysicalDeviceFormatPropertiesBottom(
630 VkPhysicalDevice pdev,
631 VkFormat format,
632 VkFormatProperties* properties) {
633 return GetVtbl(pdev)->instance->drv.vtbl.GetPhysicalDeviceFormatProperties(
634 pdev, format, properties);
635}
636
637VkResult GetPhysicalDeviceImageFormatPropertiesBottom(
638 VkPhysicalDevice pdev,
639 VkFormat format,
640 VkImageType type,
641 VkImageTiling tiling,
642 VkImageUsageFlags usage,
643 VkImageFormatProperties* properties) {
644 return GetVtbl(pdev)
645 ->instance->drv.vtbl.GetPhysicalDeviceImageFormatProperties(
646 pdev, format, type, tiling, usage, properties);
647}
648
649VkResult GetPhysicalDeviceLimitsBottom(VkPhysicalDevice pdev,
650 VkPhysicalDeviceLimits* limits) {
651 return GetVtbl(pdev)
652 ->instance->drv.vtbl.GetPhysicalDeviceLimits(pdev, limits);
653}
654
655VkResult GetPhysicalDevicePropertiesBottom(
656 VkPhysicalDevice pdev,
657 VkPhysicalDeviceProperties* properties) {
658 return GetVtbl(pdev)
659 ->instance->drv.vtbl.GetPhysicalDeviceProperties(pdev, properties);
660}
661
662VkResult GetPhysicalDeviceQueueCountBottom(VkPhysicalDevice pdev,
663 uint32_t* count) {
664 return GetVtbl(pdev)
665 ->instance->drv.vtbl.GetPhysicalDeviceQueueCount(pdev, count);
666}
667
668VkResult GetPhysicalDeviceQueuePropertiesBottom(
669 VkPhysicalDevice pdev,
670 uint32_t count,
671 VkPhysicalDeviceQueueProperties* properties) {
672 return GetVtbl(pdev)->instance->drv.vtbl.GetPhysicalDeviceQueueProperties(
673 pdev, count, properties);
674}
675
676VkResult GetPhysicalDeviceMemoryPropertiesBottom(
677 VkPhysicalDevice pdev,
678 VkPhysicalDeviceMemoryProperties* properties) {
679 return GetVtbl(pdev)->instance->drv.vtbl.GetPhysicalDeviceMemoryProperties(
680 pdev, properties);
681}
682
683VkResult CreateDeviceBottom(VkPhysicalDevice pdev,
684 const VkDeviceCreateInfo* create_info,
685 VkDevice* out_device) {
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500686 Instance& instance = *static_cast<Instance*>(GetVtbl(pdev)->instance);
Jesse Hall04f4f472015-08-16 19:51:04 -0700687 VkResult result;
688
689 void* mem = instance.alloc->pfnAlloc(instance.alloc->pUserData,
690 sizeof(Device), alignof(Device),
691 VK_SYSTEM_ALLOC_TYPE_API_OBJECT);
692 if (!mem)
693 return VK_ERROR_OUT_OF_HOST_MEMORY;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500694 Device* device = new (mem) Device(&instance);
Jesse Hall04f4f472015-08-16 19:51:04 -0700695
696 VkDevice drv_device;
697 result = instance.drv.vtbl.CreateDevice(pdev, create_info, &drv_device);
698 if (result != VK_SUCCESS) {
699 DestroyDevice(device);
700 return result;
701 }
702
Jesse Hall04f4f472015-08-16 19:51:04 -0700703 hwvulkan_dispatch_t* dispatch =
704 reinterpret_cast<hwvulkan_dispatch_t*>(drv_device);
705 if (dispatch->magic != HWVULKAN_DISPATCH_MAGIC) {
706 ALOGE("invalid VkDevice dispatch magic: 0x%" PRIxPTR, dispatch->magic);
Michael Lentine03c64b02015-08-26 18:27:26 -0500707 PFN_vkDestroyDevice destroy_device =
708 reinterpret_cast<PFN_vkDestroyDevice>(
709 instance.drv.GetDeviceProcAddr(drv_device, "vkDestroyDevice"));
710 destroy_device(drv_device);
Jesse Hall04f4f472015-08-16 19:51:04 -0700711 DestroyDevice(device);
712 return VK_ERROR_INITIALIZATION_FAILED;
713 }
714 dispatch->vtbl = &device->vtbl_storage;
715
Jesse Hallb1352bc2015-09-04 16:12:33 -0700716 device->vtbl_storage.GetSurfacePropertiesKHR = GetSurfacePropertiesKHR;
717 device->vtbl_storage.GetSurfaceFormatsKHR = GetSurfaceFormatsKHR;
718 device->vtbl_storage.GetSurfacePresentModesKHR = GetSurfacePresentModesKHR;
719 device->vtbl_storage.CreateSwapchainKHR = CreateSwapchainKHR;
720 device->vtbl_storage.DestroySwapchainKHR = DestroySwapchainKHR;
721 device->vtbl_storage.GetSwapchainImagesKHR = GetSwapchainImagesKHR;
722 device->vtbl_storage.AcquireNextImageKHR = AcquireNextImageKHR;
723 device->vtbl_storage.QueuePresentKHR = QueuePresentKHR;
724
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500725 ActivateAllLayers(create_info, &instance, device);
726
Michael Lentine03c64b02015-08-26 18:27:26 -0500727 void* base_object = static_cast<void*>(drv_device);
728 void* next_object = base_object;
729 VkLayerLinkedListElem* next_element;
730 PFN_vkGetDeviceProcAddr next_get_proc_addr = GetLayerDeviceProcAddr;
731 Vector<VkLayerLinkedListElem> elem_list(
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500732 device->active_layers.size(),
Michael Lentine03c64b02015-08-26 18:27:26 -0500733 CallbackAllocator<VkLayerLinkedListElem>(instance.alloc));
734
735 for (size_t i = elem_list.size(); i > 0; i--) {
736 size_t idx = i - 1;
737 next_element = &elem_list[idx];
738 next_element->get_proc_addr =
739 reinterpret_cast<PFN_vkGetProcAddr>(next_get_proc_addr);
740 next_element->base_object = base_object;
741 next_element->next_element = next_object;
742 next_object = static_cast<void*>(next_element);
743
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500744 auto& name = device->active_layers[idx]->first;
745 auto& handle = device->active_layers[idx]->second.handle;
Michael Lentine03c64b02015-08-26 18:27:26 -0500746 next_get_proc_addr = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500747 dlsym(handle, (name + "GetDeviceProcAddr").c_str()));
Michael Lentine03c64b02015-08-26 18:27:26 -0500748 if (!next_get_proc_addr) {
Michael Lentine03c64b02015-08-26 18:27:26 -0500749 next_get_proc_addr = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500750 dlsym(handle, "vkGetDeviceProcAddr"));
Michael Lentine1f0f5392015-09-11 14:54:34 -0700751 if (!next_get_proc_addr) {
752 ALOGE("Cannot find vkGetDeviceProcAddr for %s, error is %s",
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500753 name.c_str(), dlerror());
Michael Lentine1f0f5392015-09-11 14:54:34 -0700754 next_object = next_element->next_element;
755 next_get_proc_addr = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
756 next_element->get_proc_addr);
757 }
Michael Lentine03c64b02015-08-26 18:27:26 -0500758 }
759 }
760
761 if (!LoadDeviceVtbl(static_cast<VkDevice>(base_object),
762 static_cast<VkDevice>(next_object), next_get_proc_addr,
763 device->vtbl_storage)) {
764 DestroyDevice(device);
765 return VK_ERROR_INITIALIZATION_FAILED;
766 }
767
768 PFN_vkCreateDevice layer_createDevice =
769 reinterpret_cast<PFN_vkCreateDevice>(
770 device->vtbl_storage.GetDeviceProcAddr(drv_device,
771 "vkCreateDevice"));
772 layer_createDevice(pdev, create_info, &drv_device);
Jesse Hall04f4f472015-08-16 19:51:04 -0700773
774 *out_device = drv_device;
775 return VK_SUCCESS;
776}
777
778VkResult GetPhysicalDeviceExtensionPropertiesBottom(
779 VkPhysicalDevice pdev,
780 const char* layer_name,
781 uint32_t* properties_count,
782 VkExtensionProperties* properties) {
783 // TODO: what are we supposed to do with layer_name here?
784 return GetVtbl(pdev)
785 ->instance->drv.vtbl.GetPhysicalDeviceExtensionProperties(
786 pdev, layer_name, properties_count, properties);
787}
788
789VkResult GetPhysicalDeviceLayerPropertiesBottom(VkPhysicalDevice pdev,
790 uint32_t* properties_count,
791 VkLayerProperties* properties) {
792 return GetVtbl(pdev)->instance->drv.vtbl.GetPhysicalDeviceLayerProperties(
793 pdev, properties_count, properties);
794}
795
796VkResult GetPhysicalDeviceSparseImageFormatPropertiesBottom(
797 VkPhysicalDevice pdev,
798 VkFormat format,
799 VkImageType type,
800 uint32_t samples,
801 VkImageUsageFlags usage,
802 VkImageTiling tiling,
803 uint32_t* properties_count,
804 VkSparseImageFormatProperties* properties) {
805 return GetVtbl(pdev)
806 ->instance->drv.vtbl.GetPhysicalDeviceSparseImageFormatProperties(
807 pdev, format, type, samples, usage, tiling, properties_count,
808 properties);
809}
810
811PFN_vkVoidFunction GetInstanceProcAddrBottom(VkInstance, const char*);
812
813const InstanceVtbl kBottomInstanceFunctions = {
814 // clang-format off
815 .instance = nullptr,
816 .CreateInstance = CreateInstanceBottom,
817 .DestroyInstance = DestroyInstanceBottom,
818 .GetInstanceProcAddr = GetInstanceProcAddrBottom,
819 .EnumeratePhysicalDevices = EnumeratePhysicalDevicesBottom,
820 .GetPhysicalDeviceFeatures = GetPhysicalDeviceFeaturesBottom,
821 .GetPhysicalDeviceFormatProperties = GetPhysicalDeviceFormatPropertiesBottom,
822 .GetPhysicalDeviceImageFormatProperties = GetPhysicalDeviceImageFormatPropertiesBottom,
823 .GetPhysicalDeviceLimits = GetPhysicalDeviceLimitsBottom,
824 .GetPhysicalDeviceProperties = GetPhysicalDevicePropertiesBottom,
825 .GetPhysicalDeviceQueueCount = GetPhysicalDeviceQueueCountBottom,
826 .GetPhysicalDeviceQueueProperties = GetPhysicalDeviceQueuePropertiesBottom,
827 .GetPhysicalDeviceMemoryProperties = GetPhysicalDeviceMemoryPropertiesBottom,
828 .CreateDevice = CreateDeviceBottom,
829 .GetPhysicalDeviceExtensionProperties = GetPhysicalDeviceExtensionPropertiesBottom,
830 .GetPhysicalDeviceLayerProperties = GetPhysicalDeviceLayerPropertiesBottom,
831 .GetPhysicalDeviceSparseImageFormatProperties = GetPhysicalDeviceSparseImageFormatPropertiesBottom,
Jesse Hallb1352bc2015-09-04 16:12:33 -0700832 .GetPhysicalDeviceSurfaceSupportKHR = GetPhysicalDeviceSurfaceSupportKHR,
Jesse Hall04f4f472015-08-16 19:51:04 -0700833 // clang-format on
834};
835
Michael Lentine03c64b02015-08-26 18:27:26 -0500836VkResult Noop(...) {
837 return VK_SUCCESS;
838}
839
Jesse Hall04f4f472015-08-16 19:51:04 -0700840PFN_vkVoidFunction GetInstanceProcAddrBottom(VkInstance, const char* name) {
Michael Lentine03c64b02015-08-26 18:27:26 -0500841 // TODO: Possibly move this into the instance table
842 // TODO: Possibly register the callbacks in the loader
843 if (strcmp(name, "vkDbgCreateMsgCallback") == 0 ||
844 strcmp(name, "vkDbgDestroyMsgCallback") == 0) {
845 return reinterpret_cast<PFN_vkVoidFunction>(Noop);
846 }
847 if (strcmp(name, "vkCreateInstance") == 0) {
848 return reinterpret_cast<PFN_vkVoidFunction>(CreateInstanceBottom);
849 }
Jesse Hall04f4f472015-08-16 19:51:04 -0700850 return GetSpecificInstanceProcAddr(&kBottomInstanceFunctions, name);
851}
852
853} // namespace
854
855// -----------------------------------------------------------------------------
856// Global functions. These are called directly from the loader entry points,
857// without going through a dispatch table.
858
859namespace vulkan {
860
861VkResult GetGlobalExtensionProperties(const char* /*layer_name*/,
862 uint32_t* count,
863 VkExtensionProperties* /*properties*/) {
864 if (!count)
865 return VK_ERROR_INVALID_POINTER;
866 if (!EnsureInitialized())
867 return VK_ERROR_UNAVAILABLE;
868
869 // TODO: not yet implemented
870 ALOGW("vkGetGlobalExtensionProperties not implemented");
871
872 *count = 0;
873 return VK_SUCCESS;
874}
875
876VkResult GetGlobalLayerProperties(uint32_t* count,
877 VkLayerProperties* /*properties*/) {
878 if (!count)
879 return VK_ERROR_INVALID_POINTER;
880 if (!EnsureInitialized())
881 return VK_ERROR_UNAVAILABLE;
882
883 // TODO: not yet implemented
884 ALOGW("vkGetGlobalLayerProperties not implemented");
885
886 *count = 0;
887 return VK_SUCCESS;
888}
889
890VkResult CreateInstance(const VkInstanceCreateInfo* create_info,
891 VkInstance* out_instance) {
892 VkResult result;
893
894 if (!EnsureInitialized())
895 return VK_ERROR_UNAVAILABLE;
896
897 VkInstanceCreateInfo local_create_info = *create_info;
898 if (!local_create_info.pAllocCb)
899 local_create_info.pAllocCb = &kDefaultAllocCallbacks;
900 create_info = &local_create_info;
901
902 void* instance_mem = create_info->pAllocCb->pfnAlloc(
903 create_info->pAllocCb->pUserData, sizeof(Instance), alignof(Instance),
904 VK_SYSTEM_ALLOC_TYPE_API_OBJECT);
905 if (!instance_mem)
906 return VK_ERROR_OUT_OF_HOST_MEMORY;
907 Instance* instance = new (instance_mem) Instance(create_info->pAllocCb);
908
909 instance->vtbl_storage = kBottomInstanceFunctions;
910 instance->vtbl_storage.instance = instance;
Michael Lentinecd6cabf2015-09-14 17:32:59 -0500911 instance->message = VK_NULL_HANDLE;
Jesse Hall04f4f472015-08-16 19:51:04 -0700912
Michael Lentine03c64b02015-08-26 18:27:26 -0500913 // Scan layers
Michael Lentine03c64b02015-08-26 18:27:26 -0500914 CallbackAllocator<char> string_allocator(instance->alloc);
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500915
Michael Lentine03c64b02015-08-26 18:27:26 -0500916 String dir_name("/data/local/tmp/vulkan/", string_allocator);
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500917 FindLayersInDirectory(*instance, dir_name);
Michael Lentine1c69b9e2015-09-14 13:26:59 -0500918 const std::string& path = LoaderData::GetInstance().layer_path;
919 dir_name.assign(path.c_str(), path.size());
920 dir_name.append("/");
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500921 FindLayersInDirectory(*instance, dir_name);
Jesse Hall04f4f472015-08-16 19:51:04 -0700922
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500923 ActivateAllLayers(create_info, instance, instance);
Michael Lentine03c64b02015-08-26 18:27:26 -0500924
925 void* base_object = static_cast<void*>(instance);
926 void* next_object = base_object;
927 VkLayerLinkedListElem* next_element;
928 PFN_vkGetInstanceProcAddr next_get_proc_addr =
929 kBottomInstanceFunctions.GetInstanceProcAddr;
930 Vector<VkLayerLinkedListElem> elem_list(
Michael Lentine1f0f5392015-09-11 14:54:34 -0700931 instance->active_layers.size(),
Michael Lentine03c64b02015-08-26 18:27:26 -0500932 CallbackAllocator<VkLayerLinkedListElem>(instance->alloc));
933
934 for (size_t i = elem_list.size(); i > 0; i--) {
935 size_t idx = i - 1;
936 next_element = &elem_list[idx];
937 next_element->get_proc_addr =
938 reinterpret_cast<PFN_vkGetProcAddr>(next_get_proc_addr);
939 next_element->base_object = base_object;
940 next_element->next_element = next_object;
941 next_object = static_cast<void*>(next_element);
942
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500943 auto& name = instance->active_layers[idx]->first;
944 auto& handle = instance->active_layers[idx]->second.handle;
Michael Lentine03c64b02015-08-26 18:27:26 -0500945 next_get_proc_addr = reinterpret_cast<PFN_vkGetInstanceProcAddr>(
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500946 dlsym(handle, (name + "GetInstanceProcAddr").c_str()));
Michael Lentine03c64b02015-08-26 18:27:26 -0500947 if (!next_get_proc_addr) {
Michael Lentine03c64b02015-08-26 18:27:26 -0500948 next_get_proc_addr = reinterpret_cast<PFN_vkGetInstanceProcAddr>(
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500949 dlsym(handle, "vkGetInstanceProcAddr"));
Michael Lentine1f0f5392015-09-11 14:54:34 -0700950 if (!next_get_proc_addr) {
951 ALOGE("Cannot find vkGetInstanceProcAddr for %s, error is %s",
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500952 name.c_str(), dlerror());
Michael Lentine1f0f5392015-09-11 14:54:34 -0700953 next_object = next_element->next_element;
954 next_get_proc_addr =
955 reinterpret_cast<PFN_vkGetInstanceProcAddr>(
956 next_element->get_proc_addr);
957 }
Michael Lentine03c64b02015-08-26 18:27:26 -0500958 }
959 }
960
961 if (!LoadInstanceVtbl(static_cast<VkInstance>(base_object),
962 static_cast<VkInstance>(next_object),
963 next_get_proc_addr, instance->vtbl_storage)) {
964 DestroyInstanceBottom(instance);
965 return VK_ERROR_INITIALIZATION_FAILED;
966 }
967
Michael Lentine950bb4f2015-09-14 13:26:30 -0500968 // Force enable callback extension if required
969 bool enable_callback =
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500970 property_get_bool("debug.vulkan.enable_callback", false);
Michael Lentinecd6cabf2015-09-14 17:32:59 -0500971 bool enable_logging = enable_callback;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500972 const char* extension_name = "DEBUG_REPORT";
Michael Lentine950bb4f2015-09-14 13:26:30 -0500973 if (enable_callback) {
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500974 enable_callback = AddExtensionToCreateInfo(
975 local_create_info, extension_name, instance->alloc);
Michael Lentine950bb4f2015-09-14 13:26:30 -0500976 }
977
Jesse Hall04f4f472015-08-16 19:51:04 -0700978 *out_instance = instance;
Michael Lentine03c64b02015-08-26 18:27:26 -0500979 result = instance->vtbl_storage.CreateInstance(create_info, out_instance);
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500980 if (enable_callback)
981 FreeAllocatedCreateInfo(local_create_info, instance->alloc);
Jesse Hall04f4f472015-08-16 19:51:04 -0700982 if (result <= 0) {
983 // For every layer, including the loader top and bottom layers:
984 // - If a call to the next CreateInstance fails, the layer must clean
985 // up anything it has successfully done so far, and propagate the
986 // error upwards.
987 // - If a layer successfully calls the next layer's CreateInstance, and
988 // afterwards must fail for some reason, it must call the next layer's
989 // DestroyInstance before returning.
990 // - The layer must not call the next layer's DestroyInstance if that
991 // layer's CreateInstance wasn't called, or returned failure.
992
993 // On failure, CreateInstanceBottom frees the instance struct, so it's
994 // already gone at this point. Nothing to do.
995 }
996
Michael Lentinecd6cabf2015-09-14 17:32:59 -0500997 if (enable_logging) {
998 PFN_vkDbgCreateMsgCallback DebugCreateMessageCallback;
Michael Lentine9dbe67f2015-09-16 15:53:50 -0500999 DebugCreateMessageCallback =
1000 reinterpret_cast<PFN_vkDbgCreateMsgCallback>(
1001 vkGetInstanceProcAddr(instance, "vkDbgCreateMsgCallback"));
1002 DebugCreateMessageCallback(
1003 instance, VK_DBG_REPORT_ERROR_BIT | VK_DBG_REPORT_WARN_BIT,
1004 LogDebugMessageCallback, NULL, &instance->message);
Michael Lentinecd6cabf2015-09-14 17:32:59 -05001005 }
1006
Jesse Hall04f4f472015-08-16 19:51:04 -07001007 return result;
1008}
1009
1010PFN_vkVoidFunction GetInstanceProcAddr(VkInstance instance, const char* name) {
1011 if (!instance)
1012 return GetGlobalInstanceProcAddr(name);
Michael Lentine03c64b02015-08-26 18:27:26 -05001013 // TODO: Possibly move this into the instance table
1014 if (strcmp(name, "vkDbgCreateMsgCallback") == 0 ||
1015 strcmp(name, "vkDbgDestroyMsgCallback") == 0) {
1016 if (!instance->vtbl)
1017 return NULL;
1018 PFN_vkGetInstanceProcAddr gpa = instance->vtbl->GetInstanceProcAddr;
1019 return reinterpret_cast<PFN_vkVoidFunction>(gpa(instance, name));
1020 }
Jesse Hall04f4f472015-08-16 19:51:04 -07001021 // For special-case functions we always return the loader entry
1022 if (strcmp(name, "vkGetInstanceProcAddr") == 0 ||
1023 strcmp(name, "vkGetDeviceProcAddr") == 0) {
1024 return GetGlobalInstanceProcAddr(name);
1025 }
1026 return GetSpecificInstanceProcAddr(instance->vtbl, name);
1027}
1028
1029PFN_vkVoidFunction GetDeviceProcAddr(VkDevice device, const char* name) {
1030 if (!device)
1031 return GetGlobalDeviceProcAddr(name);
Michael Lentine03c64b02015-08-26 18:27:26 -05001032 if (strcmp(name, "vkGetDeviceProcAddr") == 0) {
1033 return reinterpret_cast<PFN_vkVoidFunction>(GetDeviceProcAddr);
1034 }
Michael Lentine9dbe67f2015-09-16 15:53:50 -05001035 if (strcmp(name, "vkGetDeviceQueue") == 0) {
1036 return reinterpret_cast<PFN_vkVoidFunction>(GetDeviceQueue);
1037 }
1038 if (strcmp(name, "vkCreateCommandBuffer") == 0) {
1039 return reinterpret_cast<PFN_vkVoidFunction>(CreateCommandBuffer);
1040 }
1041 if (strcmp(name, "vkDestroyDevice") == 0) {
1042 return reinterpret_cast<PFN_vkVoidFunction>(DestroyDevice);
1043 }
Jesse Hall04f4f472015-08-16 19:51:04 -07001044 // For special-case functions we always return the loader entry
1045 if (strcmp(name, "vkGetDeviceQueue") == 0 ||
Jesse Hallc7a6eb52015-08-31 12:52:03 -07001046 strcmp(name, "vkCreateCommandBuffer") == 0 ||
Jesse Hall04f4f472015-08-16 19:51:04 -07001047 strcmp(name, "vkDestroyDevice") == 0) {
1048 return GetGlobalDeviceProcAddr(name);
1049 }
1050 return GetSpecificDeviceProcAddr(GetVtbl(device), name);
1051}
1052
1053VkResult GetDeviceQueue(VkDevice drv_device,
1054 uint32_t family,
1055 uint32_t index,
1056 VkQueue* out_queue) {
1057 VkResult result;
1058 VkQueue queue;
1059 const DeviceVtbl* vtbl = GetVtbl(drv_device);
1060 result = vtbl->GetDeviceQueue(drv_device, family, index, &queue);
1061 if (result != VK_SUCCESS)
1062 return result;
1063 hwvulkan_dispatch_t* dispatch =
1064 reinterpret_cast<hwvulkan_dispatch_t*>(queue);
1065 if (dispatch->magic != HWVULKAN_DISPATCH_MAGIC && dispatch->vtbl != &vtbl) {
1066 ALOGE("invalid VkQueue dispatch magic: 0x%" PRIxPTR, dispatch->magic);
1067 return VK_ERROR_INITIALIZATION_FAILED;
1068 }
1069 dispatch->vtbl = vtbl;
1070 *out_queue = queue;
1071 return VK_SUCCESS;
1072}
1073
Jesse Hallc7a6eb52015-08-31 12:52:03 -07001074VkResult CreateCommandBuffer(VkDevice drv_device,
1075 const VkCmdBufferCreateInfo* create_info,
1076 VkCmdBuffer* out_cmdbuf) {
1077 const DeviceVtbl* vtbl = GetVtbl(drv_device);
1078 VkCmdBuffer cmdbuf;
1079 VkResult result =
1080 vtbl->CreateCommandBuffer(drv_device, create_info, &cmdbuf);
1081 if (result != VK_SUCCESS)
1082 return result;
1083 hwvulkan_dispatch_t* dispatch =
1084 reinterpret_cast<hwvulkan_dispatch_t*>(cmdbuf);
1085 if (dispatch->magic != HWVULKAN_DISPATCH_MAGIC) {
1086 ALOGE("invalid VkCmdBuffer dispatch magic: 0x%" PRIxPTR,
1087 dispatch->magic);
1088 return VK_ERROR_INITIALIZATION_FAILED;
1089 }
1090 dispatch->vtbl = vtbl;
1091 *out_cmdbuf = cmdbuf;
1092 return VK_SUCCESS;
1093}
1094
Jesse Hall04f4f472015-08-16 19:51:04 -07001095VkResult DestroyDevice(VkDevice drv_device) {
1096 const DeviceVtbl* vtbl = GetVtbl(drv_device);
1097 Device* device = static_cast<Device*>(vtbl->device);
Michael Lentine9dbe67f2015-09-16 15:53:50 -05001098 for (auto it = device->active_layers.begin();
1099 it != device->active_layers.end(); ++it) {
1100 DeactivateLayer(device, device->instance, it);
1101 }
1102 device->active_layers.clear();
Jesse Hall04f4f472015-08-16 19:51:04 -07001103 vtbl->DestroyDevice(drv_device);
1104 DestroyDevice(device);
1105 return VK_SUCCESS;
1106}
1107
Jesse Halld7b994a2015-09-07 14:17:37 -07001108void* AllocDeviceMem(VkDevice device,
1109 size_t size,
1110 size_t align,
1111 VkSystemAllocType type) {
1112 const VkAllocCallbacks* alloc_cb =
Michael Lentine9dbe67f2015-09-16 15:53:50 -05001113 static_cast<Device*>(GetVtbl(device)->device)->instance->alloc;
Jesse Halld7b994a2015-09-07 14:17:37 -07001114 return alloc_cb->pfnAlloc(alloc_cb->pUserData, size, align, type);
1115}
1116
1117void FreeDeviceMem(VkDevice device, void* ptr) {
1118 const VkAllocCallbacks* alloc_cb =
Michael Lentine9dbe67f2015-09-16 15:53:50 -05001119 static_cast<Device*>(GetVtbl(device)->device)->instance->alloc;
Jesse Halld7b994a2015-09-07 14:17:37 -07001120 alloc_cb->pfnFree(alloc_cb->pUserData, ptr);
1121}
1122
1123const DeviceVtbl& GetDriverVtbl(VkDevice device) {
1124 // TODO(jessehall): This actually returns the API-level vtbl for the
1125 // device, not the driver entry points. Given the current use -- getting
1126 // the driver's private swapchain-related functions -- that works, but is
1127 // misleading and likely to cause bugs. Fix as part of separating the
1128 // loader->driver interface from the app->loader interface.
1129 return static_cast<Device*>(GetVtbl(device)->device)->vtbl_storage;
1130}
1131
1132const DeviceVtbl& GetDriverVtbl(VkQueue queue) {
1133 // TODO(jessehall): This actually returns the API-level vtbl for the
1134 // device, not the driver entry points. Given the current use -- getting
1135 // the driver's private swapchain-related functions -- that works, but is
1136 // misleading and likely to cause bugs. Fix as part of separating the
1137 // loader->driver interface from the app->loader interface.
1138 return static_cast<Device*>(GetVtbl(queue)->device)->vtbl_storage;
1139}
1140
Jesse Hall04f4f472015-08-16 19:51:04 -07001141} // namespace vulkan