1 /*
2 * Copyright © 2017 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23 #ifndef VK_UTIL_H
24 #define VK_UTIL_H
25
26 /* common inlines and macros for vulkan drivers */
27
28 #include <inttypes.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <vulkan/vulkan.h>
32
33 #include <chrono>
34 #include <functional>
35 #include <memory>
36 #include <optional>
37 #include <string>
38 #include <thread>
39 #include <tuple>
40 #include <type_traits>
41 #include <vector>
42
43 #include "VkDecoderContext.h"
44 #include "VulkanDispatch.h"
45 #include "aemu/base/synchronization/Lock.h"
46 #include "host-common/GfxstreamFatalError.h"
47 #include "host-common/logging.h"
48 #include "vk_fn_info.h"
49 #include "vulkan/cereal/common/vk_struct_id.h"
50
51 namespace gfxstream {
52 namespace vk {
53
54 struct vk_struct_common {
55 VkStructureType sType;
56 struct vk_struct_common* pNext;
57 };
58
59 struct vk_struct_chain_iterator {
60 vk_struct_common* value;
61 };
62
63 #define vk_foreach_struct(__iter, __start) \
64 for (struct vk_struct_common* __iter = (struct vk_struct_common*)(__start); __iter; \
65 __iter = __iter->pNext)
66
67 #define vk_foreach_struct_const(__iter, __start) \
68 for (const struct vk_struct_common* __iter = (const struct vk_struct_common*)(__start); \
69 __iter; __iter = __iter->pNext)
70
71 /**
72 * A wrapper for a Vulkan output array. A Vulkan output array is one that
73 * follows the convention of the parameters to
74 * vkGetPhysicalDeviceQueueFamilyProperties().
75 *
76 * Example Usage:
77 *
78 * VkResult
79 * vkGetPhysicalDeviceQueueFamilyProperties(
80 * VkPhysicalDevice physicalDevice,
81 * uint32_t* pQueueFamilyPropertyCount,
82 * VkQueueFamilyProperties* pQueueFamilyProperties)
83 * {
84 * VK_OUTARRAY_MAKE(props, pQueueFamilyProperties,
85 * pQueueFamilyPropertyCount);
86 *
87 * vk_outarray_append(&props, p) {
88 * p->queueFlags = ...;
89 * p->queueCount = ...;
90 * }
91 *
92 * vk_outarray_append(&props, p) {
93 * p->queueFlags = ...;
94 * p->queueCount = ...;
95 * }
96 *
97 * return vk_outarray_status(&props);
98 * }
99 */
100 struct __vk_outarray {
101 /** May be null. */
102 void* data;
103
104 /**
105 * Capacity, in number of elements. Capacity is unlimited (UINT32_MAX) if
106 * data is null.
107 */
108 uint32_t cap;
109
110 /**
111 * Count of elements successfully written to the array. Every write is
112 * considered successful if data is null.
113 */
114 uint32_t* filled_len;
115
116 /**
117 * Count of elements that would have been written to the array if its
118 * capacity were sufficient. Vulkan functions often return VK_INCOMPLETE
119 * when `*filled_len < wanted_len`.
120 */
121 uint32_t wanted_len;
122 };
123
__vk_outarray_init(struct __vk_outarray * a,void * data,uint32_t * len)124 static inline void __vk_outarray_init(struct __vk_outarray* a, void* data, uint32_t* len) {
125 a->data = data;
126 a->cap = *len;
127 a->filled_len = len;
128 *a->filled_len = 0;
129 a->wanted_len = 0;
130
131 if (a->data == NULL) a->cap = UINT32_MAX;
132 }
133
__vk_outarray_status(const struct __vk_outarray * a)134 static inline VkResult __vk_outarray_status(const struct __vk_outarray* a) {
135 if (*a->filled_len < a->wanted_len)
136 return VK_INCOMPLETE;
137 else
138 return VK_SUCCESS;
139 }
140
__vk_outarray_next(struct __vk_outarray * a,size_t elem_size)141 static inline void* __vk_outarray_next(struct __vk_outarray* a, size_t elem_size) {
142 void* p = NULL;
143
144 a->wanted_len += 1;
145
146 if (*a->filled_len >= a->cap) return NULL;
147
148 if (a->data != NULL) p = ((uint8_t*)a->data) + (*a->filled_len) * elem_size;
149
150 *a->filled_len += 1;
151
152 return p;
153 }
154
155 #define vk_outarray(elem_t) \
156 struct { \
157 struct __vk_outarray base; \
158 elem_t meta[]; \
159 }
160
161 #define vk_outarray_typeof_elem(a) __typeof__((a)->meta[0])
162 #define vk_outarray_sizeof_elem(a) sizeof((a)->meta[0])
163
164 #define vk_outarray_init(a, data, len) __vk_outarray_init(&(a)->base, (data), (len))
165
166 #define VK_OUTARRAY_MAKE(name, data, len) \
167 vk_outarray(__typeof__((data)[0])) name; \
168 vk_outarray_init(&name, (data), (len))
169
170 #define vk_outarray_status(a) __vk_outarray_status(&(a)->base)
171
172 #define vk_outarray_next(a) \
173 ((vk_outarray_typeof_elem(a)*)__vk_outarray_next(&(a)->base, vk_outarray_sizeof_elem(a)))
174
175 /**
176 * Append to a Vulkan output array.
177 *
178 * This is a block-based macro. For example:
179 *
180 * vk_outarray_append(&a, elem) {
181 * elem->foo = ...;
182 * elem->bar = ...;
183 * }
184 *
185 * The array `a` has type `vk_outarray(elem_t) *`. It is usually declared with
186 * VK_OUTARRAY_MAKE(). The variable `elem` is block-scoped and has type
187 * `elem_t *`.
188 *
189 * The macro unconditionally increments the array's `wanted_len`. If the array
190 * is not full, then the macro also increment its `filled_len` and then
191 * executes the block. When the block is executed, `elem` is non-null and
192 * points to the newly appended element.
193 */
194 #define vk_outarray_append(a, elem) \
195 for (vk_outarray_typeof_elem(a)* elem = vk_outarray_next(a); elem != NULL; elem = NULL)
196
__vk_find_struct(void * start,VkStructureType sType)197 static inline void* __vk_find_struct(void* start, VkStructureType sType) {
198 vk_foreach_struct(s, start) {
199 if (s->sType == sType) return s;
200 }
201
202 return NULL;
203 }
204
205 template <class T, class H>
vk_find_struct(H * head)206 T* vk_find_struct(H* head) {
207 (void)vk_get_vk_struct_id<H>::id;
208 return static_cast<T*>(__vk_find_struct(static_cast<void*>(head), vk_get_vk_struct_id<T>::id));
209 }
210
211 template <class T, class H>
vk_find_struct(const H * head)212 const T* vk_find_struct(const H* head) {
213 (void)vk_get_vk_struct_id<H>::id;
214 return static_cast<const T*>(__vk_find_struct(const_cast<void*>(static_cast<const void*>(head)),
215 vk_get_vk_struct_id<T>::id));
216 }
217
218 uint32_t vk_get_driver_version(void);
219
220 uint32_t vk_get_version_override(void);
221
222 #define VK_EXT_OFFSET (1000000000UL)
223 #define VK_ENUM_EXTENSION(__enum) \
224 ((__enum) >= VK_EXT_OFFSET ? ((((__enum)-VK_EXT_OFFSET) / 1000UL) + 1) : 0)
225 #define VK_ENUM_OFFSET(__enum) ((__enum) >= VK_EXT_OFFSET ? ((__enum) % 1000) : (__enum))
226
227 template <class T>
vk_make_orphan_copy(const T & vk_struct)228 T vk_make_orphan_copy(const T& vk_struct) {
229 T copy = vk_struct;
230 copy.pNext = NULL;
231 return copy;
232 }
233
234 template <class T>
vk_make_chain_iterator(T * vk_struct)235 vk_struct_chain_iterator vk_make_chain_iterator(T* vk_struct) {
236 (void)vk_get_vk_struct_id<T>::id;
237 vk_struct_chain_iterator result = {reinterpret_cast<vk_struct_common*>(vk_struct)};
238 return result;
239 }
240
241 template <class T>
vk_append_struct(vk_struct_chain_iterator * i,T * vk_struct)242 void vk_append_struct(vk_struct_chain_iterator* i, T* vk_struct) {
243 (void)vk_get_vk_struct_id<T>::id;
244
245 vk_struct_common* p = i->value;
246 if (p->pNext) {
247 ::abort();
248 }
249
250 p->pNext = reinterpret_cast<vk_struct_common*>(vk_struct);
251 vk_struct->pNext = NULL;
252
253 *i = vk_make_chain_iterator(vk_struct);
254 }
255
256 // The caller should guarantee that all the pNext structs in the chain starting at nextChain is not
257 // a const object to avoid unexpected undefined behavior.
258 template <class T, class U, typename = std::enable_if_t<!std::is_const_v<T> && !std::is_const_v<U>>>
vk_insert_struct(T & pos,U & nextChain)259 void vk_insert_struct(T& pos, U& nextChain) {
260 vk_struct_common* nextChainTail = reinterpret_cast<vk_struct_common*>(&nextChain);
261 for (; nextChainTail->pNext; nextChainTail = nextChainTail->pNext) {}
262
263 nextChainTail->pNext = reinterpret_cast<vk_struct_common*>(const_cast<void*>(pos.pNext));
264 pos.pNext = &nextChain;
265 }
266
267 template <class S, class T>
vk_struct_chain_remove(S * unwanted,T * vk_struct)268 void vk_struct_chain_remove(S* unwanted, T* vk_struct) {
269 if (!unwanted) return;
270
271 vk_foreach_struct(current, vk_struct) {
272 if ((void*)unwanted == current->pNext) {
273 const vk_struct_common* unwanted_as_common =
274 reinterpret_cast<const vk_struct_common*>(unwanted);
275 current->pNext = unwanted_as_common->pNext;
276 }
277 }
278 }
279
280 #define VK_CHECK(x) \
281 do { \
282 VkResult err = x; \
283 if (err != VK_SUCCESS) { \
284 if (err == VK_ERROR_DEVICE_LOST) { \
285 vk_util::getVkCheckCallbacks().callIfExists( \
286 &vk_util::VkCheckCallbacks::onVkErrorDeviceLost); \
287 } \
288 if (err == VK_ERROR_OUT_OF_HOST_MEMORY || err == VK_ERROR_OUT_OF_DEVICE_MEMORY || \
289 err == VK_ERROR_OUT_OF_POOL_MEMORY) { \
290 vk_util::getVkCheckCallbacks().callIfExists( \
291 &vk_util::VkCheckCallbacks::onVkErrorOutOfMemory, err, __func__, __LINE__); \
292 } \
293 GFXSTREAM_ABORT(::emugl::FatalError(err)); \
294 } \
295 } while (0)
296
297 #define VK_CHECK_MEMALLOC(x, allocateInfo) \
298 do { \
299 VkResult err = x; \
300 if (err != VK_SUCCESS) { \
301 if (err == VK_ERROR_OUT_OF_HOST_MEMORY || err == VK_ERROR_OUT_OF_DEVICE_MEMORY) { \
302 vk_util::getVkCheckCallbacks().callIfExists( \
303 &vk_util::VkCheckCallbacks::onVkErrorOutOfMemoryOnAllocation, err, __func__, \
304 __LINE__, allocateInfo.allocationSize); \
305 } \
306 GFXSTREAM_ABORT(::emugl::FatalError(err)); \
307 } \
308 } while (0)
309
310 typedef void* MTLTextureRef;
311 typedef void* MTLBufferRef;
312
313 namespace vk_util {
314
waitForVkQueueIdleWithRetry(const VulkanDispatch & vk,VkQueue queue)315 inline VkResult waitForVkQueueIdleWithRetry(const VulkanDispatch& vk, VkQueue queue) {
316 using namespace std::chrono_literals;
317 constexpr uint32_t retryLimit = 5;
318 constexpr std::chrono::duration waitInterval = 4ms;
319 VkResult res = vk.vkQueueWaitIdle(queue);
320 for (uint32_t retryTimes = 1; retryTimes < retryLimit && res == VK_TIMEOUT; retryTimes++) {
321 INFO("VK_TIMEOUT returned from vkQueueWaitIdle with %" PRIu32 " attempt. Wait for %" PRIu32
322 "ms before another attempt.",
323 retryTimes,
324 static_cast<uint32_t>(
325 std::chrono::duration_cast<std::chrono::milliseconds>(waitInterval).count()));
326 std::this_thread::sleep_for(waitInterval);
327 res = vk.vkQueueWaitIdle(queue);
328 }
329 return res;
330 }
331
332 typedef struct {
333 std::function<void()> onVkErrorDeviceLost;
334 std::function<void(VkResult, const char*, int)> onVkErrorOutOfMemory;
335 std::function<void(VkResult, const char*, int, uint64_t)> onVkErrorOutOfMemoryOnAllocation;
336 } VkCheckCallbacks;
337
338 template <class T>
339 class CallbacksWrapper {
340 public:
CallbacksWrapper(std::unique_ptr<T> callbacks)341 CallbacksWrapper(std::unique_ptr<T> callbacks) : mCallbacks(std::move(callbacks)) {}
342 // function should be a member function pointer to T.
343 template <class U, class... Args>
callIfExists(U function,Args &&...args)344 void callIfExists(U function, Args&&... args) const {
345 if (mCallbacks && (*mCallbacks.*function)) {
346 (*mCallbacks.*function)(std::forward<Args>(args)...);
347 }
348 }
349
get()350 T* get() const { return mCallbacks.get(); }
351
352 private:
353 std::unique_ptr<T> mCallbacks;
354 };
355
356 std::optional<uint32_t> findMemoryType(const VulkanDispatch* ivk, VkPhysicalDevice physicalDevice,
357 uint32_t typeFilter, VkMemoryPropertyFlags properties);
358
359 void setVkCheckCallbacks(std::unique_ptr<VkCheckCallbacks>);
360 const CallbacksWrapper<VkCheckCallbacks>& getVkCheckCallbacks();
361
362 class CrtpBase {};
363
364 // Utility class to make chaining inheritance of multiple CRTP classes more
365 // readable by allowing one to replace
366 //
367 // class MyClass
368 // : public vk_util::Crtp1<MyClass,
369 // vk_util::Crtp2<MyClass,
370 // vk_util::Crtp3<MyClass>>> {};
371 //
372 // with
373 //
374 // class MyClass :
375 // : public vk_util::MultiCrtp<MyClass,
376 // vk_util::Crtp1,
377 // vk_util::Crtp2,
378 // vk_util::Ctrp3> {};
379 namespace vk_util_internal {
380
381 // For the template "recursion", this is the base case where the list is empty
382 // and which just inherits from the last type.
383 template <typename T, //
384 typename U, //
385 template <typename, typename> class... CrtpClasses>
386 class MultiCrtpChainHelper : public U {};
387
388 // For the template "recursion", this is the case where the list is not empty
389 // and which uses the "current" CRTP class as the "U" type and passes the
390 // resulting type to the next step in the template "recursion".
391 template <typename T, //
392 typename U, //
393 template <typename, typename> class Crtp, //
394 template <typename, typename> class... Crtps>
395 class MultiCrtpChainHelper<T, U, Crtp, Crtps...>
396 : public MultiCrtpChainHelper<T, Crtp<T, U>, Crtps...> {};
397
398 } // namespace vk_util_internal
399
400 template <typename T, //
401 template <typename, typename> class... CrtpClasses>
402 class MultiCrtp : public vk_util_internal::MultiCrtpChainHelper<T, CrtpBase, CrtpClasses...> {};
403
404 template <class T, class U = CrtpBase>
405 class FindMemoryType : public U {
406 protected:
findMemoryType(uint32_t typeFilter,VkMemoryPropertyFlags properties)407 std::optional<uint32_t> findMemoryType(uint32_t typeFilter,
408 VkMemoryPropertyFlags properties) const {
409 const T& self = static_cast<const T&>(*this);
410 return vk_util::findMemoryType(&self.m_vk, self.m_vkPhysicalDevice, typeFilter, properties);
411 }
412 };
413
414 template <class T, class U = CrtpBase>
415 class RunSingleTimeCommand : public U {
416 protected:
runSingleTimeCommands(VkQueue queue,std::shared_ptr<android::base::Lock> queueLock,std::function<void (const VkCommandBuffer & commandBuffer)> f)417 void runSingleTimeCommands(VkQueue queue, std::shared_ptr<android::base::Lock> queueLock,
418 std::function<void(const VkCommandBuffer& commandBuffer)> f) const {
419 const T& self = static_cast<const T&>(*this);
420 VkCommandBuffer cmdBuff;
421 VkCommandBufferAllocateInfo cmdBuffAllocInfo = {
422 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
423 .commandPool = self.m_vkCommandPool,
424 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
425 .commandBufferCount = 1};
426 VK_CHECK(self.m_vk.vkAllocateCommandBuffers(self.m_vkDevice, &cmdBuffAllocInfo, &cmdBuff));
427 VkCommandBufferBeginInfo beginInfo = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
428 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
429 VK_CHECK(self.m_vk.vkBeginCommandBuffer(cmdBuff, &beginInfo));
430 f(cmdBuff);
431 VK_CHECK(self.m_vk.vkEndCommandBuffer(cmdBuff));
432 VkSubmitInfo submitInfo = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
433 .commandBufferCount = 1,
434 .pCommandBuffers = &cmdBuff};
435 {
436 std::unique_ptr<android::base::AutoLock> lock = nullptr;
437 if (queueLock) {
438 lock = std::make_unique<android::base::AutoLock>(*queueLock);
439 }
440 VK_CHECK(self.m_vk.vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
441 VK_CHECK(self.m_vk.vkQueueWaitIdle(queue));
442 }
443 self.m_vk.vkFreeCommandBuffers(self.m_vkDevice, self.m_vkCommandPool, 1, &cmdBuff);
444 }
445 };
446 template <class T, class U = CrtpBase>
447 class RecordImageLayoutTransformCommands : public U {
448 protected:
recordImageLayoutTransformCommands(VkCommandBuffer cmdBuff,VkImage image,VkImageLayout oldLayout,VkImageLayout newLayout)449 void recordImageLayoutTransformCommands(VkCommandBuffer cmdBuff, VkImage image,
450 VkImageLayout oldLayout,
451 VkImageLayout newLayout) const {
452 const T& self = static_cast<const T&>(*this);
453 VkImageMemoryBarrier imageBarrier = {
454 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
455 .srcAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
456 .dstAccessMask = VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
457 .oldLayout = oldLayout,
458 .newLayout = newLayout,
459 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
460 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
461 .image = image,
462 .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
463 .baseMipLevel = 0,
464 .levelCount = 1,
465 .baseArrayLayer = 0,
466 .layerCount = 1}};
467 self.m_vk.vkCmdPipelineBarrier(cmdBuff, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
468 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 0,
469 nullptr, 1, &imageBarrier);
470 }
471 };
472
473 template <class T>
getVkInstanceProcAddrWithFallback(const std::vector<std::function<std::remove_pointer_t<PFN_vkGetInstanceProcAddr>>> & vkGetInstanceProcAddrs,VkInstance instance)474 typename vk_fn_info::GetVkFnInfo<T>::type getVkInstanceProcAddrWithFallback(
475 const std::vector<std::function<std::remove_pointer_t<PFN_vkGetInstanceProcAddr>>>&
476 vkGetInstanceProcAddrs,
477 VkInstance instance) {
478 for (const auto& vkGetInstanceProcAddr : vkGetInstanceProcAddrs) {
479 if (!vkGetInstanceProcAddr) {
480 continue;
481 }
482 PFN_vkVoidFunction resWithCurrentVkGetInstanceProcAddr = std::apply(
483 [&vkGetInstanceProcAddr, instance](auto&&... names) -> PFN_vkVoidFunction {
484 for (const char* name : {names...}) {
485 if (PFN_vkVoidFunction resWithCurrentName =
486 vkGetInstanceProcAddr(instance, name)) {
487 return resWithCurrentName;
488 }
489 }
490 return nullptr;
491 },
492 vk_fn_info::GetVkFnInfo<T>::names);
493 if (resWithCurrentVkGetInstanceProcAddr) {
494 return reinterpret_cast<typename vk_fn_info::GetVkFnInfo<T>::type>(
495 resWithCurrentVkGetInstanceProcAddr);
496 }
497 }
498 return nullptr;
499 }
500
501 } // namespace vk_util
502 } // namespace vk
503 } // namespace gfxstream
504
505 #endif /* VK_UTIL_H */
506