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 <stdio.h>
29 #include <stdlib.h>
30 #include <vulkan/vulkan.h>
31
32 #include <functional>
33 #include <memory>
34 #include <optional>
35 #include <string>
36 #include <tuple>
37 #include <type_traits>
38 #include <vector>
39
40 #include "base/Lock.h"
41 #include "common/vk_struct_id.h"
42 #include "host-common/GfxstreamFatalError.h"
43 #include "vk_fn_info.h"
44
45 struct vk_struct_common {
46 VkStructureType sType;
47 struct vk_struct_common *pNext;
48 };
49
50 struct vk_struct_chain_iterator {
51 vk_struct_common *value;
52 };
53
54 #define vk_foreach_struct(__iter, __start) \
55 for (struct vk_struct_common *__iter = \
56 (struct vk_struct_common *)(__start); \
57 __iter; __iter = __iter->pNext)
58
59 #define vk_foreach_struct_const(__iter, __start) \
60 for (const struct vk_struct_common *__iter = \
61 (const struct vk_struct_common *)(__start); \
62 __iter; __iter = __iter->pNext)
63
64 /**
65 * A wrapper for a Vulkan output array. A Vulkan output array is one that
66 * follows the convention of the parameters to
67 * vkGetPhysicalDeviceQueueFamilyProperties().
68 *
69 * Example Usage:
70 *
71 * VkResult
72 * vkGetPhysicalDeviceQueueFamilyProperties(
73 * VkPhysicalDevice physicalDevice,
74 * uint32_t* pQueueFamilyPropertyCount,
75 * VkQueueFamilyProperties* pQueueFamilyProperties)
76 * {
77 * VK_OUTARRAY_MAKE(props, pQueueFamilyProperties,
78 * pQueueFamilyPropertyCount);
79 *
80 * vk_outarray_append(&props, p) {
81 * p->queueFlags = ...;
82 * p->queueCount = ...;
83 * }
84 *
85 * vk_outarray_append(&props, p) {
86 * p->queueFlags = ...;
87 * p->queueCount = ...;
88 * }
89 *
90 * return vk_outarray_status(&props);
91 * }
92 */
93 struct __vk_outarray {
94 /** May be null. */
95 void *data;
96
97 /**
98 * Capacity, in number of elements. Capacity is unlimited (UINT32_MAX) if
99 * data is null.
100 */
101 uint32_t cap;
102
103 /**
104 * Count of elements successfully written to the array. Every write is
105 * considered successful if data is null.
106 */
107 uint32_t *filled_len;
108
109 /**
110 * Count of elements that would have been written to the array if its
111 * capacity were sufficient. Vulkan functions often return VK_INCOMPLETE
112 * when `*filled_len < wanted_len`.
113 */
114 uint32_t wanted_len;
115 };
116
__vk_outarray_init(struct __vk_outarray * a,void * data,uint32_t * len)117 static inline void __vk_outarray_init(struct __vk_outarray *a, void *data,
118 uint32_t *len) {
119 a->data = data;
120 a->cap = *len;
121 a->filled_len = len;
122 *a->filled_len = 0;
123 a->wanted_len = 0;
124
125 if (a->data == NULL) a->cap = UINT32_MAX;
126 }
127
__vk_outarray_status(const struct __vk_outarray * a)128 static inline VkResult __vk_outarray_status(const struct __vk_outarray *a) {
129 if (*a->filled_len < a->wanted_len)
130 return VK_INCOMPLETE;
131 else
132 return VK_SUCCESS;
133 }
134
__vk_outarray_next(struct __vk_outarray * a,size_t elem_size)135 static inline void *__vk_outarray_next(struct __vk_outarray *a,
136 size_t elem_size) {
137 void *p = NULL;
138
139 a->wanted_len += 1;
140
141 if (*a->filled_len >= a->cap) return NULL;
142
143 if (a->data != NULL)
144 p = ((uint8_t *)a->data) + (*a->filled_len) * elem_size;
145
146 *a->filled_len += 1;
147
148 return p;
149 }
150
151 #define vk_outarray(elem_t) \
152 struct { \
153 struct __vk_outarray base; \
154 elem_t meta[]; \
155 }
156
157 #define vk_outarray_typeof_elem(a) __typeof__((a)->meta[0])
158 #define vk_outarray_sizeof_elem(a) sizeof((a)->meta[0])
159
160 #define vk_outarray_init(a, data, len) \
161 __vk_outarray_init(&(a)->base, (data), (len))
162
163 #define VK_OUTARRAY_MAKE(name, data, len) \
164 vk_outarray(__typeof__((data)[0])) name; \
165 vk_outarray_init(&name, (data), (len))
166
167 #define vk_outarray_status(a) __vk_outarray_status(&(a)->base)
168
169 #define vk_outarray_next(a) \
170 ((vk_outarray_typeof_elem(a) *)__vk_outarray_next( \
171 &(a)->base, vk_outarray_sizeof_elem(a)))
172
173 /**
174 * Append to a Vulkan output array.
175 *
176 * This is a block-based macro. For example:
177 *
178 * vk_outarray_append(&a, elem) {
179 * elem->foo = ...;
180 * elem->bar = ...;
181 * }
182 *
183 * The array `a` has type `vk_outarray(elem_t) *`. It is usually declared with
184 * VK_OUTARRAY_MAKE(). The variable `elem` is block-scoped and has type
185 * `elem_t *`.
186 *
187 * The macro unconditionally increments the array's `wanted_len`. If the array
188 * is not full, then the macro also increment its `filled_len` and then
189 * executes the block. When the block is executed, `elem` is non-null and
190 * points to the newly appended element.
191 */
192 #define vk_outarray_append(a, elem) \
193 for (vk_outarray_typeof_elem(a) *elem = vk_outarray_next(a); elem != NULL; \
194 elem = NULL)
195
__vk_find_struct(void * start,VkStructureType sType)196 static inline void *__vk_find_struct(void *start, VkStructureType sType) {
197 vk_foreach_struct(s, start) {
198 if (s->sType == sType) return s;
199 }
200
201 return NULL;
202 }
203
204 template <class T, class H>
vk_find_struct(H * head)205 T *vk_find_struct(H *head) {
206 (void)vk_get_vk_struct_id<H>::id;
207 return static_cast<T *>(__vk_find_struct(static_cast<void *>(head),
208 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 *>(
215 __vk_find_struct(const_cast<void *>(static_cast<const void *>(head)),
216 vk_get_vk_struct_id<T>::id));
217 }
218
219 uint32_t vk_get_driver_version(void);
220
221 uint32_t vk_get_version_override(void);
222
223 #define VK_EXT_OFFSET (1000000000UL)
224 #define VK_ENUM_EXTENSION(__enum) \
225 ((__enum) >= VK_EXT_OFFSET ? ((((__enum)-VK_EXT_OFFSET) / 1000UL) + 1) : 0)
226 #define VK_ENUM_OFFSET(__enum) \
227 ((__enum) >= VK_EXT_OFFSET ? ((__enum) % 1000) : (__enum))
228
229 template <class T>
vk_make_orphan_copy(const T & vk_struct)230 T vk_make_orphan_copy(const T &vk_struct) {
231 T copy = vk_struct;
232 copy.pNext = NULL;
233 return copy;
234 }
235
236 template <class T>
vk_make_chain_iterator(T * vk_struct)237 vk_struct_chain_iterator vk_make_chain_iterator(T *vk_struct) {
238 vk_get_vk_struct_id<T>::id;
239 vk_struct_chain_iterator result = {
240 reinterpret_cast<vk_struct_common *>(vk_struct)};
241 return result;
242 }
243
244 template <class T>
vk_append_struct(vk_struct_chain_iterator * i,T * vk_struct)245 void vk_append_struct(vk_struct_chain_iterator *i, T *vk_struct) {
246 vk_get_vk_struct_id<T>::id;
247
248 vk_struct_common *p = i->value;
249 if (p->pNext) {
250 ::abort();
251 }
252
253 p->pNext = reinterpret_cast<vk_struct_common *>(vk_struct);
254 vk_struct->pNext = NULL;
255
256 *i = vk_make_chain_iterator(vk_struct);
257 }
258
vk_struct_chain_remove(S * unwanted,T * vk_struct)259 template <class S, class T> void vk_struct_chain_remove(S* unwanted, T* vk_struct)
260 {
261 if (!unwanted) return;
262
263 vk_foreach_struct(current, vk_struct) {
264 if ((void*)unwanted == current->pNext) {
265 const vk_struct_common* unwanted_as_common =
266 reinterpret_cast<const vk_struct_common*>(unwanted);
267 current->pNext = unwanted_as_common->pNext;
268 }
269 }
270 }
271
272 #define VK_CHECK(x) \
273 do { \
274 VkResult err = x; \
275 if (err != VK_SUCCESS) { \
276 if (err == VK_ERROR_DEVICE_LOST) { \
277 ::vk_util::getVkCheckCallbacks().callIfExists( \
278 &::vk_util::VkCheckCallbacks::onVkErrorDeviceLost); \
279 } \
280 GFXSTREAM_ABORT(::emugl::FatalError(err)); \
281 } \
282 } while (0)
283
284 namespace vk_util {
285
286 typedef struct {
287 std::function<void()> onVkErrorDeviceLost;
288 } VkCheckCallbacks;
289
290 template <class T>
291 class CallbacksWrapper {
292 public:
CallbacksWrapper(std::unique_ptr<T> callbacks)293 CallbacksWrapper(std::unique_ptr<T> callbacks) : mCallbacks(std::move(callbacks)) {}
294 // function should be a member function pointer to T.
295 template <class U, class... Args>
callIfExists(U function,Args &&...args)296 void callIfExists(U function, Args &&...args) const {
297 if (mCallbacks && (*mCallbacks.*function)) {
298 (*mCallbacks.*function)(std::forward(args)...);
299 }
300 }
301
302 private:
303 std::unique_ptr<T> mCallbacks;
304 };
305
306 void setVkCheckCallbacks(std::unique_ptr<VkCheckCallbacks>);
307 const CallbacksWrapper<VkCheckCallbacks> &getVkCheckCallbacks();
308
309 class CRTPBase {};
310
311 template <class T, class U = CRTPBase>
312 class FindMemoryType : public U {
313 protected:
findMemoryType(uint32_t typeFilter,VkMemoryPropertyFlags properties)314 std::optional<uint32_t> findMemoryType(
315 uint32_t typeFilter, VkMemoryPropertyFlags properties) const {
316 const T &self = static_cast<const T &>(*this);
317 VkPhysicalDeviceMemoryProperties memProperties;
318 self.m_vk.vkGetPhysicalDeviceMemoryProperties(self.m_vkPhysicalDevice,
319 &memProperties);
320
321 for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) {
322 if ((typeFilter & (1 << i)) &&
323 (memProperties.memoryTypes[i].propertyFlags & properties) ==
324 properties) {
325 return i;
326 }
327 }
328 return std::nullopt;
329 }
330 };
331
332 template <class T, class U = CRTPBase>
333 class RunSingleTimeCommand : public U {
334 protected:
runSingleTimeCommands(VkQueue queue,std::shared_ptr<android::base::Lock> queueLock,std::function<void (const VkCommandBuffer & commandBuffer)> f)335 void runSingleTimeCommands(
336 VkQueue queue, std::shared_ptr<android::base::Lock> queueLock,
337 std::function<void(const VkCommandBuffer &commandBuffer)> f) const {
338 const T &self = static_cast<const T &>(*this);
339 VkCommandBuffer cmdBuff;
340 VkCommandBufferAllocateInfo cmdBuffAllocInfo = {
341 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
342 .commandPool = self.m_vkCommandPool,
343 .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
344 .commandBufferCount = 1};
345 VK_CHECK(self.m_vk.vkAllocateCommandBuffers(
346 self.m_vkDevice, &cmdBuffAllocInfo, &cmdBuff));
347 VkCommandBufferBeginInfo beginInfo = {
348 .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
349 .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
350 VK_CHECK(self.m_vk.vkBeginCommandBuffer(cmdBuff, &beginInfo));
351 f(cmdBuff);
352 VK_CHECK(self.m_vk.vkEndCommandBuffer(cmdBuff));
353 VkSubmitInfo submitInfo = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
354 .commandBufferCount = 1,
355 .pCommandBuffers = &cmdBuff};
356 {
357 std::unique_ptr<android::base::AutoLock> lock = nullptr;
358 if (queueLock) {
359 lock = std::make_unique<android::base::AutoLock>(*queueLock);
360 }
361 VK_CHECK(
362 self.m_vk.vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
363 VK_CHECK(self.m_vk.vkQueueWaitIdle(queue));
364 }
365 self.m_vk.vkFreeCommandBuffers(self.m_vkDevice, self.m_vkCommandPool, 1,
366 &cmdBuff);
367 }
368 };
369 template <class T, class U = CRTPBase>
370 class RecordImageLayoutTransformCommands : public U {
371 protected:
recordImageLayoutTransformCommands(VkCommandBuffer cmdBuff,VkImage image,VkImageLayout oldLayout,VkImageLayout newLayout)372 void recordImageLayoutTransformCommands(VkCommandBuffer cmdBuff,
373 VkImage image,
374 VkImageLayout oldLayout,
375 VkImageLayout newLayout) const {
376 const T &self = static_cast<const T &>(*this);
377 VkImageMemoryBarrier imageBarrier = {
378 .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
379 .srcAccessMask =
380 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
381 .dstAccessMask =
382 VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
383 .oldLayout = oldLayout,
384 .newLayout = newLayout,
385 .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
386 .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
387 .image = image,
388 .subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
389 .baseMipLevel = 0,
390 .levelCount = 1,
391 .baseArrayLayer = 0,
392 .layerCount = 1}};
393 self.m_vk.vkCmdPipelineBarrier(cmdBuff,
394 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
395 VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0,
396 nullptr, 0, nullptr, 1, &imageBarrier);
397 }
398 };
399
400 template <class T>
getVkInstanceProcAddrWithFallback(const std::vector<std::function<std::remove_pointer_t<PFN_vkGetInstanceProcAddr>>> & vkGetInstanceProcAddrs,VkInstance instance)401 typename vk_fn_info::GetVkFnInfo<T>::type getVkInstanceProcAddrWithFallback(
402 const std::vector<std::function<std::remove_pointer_t<PFN_vkGetInstanceProcAddr>>>
403 &vkGetInstanceProcAddrs,
404 VkInstance instance) {
405 for (const auto &vkGetInstanceProcAddr : vkGetInstanceProcAddrs) {
406 if (!vkGetInstanceProcAddr) {
407 continue;
408 }
409 PFN_vkVoidFunction resWithCurrentVkGetInstanceProcAddr = std::apply(
410 [&vkGetInstanceProcAddr, instance](auto &&...names) -> PFN_vkVoidFunction {
411 for (const char *name : {names...}) {
412 if (PFN_vkVoidFunction resWithCurrentName =
413 vkGetInstanceProcAddr(instance, name)) {
414 return resWithCurrentName;
415 }
416 }
417 return nullptr;
418 },
419 vk_fn_info::GetVkFnInfo<T>::names);
420 if (resWithCurrentVkGetInstanceProcAddr) {
421 return reinterpret_cast<typename vk_fn_info::GetVkFnInfo<T>::type>(
422 resWithCurrentVkGetInstanceProcAddr);
423 }
424 }
425 return nullptr;
426 }
427 } // namespace vk_util
428
429 #endif /* VK_UTIL_H */
430