anv: don't crash on vkDestroyDevice(NULL)
[mesa.git] / src / intel / vulkan / anv_device.c
1 /*
2 * Copyright © 2015 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
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <string.h>
27 #include <sys/mman.h>
28 #include <sys/sysinfo.h>
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include <xf86drm.h>
32 #include <drm_fourcc.h>
33
34 #include "anv_private.h"
35 #include "util/strtod.h"
36 #include "util/debug.h"
37 #include "util/build_id.h"
38 #include "util/disk_cache.h"
39 #include "util/mesa-sha1.h"
40 #include "vk_util.h"
41 #include "common/gen_defines.h"
42
43 #include "genxml/gen7_pack.h"
44
45 static void
46 compiler_debug_log(void *data, const char *fmt, ...)
47 { }
48
49 static void
50 compiler_perf_log(void *data, const char *fmt, ...)
51 {
52 va_list args;
53 va_start(args, fmt);
54
55 if (unlikely(INTEL_DEBUG & DEBUG_PERF))
56 intel_logd_v(fmt, args);
57
58 va_end(args);
59 }
60
61 static VkResult
62 anv_compute_heap_size(int fd, uint64_t gtt_size, uint64_t *heap_size)
63 {
64 /* Query the total ram from the system */
65 struct sysinfo info;
66 sysinfo(&info);
67
68 uint64_t total_ram = (uint64_t)info.totalram * (uint64_t)info.mem_unit;
69
70 /* We don't want to burn too much ram with the GPU. If the user has 4GiB
71 * or less, we use at most half. If they have more than 4GiB, we use 3/4.
72 */
73 uint64_t available_ram;
74 if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
75 available_ram = total_ram / 2;
76 else
77 available_ram = total_ram * 3 / 4;
78
79 /* We also want to leave some padding for things we allocate in the driver,
80 * so don't go over 3/4 of the GTT either.
81 */
82 uint64_t available_gtt = gtt_size * 3 / 4;
83
84 *heap_size = MIN2(available_ram, available_gtt);
85
86 return VK_SUCCESS;
87 }
88
89 static VkResult
90 anv_physical_device_init_heaps(struct anv_physical_device *device, int fd)
91 {
92 uint64_t gtt_size;
93 if (anv_gem_get_context_param(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE,
94 &gtt_size) == -1) {
95 /* If, for whatever reason, we can't actually get the GTT size from the
96 * kernel (too old?) fall back to the aperture size.
97 */
98 anv_perf_warn(NULL, NULL,
99 "Failed to get I915_CONTEXT_PARAM_GTT_SIZE: %m");
100
101 if (anv_gem_get_aperture(fd, &gtt_size) == -1) {
102 return vk_errorf(NULL, NULL, VK_ERROR_INITIALIZATION_FAILED,
103 "failed to get aperture size: %m");
104 }
105 }
106
107 device->supports_48bit_addresses = (device->info.gen >= 8) &&
108 gtt_size > (4ULL << 30 /* GiB */);
109
110 uint64_t heap_size = 0;
111 VkResult result = anv_compute_heap_size(fd, gtt_size, &heap_size);
112 if (result != VK_SUCCESS)
113 return result;
114
115 if (heap_size > (2ull << 30) && !device->supports_48bit_addresses) {
116 /* When running with an overridden PCI ID, we may get a GTT size from
117 * the kernel that is greater than 2 GiB but the execbuf check for 48bit
118 * address support can still fail. Just clamp the address space size to
119 * 2 GiB if we don't have 48-bit support.
120 */
121 intel_logw("%s:%d: The kernel reported a GTT size larger than 2 GiB but "
122 "not support for 48-bit addresses",
123 __FILE__, __LINE__);
124 heap_size = 2ull << 30;
125 }
126
127 if (heap_size <= 3ull * (1ull << 30)) {
128 /* In this case, everything fits nicely into the 32-bit address space,
129 * so there's no need for supporting 48bit addresses on client-allocated
130 * memory objects.
131 */
132 device->memory.heap_count = 1;
133 device->memory.heaps[0] = (struct anv_memory_heap) {
134 .size = heap_size,
135 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
136 .supports_48bit_addresses = false,
137 };
138 } else {
139 /* Not everything will fit nicely into a 32-bit address space. In this
140 * case we need a 64-bit heap. Advertise a small 32-bit heap and a
141 * larger 48-bit heap. If we're in this case, then we have a total heap
142 * size larger than 3GiB which most likely means they have 8 GiB of
143 * video memory and so carving off 1 GiB for the 32-bit heap should be
144 * reasonable.
145 */
146 const uint64_t heap_size_32bit = 1ull << 30;
147 const uint64_t heap_size_48bit = heap_size - heap_size_32bit;
148
149 assert(device->supports_48bit_addresses);
150
151 device->memory.heap_count = 2;
152 device->memory.heaps[0] = (struct anv_memory_heap) {
153 .size = heap_size_48bit,
154 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
155 .supports_48bit_addresses = true,
156 };
157 device->memory.heaps[1] = (struct anv_memory_heap) {
158 .size = heap_size_32bit,
159 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
160 .supports_48bit_addresses = false,
161 };
162 }
163
164 uint32_t type_count = 0;
165 for (uint32_t heap = 0; heap < device->memory.heap_count; heap++) {
166 uint32_t valid_buffer_usage = ~0;
167
168 /* There appears to be a hardware issue in the VF cache where it only
169 * considers the bottom 32 bits of memory addresses. If you happen to
170 * have two vertex buffers which get placed exactly 4 GiB apart and use
171 * them in back-to-back draw calls, you can get collisions. In order to
172 * solve this problem, we require vertex and index buffers be bound to
173 * memory allocated out of the 32-bit heap.
174 */
175 if (device->memory.heaps[heap].supports_48bit_addresses) {
176 valid_buffer_usage &= ~(VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
177 VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
178 }
179
180 if (device->info.has_llc) {
181 /* Big core GPUs share LLC with the CPU and thus one memory type can be
182 * both cached and coherent at the same time.
183 */
184 device->memory.types[type_count++] = (struct anv_memory_type) {
185 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
186 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
187 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
188 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
189 .heapIndex = heap,
190 .valid_buffer_usage = valid_buffer_usage,
191 };
192 } else {
193 /* The spec requires that we expose a host-visible, coherent memory
194 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
195 * to give the application a choice between cached, but not coherent and
196 * coherent but uncached (WC though).
197 */
198 device->memory.types[type_count++] = (struct anv_memory_type) {
199 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
200 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
201 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
202 .heapIndex = heap,
203 .valid_buffer_usage = valid_buffer_usage,
204 };
205 device->memory.types[type_count++] = (struct anv_memory_type) {
206 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
207 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
208 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
209 .heapIndex = heap,
210 .valid_buffer_usage = valid_buffer_usage,
211 };
212 }
213 }
214 device->memory.type_count = type_count;
215
216 return VK_SUCCESS;
217 }
218
219 static VkResult
220 anv_physical_device_init_uuids(struct anv_physical_device *device)
221 {
222 const struct build_id_note *note =
223 build_id_find_nhdr_for_addr(anv_physical_device_init_uuids);
224 if (!note) {
225 return vk_errorf(device->instance, device,
226 VK_ERROR_INITIALIZATION_FAILED,
227 "Failed to find build-id");
228 }
229
230 unsigned build_id_len = build_id_length(note);
231 if (build_id_len < 20) {
232 return vk_errorf(device->instance, device,
233 VK_ERROR_INITIALIZATION_FAILED,
234 "build-id too short. It needs to be a SHA");
235 }
236
237 memcpy(device->driver_build_sha1, build_id_data(note), 20);
238
239 struct mesa_sha1 sha1_ctx;
240 uint8_t sha1[20];
241 STATIC_ASSERT(VK_UUID_SIZE <= sizeof(sha1));
242
243 /* The pipeline cache UUID is used for determining when a pipeline cache is
244 * invalid. It needs both a driver build and the PCI ID of the device.
245 */
246 _mesa_sha1_init(&sha1_ctx);
247 _mesa_sha1_update(&sha1_ctx, build_id_data(note), build_id_len);
248 _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
249 sizeof(device->chipset_id));
250 _mesa_sha1_final(&sha1_ctx, sha1);
251 memcpy(device->pipeline_cache_uuid, sha1, VK_UUID_SIZE);
252
253 /* The driver UUID is used for determining sharability of images and memory
254 * between two Vulkan instances in separate processes. People who want to
255 * share memory need to also check the device UUID (below) so all this
256 * needs to be is the build-id.
257 */
258 memcpy(device->driver_uuid, build_id_data(note), VK_UUID_SIZE);
259
260 /* The device UUID uniquely identifies the given device within the machine.
261 * Since we never have more than one device, this doesn't need to be a real
262 * UUID. However, on the off-chance that someone tries to use this to
263 * cache pre-tiled images or something of the like, we use the PCI ID and
264 * some bits of ISL info to ensure that this is safe.
265 */
266 _mesa_sha1_init(&sha1_ctx);
267 _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
268 sizeof(device->chipset_id));
269 _mesa_sha1_update(&sha1_ctx, &device->isl_dev.has_bit6_swizzling,
270 sizeof(device->isl_dev.has_bit6_swizzling));
271 _mesa_sha1_final(&sha1_ctx, sha1);
272 memcpy(device->device_uuid, sha1, VK_UUID_SIZE);
273
274 return VK_SUCCESS;
275 }
276
277 static void
278 anv_physical_device_init_disk_cache(struct anv_physical_device *device)
279 {
280 #ifdef ENABLE_SHADER_CACHE
281 char renderer[10];
282 MAYBE_UNUSED int len = snprintf(renderer, sizeof(renderer), "anv_%04x",
283 device->chipset_id);
284 assert(len == sizeof(renderer) - 2);
285
286 char timestamp[41];
287 _mesa_sha1_format(timestamp, device->driver_build_sha1);
288
289 const uint64_t driver_flags = INTEL_DEBUG & DEBUG_DISK_CACHE_MASK;
290 device->disk_cache = disk_cache_create(renderer, timestamp, driver_flags);
291 #else
292 device->disk_cache = NULL;
293 #endif
294 }
295
296 static void
297 anv_physical_device_free_disk_cache(struct anv_physical_device *device)
298 {
299 #ifdef ENABLE_SHADER_CACHE
300 if (device->disk_cache)
301 disk_cache_destroy(device->disk_cache);
302 #else
303 assert(device->disk_cache == NULL);
304 #endif
305 }
306
307 static VkResult
308 anv_physical_device_init(struct anv_physical_device *device,
309 struct anv_instance *instance,
310 const char *primary_path,
311 const char *path)
312 {
313 VkResult result;
314 int fd;
315 int master_fd = -1;
316
317 brw_process_intel_debug_variable();
318
319 fd = open(path, O_RDWR | O_CLOEXEC);
320 if (fd < 0)
321 return vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
322
323 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
324 device->instance = instance;
325
326 assert(strlen(path) < ARRAY_SIZE(device->path));
327 strncpy(device->path, path, ARRAY_SIZE(device->path));
328
329 device->no_hw = getenv("INTEL_NO_HW") != NULL;
330
331 const int pci_id_override = gen_get_pci_device_id_override();
332 if (pci_id_override < 0) {
333 device->chipset_id = anv_gem_get_param(fd, I915_PARAM_CHIPSET_ID);
334 if (!device->chipset_id) {
335 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
336 goto fail;
337 }
338 } else {
339 device->chipset_id = pci_id_override;
340 device->no_hw = true;
341 }
342
343 device->name = gen_get_device_name(device->chipset_id);
344 if (!gen_get_device_info(device->chipset_id, &device->info)) {
345 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
346 goto fail;
347 }
348
349 if (device->info.is_haswell) {
350 intel_logw("Haswell Vulkan support is incomplete");
351 } else if (device->info.gen == 7 && !device->info.is_baytrail) {
352 intel_logw("Ivy Bridge Vulkan support is incomplete");
353 } else if (device->info.gen == 7 && device->info.is_baytrail) {
354 intel_logw("Bay Trail Vulkan support is incomplete");
355 } else if (device->info.gen >= 8 && device->info.gen <= 10) {
356 /* Gen8-10 fully supported */
357 } else if (device->info.gen == 11) {
358 intel_logw("Vulkan is not yet fully supported on gen11.");
359 } else {
360 result = vk_errorf(device->instance, device,
361 VK_ERROR_INCOMPATIBLE_DRIVER,
362 "Vulkan not yet supported on %s", device->name);
363 goto fail;
364 }
365
366 device->cmd_parser_version = -1;
367 if (device->info.gen == 7) {
368 device->cmd_parser_version =
369 anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
370 if (device->cmd_parser_version == -1) {
371 result = vk_errorf(device->instance, device,
372 VK_ERROR_INITIALIZATION_FAILED,
373 "failed to get command parser version");
374 goto fail;
375 }
376 }
377
378 if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
379 result = vk_errorf(device->instance, device,
380 VK_ERROR_INITIALIZATION_FAILED,
381 "kernel missing gem wait");
382 goto fail;
383 }
384
385 if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
386 result = vk_errorf(device->instance, device,
387 VK_ERROR_INITIALIZATION_FAILED,
388 "kernel missing execbuf2");
389 goto fail;
390 }
391
392 if (!device->info.has_llc &&
393 anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
394 result = vk_errorf(device->instance, device,
395 VK_ERROR_INITIALIZATION_FAILED,
396 "kernel missing wc mmap");
397 goto fail;
398 }
399
400 result = anv_physical_device_init_heaps(device, fd);
401 if (result != VK_SUCCESS)
402 goto fail;
403
404 device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
405 device->has_exec_capture = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_CAPTURE);
406 device->has_exec_fence = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE);
407 device->has_syncobj = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE_ARRAY);
408 device->has_syncobj_wait = device->has_syncobj &&
409 anv_gem_supports_syncobj_wait(fd);
410 device->has_context_priority = anv_gem_has_context_priority(fd);
411
412 device->use_softpin = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_SOFTPIN)
413 && device->supports_48bit_addresses;
414
415 device->has_context_isolation =
416 anv_gem_get_param(fd, I915_PARAM_HAS_CONTEXT_ISOLATION);
417
418 bool swizzled = anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
419
420 /* Starting with Gen10, the timestamp frequency of the command streamer may
421 * vary from one part to another. We can query the value from the kernel.
422 */
423 if (device->info.gen >= 10) {
424 int timestamp_frequency =
425 anv_gem_get_param(fd, I915_PARAM_CS_TIMESTAMP_FREQUENCY);
426
427 if (timestamp_frequency < 0)
428 intel_logw("Kernel 4.16-rc1+ required to properly query CS timestamp frequency");
429 else
430 device->info.timestamp_frequency = timestamp_frequency;
431 }
432
433 /* GENs prior to 8 do not support EU/Subslice info */
434 if (device->info.gen >= 8) {
435 device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
436 device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
437
438 /* Without this information, we cannot get the right Braswell
439 * brandstrings, and we have to use conservative numbers for GPGPU on
440 * many platforms, but otherwise, things will just work.
441 */
442 if (device->subslice_total < 1 || device->eu_total < 1) {
443 intel_logw("Kernel 4.1 required to properly query GPU properties");
444 }
445 } else if (device->info.gen == 7) {
446 device->subslice_total = 1 << (device->info.gt - 1);
447 }
448
449 if (device->info.is_cherryview &&
450 device->subslice_total > 0 && device->eu_total > 0) {
451 /* Logical CS threads = EUs per subslice * num threads per EU */
452 uint32_t max_cs_threads =
453 device->eu_total / device->subslice_total * device->info.num_thread_per_eu;
454
455 /* Fuse configurations may give more threads than expected, never less. */
456 if (max_cs_threads > device->info.max_cs_threads)
457 device->info.max_cs_threads = max_cs_threads;
458 }
459
460 device->compiler = brw_compiler_create(NULL, &device->info);
461 if (device->compiler == NULL) {
462 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
463 goto fail;
464 }
465 device->compiler->shader_debug_log = compiler_debug_log;
466 device->compiler->shader_perf_log = compiler_perf_log;
467 device->compiler->supports_pull_constants = false;
468 device->compiler->constant_buffer_0_is_relative =
469 device->info.gen < 8 || !device->has_context_isolation;
470 device->compiler->supports_shader_constants = true;
471
472 isl_device_init(&device->isl_dev, &device->info, swizzled);
473
474 result = anv_physical_device_init_uuids(device);
475 if (result != VK_SUCCESS)
476 goto fail;
477
478 anv_physical_device_init_disk_cache(device);
479
480 if (instance->enabled_extensions.KHR_display) {
481 master_fd = open(primary_path, O_RDWR | O_CLOEXEC);
482 if (master_fd >= 0) {
483 /* prod the device with a GETPARAM call which will fail if
484 * we don't have permission to even render on this device
485 */
486 if (anv_gem_get_param(master_fd, I915_PARAM_CHIPSET_ID) == 0) {
487 close(master_fd);
488 master_fd = -1;
489 }
490 }
491 }
492 device->master_fd = master_fd;
493
494 result = anv_init_wsi(device);
495 if (result != VK_SUCCESS) {
496 ralloc_free(device->compiler);
497 anv_physical_device_free_disk_cache(device);
498 goto fail;
499 }
500
501 anv_physical_device_get_supported_extensions(device,
502 &device->supported_extensions);
503
504
505 device->local_fd = fd;
506
507 return VK_SUCCESS;
508
509 fail:
510 close(fd);
511 if (master_fd != -1)
512 close(master_fd);
513 return result;
514 }
515
516 static void
517 anv_physical_device_finish(struct anv_physical_device *device)
518 {
519 anv_finish_wsi(device);
520 anv_physical_device_free_disk_cache(device);
521 ralloc_free(device->compiler);
522 close(device->local_fd);
523 if (device->master_fd >= 0)
524 close(device->master_fd);
525 }
526
527 static void *
528 default_alloc_func(void *pUserData, size_t size, size_t align,
529 VkSystemAllocationScope allocationScope)
530 {
531 return malloc(size);
532 }
533
534 static void *
535 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
536 size_t align, VkSystemAllocationScope allocationScope)
537 {
538 return realloc(pOriginal, size);
539 }
540
541 static void
542 default_free_func(void *pUserData, void *pMemory)
543 {
544 free(pMemory);
545 }
546
547 static const VkAllocationCallbacks default_alloc = {
548 .pUserData = NULL,
549 .pfnAllocation = default_alloc_func,
550 .pfnReallocation = default_realloc_func,
551 .pfnFree = default_free_func,
552 };
553
554 VkResult anv_EnumerateInstanceExtensionProperties(
555 const char* pLayerName,
556 uint32_t* pPropertyCount,
557 VkExtensionProperties* pProperties)
558 {
559 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
560
561 for (int i = 0; i < ANV_INSTANCE_EXTENSION_COUNT; i++) {
562 if (anv_instance_extensions_supported.extensions[i]) {
563 vk_outarray_append(&out, prop) {
564 *prop = anv_instance_extensions[i];
565 }
566 }
567 }
568
569 return vk_outarray_status(&out);
570 }
571
572 VkResult anv_CreateInstance(
573 const VkInstanceCreateInfo* pCreateInfo,
574 const VkAllocationCallbacks* pAllocator,
575 VkInstance* pInstance)
576 {
577 struct anv_instance *instance;
578 VkResult result;
579
580 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
581
582 struct anv_instance_extension_table enabled_extensions = {};
583 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
584 int idx;
585 for (idx = 0; idx < ANV_INSTANCE_EXTENSION_COUNT; idx++) {
586 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
587 anv_instance_extensions[idx].extensionName) == 0)
588 break;
589 }
590
591 if (idx >= ANV_INSTANCE_EXTENSION_COUNT)
592 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
593
594 if (!anv_instance_extensions_supported.extensions[idx])
595 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
596
597 enabled_extensions.extensions[idx] = true;
598 }
599
600 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
601 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
602 if (!instance)
603 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
604
605 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
606
607 if (pAllocator)
608 instance->alloc = *pAllocator;
609 else
610 instance->alloc = default_alloc;
611
612 if (pCreateInfo->pApplicationInfo &&
613 pCreateInfo->pApplicationInfo->apiVersion != 0) {
614 instance->apiVersion = pCreateInfo->pApplicationInfo->apiVersion;
615 } else {
616 anv_EnumerateInstanceVersion(&instance->apiVersion);
617 }
618
619 instance->enabled_extensions = enabled_extensions;
620
621 for (unsigned i = 0; i < ARRAY_SIZE(instance->dispatch.entrypoints); i++) {
622 /* Vulkan requires that entrypoints for extensions which have not been
623 * enabled must not be advertised.
624 */
625 if (!anv_entrypoint_is_enabled(i, instance->apiVersion,
626 &instance->enabled_extensions, NULL)) {
627 instance->dispatch.entrypoints[i] = NULL;
628 } else if (anv_dispatch_table.entrypoints[i] != NULL) {
629 instance->dispatch.entrypoints[i] = anv_dispatch_table.entrypoints[i];
630 } else {
631 instance->dispatch.entrypoints[i] =
632 anv_tramp_dispatch_table.entrypoints[i];
633 }
634 }
635
636 instance->physicalDeviceCount = -1;
637
638 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
639 if (result != VK_SUCCESS) {
640 vk_free2(&default_alloc, pAllocator, instance);
641 return vk_error(result);
642 }
643
644 instance->pipeline_cache_enabled =
645 env_var_as_boolean("ANV_ENABLE_PIPELINE_CACHE", true);
646
647 _mesa_locale_init();
648
649 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
650
651 *pInstance = anv_instance_to_handle(instance);
652
653 return VK_SUCCESS;
654 }
655
656 void anv_DestroyInstance(
657 VkInstance _instance,
658 const VkAllocationCallbacks* pAllocator)
659 {
660 ANV_FROM_HANDLE(anv_instance, instance, _instance);
661
662 if (!instance)
663 return;
664
665 if (instance->physicalDeviceCount > 0) {
666 /* We support at most one physical device. */
667 assert(instance->physicalDeviceCount == 1);
668 anv_physical_device_finish(&instance->physicalDevice);
669 }
670
671 VG(VALGRIND_DESTROY_MEMPOOL(instance));
672
673 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
674
675 _mesa_locale_fini();
676
677 vk_free(&instance->alloc, instance);
678 }
679
680 static VkResult
681 anv_enumerate_devices(struct anv_instance *instance)
682 {
683 /* TODO: Check for more devices ? */
684 drmDevicePtr devices[8];
685 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
686 int max_devices;
687
688 instance->physicalDeviceCount = 0;
689
690 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
691 if (max_devices < 1)
692 return VK_ERROR_INCOMPATIBLE_DRIVER;
693
694 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
695 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
696 devices[i]->bustype == DRM_BUS_PCI &&
697 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
698
699 result = anv_physical_device_init(&instance->physicalDevice,
700 instance,
701 devices[i]->nodes[DRM_NODE_PRIMARY],
702 devices[i]->nodes[DRM_NODE_RENDER]);
703 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
704 break;
705 }
706 }
707 drmFreeDevices(devices, max_devices);
708
709 if (result == VK_SUCCESS)
710 instance->physicalDeviceCount = 1;
711
712 return result;
713 }
714
715 static VkResult
716 anv_instance_ensure_physical_device(struct anv_instance *instance)
717 {
718 if (instance->physicalDeviceCount < 0) {
719 VkResult result = anv_enumerate_devices(instance);
720 if (result != VK_SUCCESS &&
721 result != VK_ERROR_INCOMPATIBLE_DRIVER)
722 return result;
723 }
724
725 return VK_SUCCESS;
726 }
727
728 VkResult anv_EnumeratePhysicalDevices(
729 VkInstance _instance,
730 uint32_t* pPhysicalDeviceCount,
731 VkPhysicalDevice* pPhysicalDevices)
732 {
733 ANV_FROM_HANDLE(anv_instance, instance, _instance);
734 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
735
736 VkResult result = anv_instance_ensure_physical_device(instance);
737 if (result != VK_SUCCESS)
738 return result;
739
740 if (instance->physicalDeviceCount == 0)
741 return VK_SUCCESS;
742
743 assert(instance->physicalDeviceCount == 1);
744 vk_outarray_append(&out, i) {
745 *i = anv_physical_device_to_handle(&instance->physicalDevice);
746 }
747
748 return vk_outarray_status(&out);
749 }
750
751 VkResult anv_EnumeratePhysicalDeviceGroups(
752 VkInstance _instance,
753 uint32_t* pPhysicalDeviceGroupCount,
754 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
755 {
756 ANV_FROM_HANDLE(anv_instance, instance, _instance);
757 VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
758 pPhysicalDeviceGroupCount);
759
760 VkResult result = anv_instance_ensure_physical_device(instance);
761 if (result != VK_SUCCESS)
762 return result;
763
764 if (instance->physicalDeviceCount == 0)
765 return VK_SUCCESS;
766
767 assert(instance->physicalDeviceCount == 1);
768
769 vk_outarray_append(&out, p) {
770 p->physicalDeviceCount = 1;
771 memset(p->physicalDevices, 0, sizeof(p->physicalDevices));
772 p->physicalDevices[0] =
773 anv_physical_device_to_handle(&instance->physicalDevice);
774 p->subsetAllocation = VK_FALSE;
775
776 vk_foreach_struct(ext, p->pNext)
777 anv_debug_ignored_stype(ext->sType);
778 }
779
780 return vk_outarray_status(&out);
781 }
782
783 void anv_GetPhysicalDeviceFeatures(
784 VkPhysicalDevice physicalDevice,
785 VkPhysicalDeviceFeatures* pFeatures)
786 {
787 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
788
789 *pFeatures = (VkPhysicalDeviceFeatures) {
790 .robustBufferAccess = true,
791 .fullDrawIndexUint32 = true,
792 .imageCubeArray = true,
793 .independentBlend = true,
794 .geometryShader = true,
795 .tessellationShader = true,
796 .sampleRateShading = true,
797 .dualSrcBlend = true,
798 .logicOp = true,
799 .multiDrawIndirect = true,
800 .drawIndirectFirstInstance = true,
801 .depthClamp = true,
802 .depthBiasClamp = true,
803 .fillModeNonSolid = true,
804 .depthBounds = false,
805 .wideLines = true,
806 .largePoints = true,
807 .alphaToOne = true,
808 .multiViewport = true,
809 .samplerAnisotropy = true,
810 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
811 pdevice->info.is_baytrail,
812 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
813 .textureCompressionBC = true,
814 .occlusionQueryPrecise = true,
815 .pipelineStatisticsQuery = true,
816 .fragmentStoresAndAtomics = true,
817 .shaderTessellationAndGeometryPointSize = true,
818 .shaderImageGatherExtended = true,
819 .shaderStorageImageExtendedFormats = true,
820 .shaderStorageImageMultisample = false,
821 .shaderStorageImageReadWithoutFormat = false,
822 .shaderStorageImageWriteWithoutFormat = true,
823 .shaderUniformBufferArrayDynamicIndexing = true,
824 .shaderSampledImageArrayDynamicIndexing = true,
825 .shaderStorageBufferArrayDynamicIndexing = true,
826 .shaderStorageImageArrayDynamicIndexing = true,
827 .shaderClipDistance = true,
828 .shaderCullDistance = true,
829 .shaderFloat64 = pdevice->info.gen >= 8 &&
830 pdevice->info.has_64bit_types,
831 .shaderInt64 = pdevice->info.gen >= 8 &&
832 pdevice->info.has_64bit_types,
833 .shaderInt16 = pdevice->info.gen >= 8,
834 .shaderResourceMinLod = false,
835 .variableMultisampleRate = true,
836 .inheritedQueries = true,
837 };
838
839 /* We can't do image stores in vec4 shaders */
840 pFeatures->vertexPipelineStoresAndAtomics =
841 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
842 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
843 }
844
845 void anv_GetPhysicalDeviceFeatures2(
846 VkPhysicalDevice physicalDevice,
847 VkPhysicalDeviceFeatures2* pFeatures)
848 {
849 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
850
851 vk_foreach_struct(ext, pFeatures->pNext) {
852 switch (ext->sType) {
853 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
854 VkPhysicalDeviceProtectedMemoryFeatures *features = (void *)ext;
855 features->protectedMemory = VK_FALSE;
856 break;
857 }
858
859 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
860 VkPhysicalDeviceMultiviewFeatures *features =
861 (VkPhysicalDeviceMultiviewFeatures *)ext;
862 features->multiview = true;
863 features->multiviewGeometryShader = true;
864 features->multiviewTessellationShader = true;
865 break;
866 }
867
868 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES: {
869 VkPhysicalDeviceVariablePointerFeatures *features = (void *)ext;
870 features->variablePointersStorageBuffer = true;
871 features->variablePointers = true;
872 break;
873 }
874
875 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
876 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
877 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
878 features->samplerYcbcrConversion = true;
879 break;
880 }
881
882 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETER_FEATURES: {
883 VkPhysicalDeviceShaderDrawParameterFeatures *features = (void *)ext;
884 features->shaderDrawParameters = true;
885 break;
886 }
887
888 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR: {
889 VkPhysicalDevice16BitStorageFeaturesKHR *features =
890 (VkPhysicalDevice16BitStorageFeaturesKHR *)ext;
891 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
892
893 features->storageBuffer16BitAccess = pdevice->info.gen >= 8;
894 features->uniformAndStorageBuffer16BitAccess = pdevice->info.gen >= 8;
895 features->storagePushConstant16 = pdevice->info.gen >= 8;
896 features->storageInputOutput16 = false;
897 break;
898 }
899
900 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR: {
901 VkPhysicalDevice8BitStorageFeaturesKHR *features =
902 (VkPhysicalDevice8BitStorageFeaturesKHR *)ext;
903 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
904
905 features->storageBuffer8BitAccess = pdevice->info.gen >= 8;
906 features->uniformAndStorageBuffer8BitAccess = pdevice->info.gen >= 8;
907 features->storagePushConstant8 = pdevice->info.gen >= 8;
908 break;
909 }
910
911 default:
912 anv_debug_ignored_stype(ext->sType);
913 break;
914 }
915 }
916 }
917
918 void anv_GetPhysicalDeviceProperties(
919 VkPhysicalDevice physicalDevice,
920 VkPhysicalDeviceProperties* pProperties)
921 {
922 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
923 const struct gen_device_info *devinfo = &pdevice->info;
924
925 /* See assertions made when programming the buffer surface state. */
926 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
927 (1ul << 30) : (1ul << 27);
928
929 const uint32_t max_samplers = (devinfo->gen >= 8 || devinfo->is_haswell) ?
930 128 : 16;
931
932 VkSampleCountFlags sample_counts =
933 isl_device_get_sample_counts(&pdevice->isl_dev);
934
935 VkPhysicalDeviceLimits limits = {
936 .maxImageDimension1D = (1 << 14),
937 .maxImageDimension2D = (1 << 14),
938 .maxImageDimension3D = (1 << 11),
939 .maxImageDimensionCube = (1 << 14),
940 .maxImageArrayLayers = (1 << 11),
941 .maxTexelBufferElements = 128 * 1024 * 1024,
942 .maxUniformBufferRange = (1ul << 27),
943 .maxStorageBufferRange = max_raw_buffer_sz,
944 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
945 .maxMemoryAllocationCount = UINT32_MAX,
946 .maxSamplerAllocationCount = 64 * 1024,
947 .bufferImageGranularity = 64, /* A cache line */
948 .sparseAddressSpaceSize = 0,
949 .maxBoundDescriptorSets = MAX_SETS,
950 .maxPerStageDescriptorSamplers = max_samplers,
951 .maxPerStageDescriptorUniformBuffers = 64,
952 .maxPerStageDescriptorStorageBuffers = 64,
953 .maxPerStageDescriptorSampledImages = max_samplers,
954 .maxPerStageDescriptorStorageImages = 64,
955 .maxPerStageDescriptorInputAttachments = 64,
956 .maxPerStageResources = 250,
957 .maxDescriptorSetSamplers = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
958 .maxDescriptorSetUniformBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorUniformBuffers */
959 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
960 .maxDescriptorSetStorageBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorStorageBuffers */
961 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
962 .maxDescriptorSetSampledImages = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSampledImages */
963 .maxDescriptorSetStorageImages = 6 * 64, /* number of stages * maxPerStageDescriptorStorageImages */
964 .maxDescriptorSetInputAttachments = 256,
965 .maxVertexInputAttributes = MAX_VBS,
966 .maxVertexInputBindings = MAX_VBS,
967 .maxVertexInputAttributeOffset = 2047,
968 .maxVertexInputBindingStride = 2048,
969 .maxVertexOutputComponents = 128,
970 .maxTessellationGenerationLevel = 64,
971 .maxTessellationPatchSize = 32,
972 .maxTessellationControlPerVertexInputComponents = 128,
973 .maxTessellationControlPerVertexOutputComponents = 128,
974 .maxTessellationControlPerPatchOutputComponents = 128,
975 .maxTessellationControlTotalOutputComponents = 2048,
976 .maxTessellationEvaluationInputComponents = 128,
977 .maxTessellationEvaluationOutputComponents = 128,
978 .maxGeometryShaderInvocations = 32,
979 .maxGeometryInputComponents = 64,
980 .maxGeometryOutputComponents = 128,
981 .maxGeometryOutputVertices = 256,
982 .maxGeometryTotalOutputComponents = 1024,
983 .maxFragmentInputComponents = 112, /* 128 components - (POS, PSIZ, CLIP_DIST0, CLIP_DIST1) */
984 .maxFragmentOutputAttachments = 8,
985 .maxFragmentDualSrcAttachments = 1,
986 .maxFragmentCombinedOutputResources = 8,
987 .maxComputeSharedMemorySize = 32768,
988 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
989 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
990 .maxComputeWorkGroupSize = {
991 16 * devinfo->max_cs_threads,
992 16 * devinfo->max_cs_threads,
993 16 * devinfo->max_cs_threads,
994 },
995 .subPixelPrecisionBits = 4 /* FIXME */,
996 .subTexelPrecisionBits = 4 /* FIXME */,
997 .mipmapPrecisionBits = 4 /* FIXME */,
998 .maxDrawIndexedIndexValue = UINT32_MAX,
999 .maxDrawIndirectCount = UINT32_MAX,
1000 .maxSamplerLodBias = 16,
1001 .maxSamplerAnisotropy = 16,
1002 .maxViewports = MAX_VIEWPORTS,
1003 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1004 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1005 .viewportSubPixelBits = 13, /* We take a float? */
1006 .minMemoryMapAlignment = 4096, /* A page */
1007 .minTexelBufferOffsetAlignment = 1,
1008 /* We need 16 for UBO block reads to work and 32 for push UBOs */
1009 .minUniformBufferOffsetAlignment = 32,
1010 .minStorageBufferOffsetAlignment = 4,
1011 .minTexelOffset = -8,
1012 .maxTexelOffset = 7,
1013 .minTexelGatherOffset = -32,
1014 .maxTexelGatherOffset = 31,
1015 .minInterpolationOffset = -0.5,
1016 .maxInterpolationOffset = 0.4375,
1017 .subPixelInterpolationOffsetBits = 4,
1018 .maxFramebufferWidth = (1 << 14),
1019 .maxFramebufferHeight = (1 << 14),
1020 .maxFramebufferLayers = (1 << 11),
1021 .framebufferColorSampleCounts = sample_counts,
1022 .framebufferDepthSampleCounts = sample_counts,
1023 .framebufferStencilSampleCounts = sample_counts,
1024 .framebufferNoAttachmentsSampleCounts = sample_counts,
1025 .maxColorAttachments = MAX_RTS,
1026 .sampledImageColorSampleCounts = sample_counts,
1027 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1028 .sampledImageDepthSampleCounts = sample_counts,
1029 .sampledImageStencilSampleCounts = sample_counts,
1030 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1031 .maxSampleMaskWords = 1,
1032 .timestampComputeAndGraphics = false,
1033 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
1034 .maxClipDistances = 8,
1035 .maxCullDistances = 8,
1036 .maxCombinedClipAndCullDistances = 8,
1037 .discreteQueuePriorities = 1,
1038 .pointSizeRange = { 0.125, 255.875 },
1039 .lineWidthRange = { 0.0, 7.9921875 },
1040 .pointSizeGranularity = (1.0 / 8.0),
1041 .lineWidthGranularity = (1.0 / 128.0),
1042 .strictLines = false, /* FINISHME */
1043 .standardSampleLocations = true,
1044 .optimalBufferCopyOffsetAlignment = 128,
1045 .optimalBufferCopyRowPitchAlignment = 128,
1046 .nonCoherentAtomSize = 64,
1047 };
1048
1049 *pProperties = (VkPhysicalDeviceProperties) {
1050 .apiVersion = anv_physical_device_api_version(pdevice),
1051 .driverVersion = vk_get_driver_version(),
1052 .vendorID = 0x8086,
1053 .deviceID = pdevice->chipset_id,
1054 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1055 .limits = limits,
1056 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
1057 };
1058
1059 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
1060 "%s", pdevice->name);
1061 memcpy(pProperties->pipelineCacheUUID,
1062 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
1063 }
1064
1065 void anv_GetPhysicalDeviceProperties2(
1066 VkPhysicalDevice physicalDevice,
1067 VkPhysicalDeviceProperties2* pProperties)
1068 {
1069 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1070
1071 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1072
1073 vk_foreach_struct(ext, pProperties->pNext) {
1074 switch (ext->sType) {
1075 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1076 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1077 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1078
1079 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1080 break;
1081 }
1082
1083 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1084 VkPhysicalDeviceIDProperties *id_props =
1085 (VkPhysicalDeviceIDProperties *)ext;
1086 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1087 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1088 /* The LUID is for Windows. */
1089 id_props->deviceLUIDValid = false;
1090 break;
1091 }
1092
1093 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1094 VkPhysicalDeviceMaintenance3Properties *props =
1095 (VkPhysicalDeviceMaintenance3Properties *)ext;
1096 /* This value doesn't matter for us today as our per-stage
1097 * descriptors are the real limit.
1098 */
1099 props->maxPerSetDescriptors = 1024;
1100 props->maxMemoryAllocationSize = MAX_MEMORY_ALLOCATION_SIZE;
1101 break;
1102 }
1103
1104 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1105 VkPhysicalDeviceMultiviewProperties *properties =
1106 (VkPhysicalDeviceMultiviewProperties *)ext;
1107 properties->maxMultiviewViewCount = 16;
1108 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
1109 break;
1110 }
1111
1112 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1113 VkPhysicalDevicePointClippingProperties *properties =
1114 (VkPhysicalDevicePointClippingProperties *) ext;
1115 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1116 anv_finishme("Implement pop-free point clipping");
1117 break;
1118 }
1119
1120 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1121 VkPhysicalDeviceSubgroupProperties *properties = (void *)ext;
1122
1123 properties->subgroupSize = BRW_SUBGROUP_SIZE;
1124
1125 VkShaderStageFlags scalar_stages = 0;
1126 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1127 if (pdevice->compiler->scalar_stage[stage])
1128 scalar_stages |= mesa_to_vk_shader_stage(stage);
1129 }
1130 properties->supportedStages = scalar_stages;
1131
1132 properties->supportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1133 VK_SUBGROUP_FEATURE_VOTE_BIT |
1134 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1135 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1136 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1137 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
1138 VK_SUBGROUP_FEATURE_CLUSTERED_BIT |
1139 VK_SUBGROUP_FEATURE_QUAD_BIT;
1140 properties->quadOperationsInAllStages = VK_TRUE;
1141 break;
1142 }
1143
1144 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1145 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *props =
1146 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1147 /* We have to restrict this a bit for multiview */
1148 props->maxVertexAttribDivisor = UINT32_MAX / 16;
1149 break;
1150 }
1151
1152 default:
1153 anv_debug_ignored_stype(ext->sType);
1154 break;
1155 }
1156 }
1157 }
1158
1159 /* We support exactly one queue family. */
1160 static const VkQueueFamilyProperties
1161 anv_queue_family_properties = {
1162 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1163 VK_QUEUE_COMPUTE_BIT |
1164 VK_QUEUE_TRANSFER_BIT,
1165 .queueCount = 1,
1166 .timestampValidBits = 36, /* XXX: Real value here */
1167 .minImageTransferGranularity = { 1, 1, 1 },
1168 };
1169
1170 void anv_GetPhysicalDeviceQueueFamilyProperties(
1171 VkPhysicalDevice physicalDevice,
1172 uint32_t* pCount,
1173 VkQueueFamilyProperties* pQueueFamilyProperties)
1174 {
1175 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
1176
1177 vk_outarray_append(&out, p) {
1178 *p = anv_queue_family_properties;
1179 }
1180 }
1181
1182 void anv_GetPhysicalDeviceQueueFamilyProperties2(
1183 VkPhysicalDevice physicalDevice,
1184 uint32_t* pQueueFamilyPropertyCount,
1185 VkQueueFamilyProperties2* pQueueFamilyProperties)
1186 {
1187
1188 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1189
1190 vk_outarray_append(&out, p) {
1191 p->queueFamilyProperties = anv_queue_family_properties;
1192
1193 vk_foreach_struct(s, p->pNext) {
1194 anv_debug_ignored_stype(s->sType);
1195 }
1196 }
1197 }
1198
1199 void anv_GetPhysicalDeviceMemoryProperties(
1200 VkPhysicalDevice physicalDevice,
1201 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
1202 {
1203 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1204
1205 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
1206 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
1207 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
1208 .propertyFlags = physical_device->memory.types[i].propertyFlags,
1209 .heapIndex = physical_device->memory.types[i].heapIndex,
1210 };
1211 }
1212
1213 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
1214 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
1215 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
1216 .size = physical_device->memory.heaps[i].size,
1217 .flags = physical_device->memory.heaps[i].flags,
1218 };
1219 }
1220 }
1221
1222 void anv_GetPhysicalDeviceMemoryProperties2(
1223 VkPhysicalDevice physicalDevice,
1224 VkPhysicalDeviceMemoryProperties2* pMemoryProperties)
1225 {
1226 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1227 &pMemoryProperties->memoryProperties);
1228
1229 vk_foreach_struct(ext, pMemoryProperties->pNext) {
1230 switch (ext->sType) {
1231 default:
1232 anv_debug_ignored_stype(ext->sType);
1233 break;
1234 }
1235 }
1236 }
1237
1238 void
1239 anv_GetDeviceGroupPeerMemoryFeatures(
1240 VkDevice device,
1241 uint32_t heapIndex,
1242 uint32_t localDeviceIndex,
1243 uint32_t remoteDeviceIndex,
1244 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
1245 {
1246 assert(localDeviceIndex == 0 && remoteDeviceIndex == 0);
1247 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
1248 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
1249 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
1250 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
1251 }
1252
1253 PFN_vkVoidFunction anv_GetInstanceProcAddr(
1254 VkInstance _instance,
1255 const char* pName)
1256 {
1257 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1258
1259 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
1260 * when we have to return valid function pointers, NULL, or it's left
1261 * undefined. See the table for exact details.
1262 */
1263 if (pName == NULL)
1264 return NULL;
1265
1266 #define LOOKUP_ANV_ENTRYPOINT(entrypoint) \
1267 if (strcmp(pName, "vk" #entrypoint) == 0) \
1268 return (PFN_vkVoidFunction)anv_##entrypoint
1269
1270 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
1271 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceLayerProperties);
1272 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceVersion);
1273 LOOKUP_ANV_ENTRYPOINT(CreateInstance);
1274
1275 #undef LOOKUP_ANV_ENTRYPOINT
1276
1277 if (instance == NULL)
1278 return NULL;
1279
1280 int idx = anv_get_entrypoint_index(pName);
1281 if (idx < 0)
1282 return NULL;
1283
1284 return instance->dispatch.entrypoints[idx];
1285 }
1286
1287 /* With version 1+ of the loader interface the ICD should expose
1288 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
1289 */
1290 PUBLIC
1291 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1292 VkInstance instance,
1293 const char* pName);
1294
1295 PUBLIC
1296 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1297 VkInstance instance,
1298 const char* pName)
1299 {
1300 return anv_GetInstanceProcAddr(instance, pName);
1301 }
1302
1303 PFN_vkVoidFunction anv_GetDeviceProcAddr(
1304 VkDevice _device,
1305 const char* pName)
1306 {
1307 ANV_FROM_HANDLE(anv_device, device, _device);
1308
1309 if (!device || !pName)
1310 return NULL;
1311
1312 int idx = anv_get_entrypoint_index(pName);
1313 if (idx < 0)
1314 return NULL;
1315
1316 return device->dispatch.entrypoints[idx];
1317 }
1318
1319 VkResult
1320 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
1321 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
1322 const VkAllocationCallbacks* pAllocator,
1323 VkDebugReportCallbackEXT* pCallback)
1324 {
1325 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1326 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
1327 pCreateInfo, pAllocator, &instance->alloc,
1328 pCallback);
1329 }
1330
1331 void
1332 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
1333 VkDebugReportCallbackEXT _callback,
1334 const VkAllocationCallbacks* pAllocator)
1335 {
1336 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1337 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
1338 _callback, pAllocator, &instance->alloc);
1339 }
1340
1341 void
1342 anv_DebugReportMessageEXT(VkInstance _instance,
1343 VkDebugReportFlagsEXT flags,
1344 VkDebugReportObjectTypeEXT objectType,
1345 uint64_t object,
1346 size_t location,
1347 int32_t messageCode,
1348 const char* pLayerPrefix,
1349 const char* pMessage)
1350 {
1351 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1352 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
1353 object, location, messageCode, pLayerPrefix, pMessage);
1354 }
1355
1356 static void
1357 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
1358 {
1359 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1360 queue->device = device;
1361 queue->flags = 0;
1362 }
1363
1364 static void
1365 anv_queue_finish(struct anv_queue *queue)
1366 {
1367 }
1368
1369 static struct anv_state
1370 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
1371 {
1372 struct anv_state state;
1373
1374 state = anv_state_pool_alloc(pool, size, align);
1375 memcpy(state.map, p, size);
1376
1377 anv_state_flush(pool->block_pool.device, state);
1378
1379 return state;
1380 }
1381
1382 struct gen8_border_color {
1383 union {
1384 float float32[4];
1385 uint32_t uint32[4];
1386 };
1387 /* Pad out to 64 bytes */
1388 uint32_t _pad[12];
1389 };
1390
1391 static void
1392 anv_device_init_border_colors(struct anv_device *device)
1393 {
1394 static const struct gen8_border_color border_colors[] = {
1395 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1396 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1397 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1398 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1399 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1400 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1401 };
1402
1403 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1404 sizeof(border_colors), 64,
1405 border_colors);
1406 }
1407
1408 static void
1409 anv_device_init_trivial_batch(struct anv_device *device)
1410 {
1411 anv_bo_init_new(&device->trivial_batch_bo, device, 4096);
1412
1413 if (device->instance->physicalDevice.has_exec_async)
1414 device->trivial_batch_bo.flags |= EXEC_OBJECT_ASYNC;
1415
1416 if (device->instance->physicalDevice.use_softpin)
1417 device->trivial_batch_bo.flags |= EXEC_OBJECT_PINNED;
1418
1419 anv_vma_alloc(device, &device->trivial_batch_bo);
1420
1421 void *map = anv_gem_mmap(device, device->trivial_batch_bo.gem_handle,
1422 0, 4096, 0);
1423
1424 struct anv_batch batch = {
1425 .start = map,
1426 .next = map,
1427 .end = map + 4096,
1428 };
1429
1430 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1431 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1432
1433 if (!device->info.has_llc)
1434 gen_clflush_range(map, batch.next - map);
1435
1436 anv_gem_munmap(map, device->trivial_batch_bo.size);
1437 }
1438
1439 VkResult anv_EnumerateDeviceExtensionProperties(
1440 VkPhysicalDevice physicalDevice,
1441 const char* pLayerName,
1442 uint32_t* pPropertyCount,
1443 VkExtensionProperties* pProperties)
1444 {
1445 ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
1446 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1447 (void)device;
1448
1449 for (int i = 0; i < ANV_DEVICE_EXTENSION_COUNT; i++) {
1450 if (device->supported_extensions.extensions[i]) {
1451 vk_outarray_append(&out, prop) {
1452 *prop = anv_device_extensions[i];
1453 }
1454 }
1455 }
1456
1457 return vk_outarray_status(&out);
1458 }
1459
1460 static void
1461 anv_device_init_dispatch(struct anv_device *device)
1462 {
1463 const struct anv_dispatch_table *genX_table;
1464 switch (device->info.gen) {
1465 case 11:
1466 genX_table = &gen11_dispatch_table;
1467 break;
1468 case 10:
1469 genX_table = &gen10_dispatch_table;
1470 break;
1471 case 9:
1472 genX_table = &gen9_dispatch_table;
1473 break;
1474 case 8:
1475 genX_table = &gen8_dispatch_table;
1476 break;
1477 case 7:
1478 if (device->info.is_haswell)
1479 genX_table = &gen75_dispatch_table;
1480 else
1481 genX_table = &gen7_dispatch_table;
1482 break;
1483 default:
1484 unreachable("unsupported gen\n");
1485 }
1486
1487 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
1488 /* Vulkan requires that entrypoints for extensions which have not been
1489 * enabled must not be advertised.
1490 */
1491 if (!anv_entrypoint_is_enabled(i, device->instance->apiVersion,
1492 &device->instance->enabled_extensions,
1493 &device->enabled_extensions)) {
1494 device->dispatch.entrypoints[i] = NULL;
1495 } else if (genX_table->entrypoints[i]) {
1496 device->dispatch.entrypoints[i] = genX_table->entrypoints[i];
1497 } else {
1498 device->dispatch.entrypoints[i] = anv_dispatch_table.entrypoints[i];
1499 }
1500 }
1501 }
1502
1503 static int
1504 vk_priority_to_gen(int priority)
1505 {
1506 switch (priority) {
1507 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1508 return GEN_CONTEXT_LOW_PRIORITY;
1509 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1510 return GEN_CONTEXT_MEDIUM_PRIORITY;
1511 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1512 return GEN_CONTEXT_HIGH_PRIORITY;
1513 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1514 return GEN_CONTEXT_REALTIME_PRIORITY;
1515 default:
1516 unreachable("Invalid priority");
1517 }
1518 }
1519
1520 static void
1521 anv_device_init_hiz_clear_batch(struct anv_device *device)
1522 {
1523 anv_bo_init_new(&device->hiz_clear_bo, device, 4096);
1524 uint32_t *map = anv_gem_mmap(device, device->hiz_clear_bo.gem_handle,
1525 0, 4096, 0);
1526
1527 union isl_color_value hiz_clear = { .u32 = { 0, } };
1528 hiz_clear.f32[0] = ANV_HZ_FC_VAL;
1529
1530 memcpy(map, hiz_clear.u32, sizeof(hiz_clear.u32));
1531 anv_gem_munmap(map, device->hiz_clear_bo.size);
1532 }
1533
1534 VkResult anv_CreateDevice(
1535 VkPhysicalDevice physicalDevice,
1536 const VkDeviceCreateInfo* pCreateInfo,
1537 const VkAllocationCallbacks* pAllocator,
1538 VkDevice* pDevice)
1539 {
1540 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1541 VkResult result;
1542 struct anv_device *device;
1543
1544 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1545
1546 struct anv_device_extension_table enabled_extensions = { };
1547 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1548 int idx;
1549 for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
1550 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1551 anv_device_extensions[idx].extensionName) == 0)
1552 break;
1553 }
1554
1555 if (idx >= ANV_DEVICE_EXTENSION_COUNT)
1556 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1557
1558 if (!physical_device->supported_extensions.extensions[idx])
1559 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1560
1561 enabled_extensions.extensions[idx] = true;
1562 }
1563
1564 /* Check enabled features */
1565 if (pCreateInfo->pEnabledFeatures) {
1566 VkPhysicalDeviceFeatures supported_features;
1567 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1568 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1569 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1570 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1571 for (uint32_t i = 0; i < num_features; i++) {
1572 if (enabled_feature[i] && !supported_feature[i])
1573 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1574 }
1575 }
1576
1577 /* Check requested queues and fail if we are requested to create any
1578 * queues with flags we don't support.
1579 */
1580 assert(pCreateInfo->queueCreateInfoCount > 0);
1581 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1582 if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
1583 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
1584 }
1585
1586 /* Check if client specified queue priority. */
1587 const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
1588 vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
1589 DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
1590
1591 VkQueueGlobalPriorityEXT priority =
1592 queue_priority ? queue_priority->globalPriority :
1593 VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
1594
1595 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1596 sizeof(*device), 8,
1597 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1598 if (!device)
1599 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1600
1601 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1602 device->instance = physical_device->instance;
1603 device->chipset_id = physical_device->chipset_id;
1604 device->no_hw = physical_device->no_hw;
1605 device->lost = false;
1606
1607 if (pAllocator)
1608 device->alloc = *pAllocator;
1609 else
1610 device->alloc = physical_device->instance->alloc;
1611
1612 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1613 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1614 if (device->fd == -1) {
1615 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1616 goto fail_device;
1617 }
1618
1619 device->context_id = anv_gem_create_context(device);
1620 if (device->context_id == -1) {
1621 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1622 goto fail_fd;
1623 }
1624
1625 if (physical_device->use_softpin) {
1626 if (pthread_mutex_init(&device->vma_mutex, NULL) != 0) {
1627 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1628 goto fail_fd;
1629 }
1630
1631 /* keep the page with address zero out of the allocator */
1632 util_vma_heap_init(&device->vma_lo, LOW_HEAP_MIN_ADDRESS, LOW_HEAP_SIZE);
1633 device->vma_lo_available =
1634 physical_device->memory.heaps[physical_device->memory.heap_count - 1].size;
1635
1636 /* Leave the last 4GiB out of the high vma range, so that no state base
1637 * address + size can overflow 48 bits. For more information see the
1638 * comment about Wa32bitGeneralStateOffset in anv_allocator.c
1639 */
1640 util_vma_heap_init(&device->vma_hi, HIGH_HEAP_MIN_ADDRESS,
1641 HIGH_HEAP_SIZE);
1642 device->vma_hi_available = physical_device->memory.heap_count == 1 ? 0 :
1643 physical_device->memory.heaps[0].size;
1644 }
1645
1646 /* As per spec, the driver implementation may deny requests to acquire
1647 * a priority above the default priority (MEDIUM) if the caller does not
1648 * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
1649 * is returned.
1650 */
1651 if (physical_device->has_context_priority) {
1652 int err = anv_gem_set_context_param(device->fd, device->context_id,
1653 I915_CONTEXT_PARAM_PRIORITY,
1654 vk_priority_to_gen(priority));
1655 if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
1656 result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
1657 goto fail_fd;
1658 }
1659 }
1660
1661 device->info = physical_device->info;
1662 device->isl_dev = physical_device->isl_dev;
1663
1664 /* On Broadwell and later, we can use batch chaining to more efficiently
1665 * implement growing command buffers. Prior to Haswell, the kernel
1666 * command parser gets in the way and we have to fall back to growing
1667 * the batch.
1668 */
1669 device->can_chain_batches = device->info.gen >= 8;
1670
1671 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1672 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1673 device->enabled_extensions = enabled_extensions;
1674
1675 anv_device_init_dispatch(device);
1676
1677 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1678 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1679 goto fail_context_id;
1680 }
1681
1682 pthread_condattr_t condattr;
1683 if (pthread_condattr_init(&condattr) != 0) {
1684 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1685 goto fail_mutex;
1686 }
1687 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1688 pthread_condattr_destroy(&condattr);
1689 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1690 goto fail_mutex;
1691 }
1692 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1693 pthread_condattr_destroy(&condattr);
1694 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1695 goto fail_mutex;
1696 }
1697 pthread_condattr_destroy(&condattr);
1698
1699 uint64_t bo_flags =
1700 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
1701 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1702 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0) |
1703 (physical_device->use_softpin ? EXEC_OBJECT_PINNED : 0);
1704
1705 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
1706
1707 result = anv_bo_cache_init(&device->bo_cache);
1708 if (result != VK_SUCCESS)
1709 goto fail_batch_bo_pool;
1710
1711 if (!physical_device->use_softpin)
1712 bo_flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1713
1714 result = anv_state_pool_init(&device->dynamic_state_pool, device,
1715 DYNAMIC_STATE_POOL_MIN_ADDRESS,
1716 16384,
1717 bo_flags);
1718 if (result != VK_SUCCESS)
1719 goto fail_bo_cache;
1720
1721 result = anv_state_pool_init(&device->instruction_state_pool, device,
1722 INSTRUCTION_STATE_POOL_MIN_ADDRESS,
1723 16384,
1724 bo_flags);
1725 if (result != VK_SUCCESS)
1726 goto fail_dynamic_state_pool;
1727
1728 result = anv_state_pool_init(&device->surface_state_pool, device,
1729 SURFACE_STATE_POOL_MIN_ADDRESS,
1730 4096,
1731 bo_flags);
1732 if (result != VK_SUCCESS)
1733 goto fail_instruction_state_pool;
1734
1735 if (physical_device->use_softpin) {
1736 result = anv_state_pool_init(&device->binding_table_pool, device,
1737 BINDING_TABLE_POOL_MIN_ADDRESS,
1738 4096,
1739 bo_flags);
1740 if (result != VK_SUCCESS)
1741 goto fail_surface_state_pool;
1742 }
1743
1744 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1745 if (result != VK_SUCCESS)
1746 goto fail_binding_table_pool;
1747
1748 if (physical_device->use_softpin)
1749 device->workaround_bo.flags |= EXEC_OBJECT_PINNED;
1750
1751 if (!anv_vma_alloc(device, &device->workaround_bo))
1752 goto fail_workaround_bo;
1753
1754 anv_device_init_trivial_batch(device);
1755
1756 if (device->info.gen >= 10)
1757 anv_device_init_hiz_clear_batch(device);
1758
1759 anv_scratch_pool_init(device, &device->scratch_pool);
1760
1761 anv_queue_init(device, &device->queue);
1762
1763 switch (device->info.gen) {
1764 case 7:
1765 if (!device->info.is_haswell)
1766 result = gen7_init_device_state(device);
1767 else
1768 result = gen75_init_device_state(device);
1769 break;
1770 case 8:
1771 result = gen8_init_device_state(device);
1772 break;
1773 case 9:
1774 result = gen9_init_device_state(device);
1775 break;
1776 case 10:
1777 result = gen10_init_device_state(device);
1778 break;
1779 case 11:
1780 result = gen11_init_device_state(device);
1781 break;
1782 default:
1783 /* Shouldn't get here as we don't create physical devices for any other
1784 * gens. */
1785 unreachable("unhandled gen");
1786 }
1787 if (result != VK_SUCCESS)
1788 goto fail_workaround_bo;
1789
1790 anv_pipeline_cache_init(&device->default_pipeline_cache, device, true);
1791
1792 anv_device_init_blorp(device);
1793
1794 anv_device_init_border_colors(device);
1795
1796 *pDevice = anv_device_to_handle(device);
1797
1798 return VK_SUCCESS;
1799
1800 fail_workaround_bo:
1801 anv_queue_finish(&device->queue);
1802 anv_scratch_pool_finish(device, &device->scratch_pool);
1803 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1804 anv_gem_close(device, device->workaround_bo.gem_handle);
1805 fail_binding_table_pool:
1806 if (physical_device->use_softpin)
1807 anv_state_pool_finish(&device->binding_table_pool);
1808 fail_surface_state_pool:
1809 anv_state_pool_finish(&device->surface_state_pool);
1810 fail_instruction_state_pool:
1811 anv_state_pool_finish(&device->instruction_state_pool);
1812 fail_dynamic_state_pool:
1813 anv_state_pool_finish(&device->dynamic_state_pool);
1814 fail_bo_cache:
1815 anv_bo_cache_finish(&device->bo_cache);
1816 fail_batch_bo_pool:
1817 anv_bo_pool_finish(&device->batch_bo_pool);
1818 pthread_cond_destroy(&device->queue_submit);
1819 fail_mutex:
1820 pthread_mutex_destroy(&device->mutex);
1821 fail_context_id:
1822 anv_gem_destroy_context(device, device->context_id);
1823 fail_fd:
1824 close(device->fd);
1825 fail_device:
1826 vk_free(&device->alloc, device);
1827
1828 return result;
1829 }
1830
1831 void anv_DestroyDevice(
1832 VkDevice _device,
1833 const VkAllocationCallbacks* pAllocator)
1834 {
1835 ANV_FROM_HANDLE(anv_device, device, _device);
1836 struct anv_physical_device *physical_device;
1837
1838 if (!device)
1839 return;
1840
1841 physical_device = &device->instance->physicalDevice;
1842
1843 anv_device_finish_blorp(device);
1844
1845 anv_pipeline_cache_finish(&device->default_pipeline_cache);
1846
1847 anv_queue_finish(&device->queue);
1848
1849 #ifdef HAVE_VALGRIND
1850 /* We only need to free these to prevent valgrind errors. The backing
1851 * BO will go away in a couple of lines so we don't actually leak.
1852 */
1853 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1854 #endif
1855
1856 anv_scratch_pool_finish(device, &device->scratch_pool);
1857
1858 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1859 anv_vma_free(device, &device->workaround_bo);
1860 anv_gem_close(device, device->workaround_bo.gem_handle);
1861
1862 anv_vma_free(device, &device->trivial_batch_bo);
1863 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
1864 if (device->info.gen >= 10)
1865 anv_gem_close(device, device->hiz_clear_bo.gem_handle);
1866
1867 if (physical_device->use_softpin)
1868 anv_state_pool_finish(&device->binding_table_pool);
1869 anv_state_pool_finish(&device->surface_state_pool);
1870 anv_state_pool_finish(&device->instruction_state_pool);
1871 anv_state_pool_finish(&device->dynamic_state_pool);
1872
1873 anv_bo_cache_finish(&device->bo_cache);
1874
1875 anv_bo_pool_finish(&device->batch_bo_pool);
1876
1877 pthread_cond_destroy(&device->queue_submit);
1878 pthread_mutex_destroy(&device->mutex);
1879
1880 anv_gem_destroy_context(device, device->context_id);
1881
1882 close(device->fd);
1883
1884 vk_free(&device->alloc, device);
1885 }
1886
1887 VkResult anv_EnumerateInstanceLayerProperties(
1888 uint32_t* pPropertyCount,
1889 VkLayerProperties* pProperties)
1890 {
1891 if (pProperties == NULL) {
1892 *pPropertyCount = 0;
1893 return VK_SUCCESS;
1894 }
1895
1896 /* None supported at this time */
1897 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1898 }
1899
1900 VkResult anv_EnumerateDeviceLayerProperties(
1901 VkPhysicalDevice physicalDevice,
1902 uint32_t* pPropertyCount,
1903 VkLayerProperties* pProperties)
1904 {
1905 if (pProperties == NULL) {
1906 *pPropertyCount = 0;
1907 return VK_SUCCESS;
1908 }
1909
1910 /* None supported at this time */
1911 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1912 }
1913
1914 void anv_GetDeviceQueue(
1915 VkDevice _device,
1916 uint32_t queueNodeIndex,
1917 uint32_t queueIndex,
1918 VkQueue* pQueue)
1919 {
1920 ANV_FROM_HANDLE(anv_device, device, _device);
1921
1922 assert(queueIndex == 0);
1923
1924 *pQueue = anv_queue_to_handle(&device->queue);
1925 }
1926
1927 void anv_GetDeviceQueue2(
1928 VkDevice _device,
1929 const VkDeviceQueueInfo2* pQueueInfo,
1930 VkQueue* pQueue)
1931 {
1932 ANV_FROM_HANDLE(anv_device, device, _device);
1933
1934 assert(pQueueInfo->queueIndex == 0);
1935
1936 if (pQueueInfo->flags == device->queue.flags)
1937 *pQueue = anv_queue_to_handle(&device->queue);
1938 else
1939 *pQueue = NULL;
1940 }
1941
1942 VkResult
1943 anv_device_query_status(struct anv_device *device)
1944 {
1945 /* This isn't likely as most of the callers of this function already check
1946 * for it. However, it doesn't hurt to check and it potentially lets us
1947 * avoid an ioctl.
1948 */
1949 if (unlikely(device->lost))
1950 return VK_ERROR_DEVICE_LOST;
1951
1952 uint32_t active, pending;
1953 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
1954 if (ret == -1) {
1955 /* We don't know the real error. */
1956 device->lost = true;
1957 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1958 "get_reset_stats failed: %m");
1959 }
1960
1961 if (active) {
1962 device->lost = true;
1963 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1964 "GPU hung on one of our command buffers");
1965 } else if (pending) {
1966 device->lost = true;
1967 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1968 "GPU hung with commands in-flight");
1969 }
1970
1971 return VK_SUCCESS;
1972 }
1973
1974 VkResult
1975 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
1976 {
1977 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
1978 * Other usages of the BO (such as on different hardware) will not be
1979 * flagged as "busy" by this ioctl. Use with care.
1980 */
1981 int ret = anv_gem_busy(device, bo->gem_handle);
1982 if (ret == 1) {
1983 return VK_NOT_READY;
1984 } else if (ret == -1) {
1985 /* We don't know the real error. */
1986 device->lost = true;
1987 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1988 "gem wait failed: %m");
1989 }
1990
1991 /* Query for device status after the busy call. If the BO we're checking
1992 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
1993 * client because it clearly doesn't have valid data. Yes, this most
1994 * likely means an ioctl, but we just did an ioctl to query the busy status
1995 * so it's no great loss.
1996 */
1997 return anv_device_query_status(device);
1998 }
1999
2000 VkResult
2001 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
2002 int64_t timeout)
2003 {
2004 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
2005 if (ret == -1 && errno == ETIME) {
2006 return VK_TIMEOUT;
2007 } else if (ret == -1) {
2008 /* We don't know the real error. */
2009 device->lost = true;
2010 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
2011 "gem wait failed: %m");
2012 }
2013
2014 /* Query for device status after the wait. If the BO we're waiting on got
2015 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
2016 * because it clearly doesn't have valid data. Yes, this most likely means
2017 * an ioctl, but we just did an ioctl to wait so it's no great loss.
2018 */
2019 return anv_device_query_status(device);
2020 }
2021
2022 VkResult anv_DeviceWaitIdle(
2023 VkDevice _device)
2024 {
2025 ANV_FROM_HANDLE(anv_device, device, _device);
2026 if (unlikely(device->lost))
2027 return VK_ERROR_DEVICE_LOST;
2028
2029 struct anv_batch batch;
2030
2031 uint32_t cmds[8];
2032 batch.start = batch.next = cmds;
2033 batch.end = (void *) cmds + sizeof(cmds);
2034
2035 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
2036 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
2037
2038 return anv_device_submit_simple_batch(device, &batch);
2039 }
2040
2041 bool
2042 anv_vma_alloc(struct anv_device *device, struct anv_bo *bo)
2043 {
2044 if (!(bo->flags & EXEC_OBJECT_PINNED))
2045 return true;
2046
2047 pthread_mutex_lock(&device->vma_mutex);
2048
2049 bo->offset = 0;
2050
2051 if (bo->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS &&
2052 device->vma_hi_available >= bo->size) {
2053 uint64_t addr = util_vma_heap_alloc(&device->vma_hi, bo->size, 4096);
2054 if (addr) {
2055 bo->offset = gen_canonical_address(addr);
2056 assert(addr == gen_48b_address(bo->offset));
2057 device->vma_hi_available -= bo->size;
2058 }
2059 }
2060
2061 if (bo->offset == 0 && device->vma_lo_available >= bo->size) {
2062 uint64_t addr = util_vma_heap_alloc(&device->vma_lo, bo->size, 4096);
2063 if (addr) {
2064 bo->offset = gen_canonical_address(addr);
2065 assert(addr == gen_48b_address(bo->offset));
2066 device->vma_lo_available -= bo->size;
2067 }
2068 }
2069
2070 pthread_mutex_unlock(&device->vma_mutex);
2071
2072 return bo->offset != 0;
2073 }
2074
2075 void
2076 anv_vma_free(struct anv_device *device, struct anv_bo *bo)
2077 {
2078 if (!(bo->flags & EXEC_OBJECT_PINNED))
2079 return;
2080
2081 const uint64_t addr_48b = gen_48b_address(bo->offset);
2082
2083 pthread_mutex_lock(&device->vma_mutex);
2084
2085 if (addr_48b >= LOW_HEAP_MIN_ADDRESS &&
2086 addr_48b <= LOW_HEAP_MAX_ADDRESS) {
2087 util_vma_heap_free(&device->vma_lo, addr_48b, bo->size);
2088 device->vma_lo_available += bo->size;
2089 } else {
2090 assert(addr_48b >= HIGH_HEAP_MIN_ADDRESS &&
2091 addr_48b <= HIGH_HEAP_MAX_ADDRESS);
2092 util_vma_heap_free(&device->vma_hi, addr_48b, bo->size);
2093 device->vma_hi_available += bo->size;
2094 }
2095
2096 pthread_mutex_unlock(&device->vma_mutex);
2097
2098 bo->offset = 0;
2099 }
2100
2101 VkResult
2102 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
2103 {
2104 uint32_t gem_handle = anv_gem_create(device, size);
2105 if (!gem_handle)
2106 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
2107
2108 anv_bo_init(bo, gem_handle, size);
2109
2110 return VK_SUCCESS;
2111 }
2112
2113 VkResult anv_AllocateMemory(
2114 VkDevice _device,
2115 const VkMemoryAllocateInfo* pAllocateInfo,
2116 const VkAllocationCallbacks* pAllocator,
2117 VkDeviceMemory* pMem)
2118 {
2119 ANV_FROM_HANDLE(anv_device, device, _device);
2120 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2121 struct anv_device_memory *mem;
2122 VkResult result = VK_SUCCESS;
2123
2124 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
2125
2126 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
2127 assert(pAllocateInfo->allocationSize > 0);
2128
2129 if (pAllocateInfo->allocationSize > MAX_MEMORY_ALLOCATION_SIZE)
2130 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2131
2132 /* FINISHME: Fail if allocation request exceeds heap size. */
2133
2134 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
2135 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2136 if (mem == NULL)
2137 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2138
2139 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
2140 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
2141 mem->map = NULL;
2142 mem->map_size = 0;
2143
2144 uint64_t bo_flags = 0;
2145
2146 assert(mem->type->heapIndex < pdevice->memory.heap_count);
2147 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
2148 bo_flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2149
2150 const struct wsi_memory_allocate_info *wsi_info =
2151 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
2152 if (wsi_info && wsi_info->implicit_sync) {
2153 /* We need to set the WRITE flag on window system buffers so that GEM
2154 * will know we're writing to them and synchronize uses on other rings
2155 * (eg if the display server uses the blitter ring).
2156 */
2157 bo_flags |= EXEC_OBJECT_WRITE;
2158 } else if (pdevice->has_exec_async) {
2159 bo_flags |= EXEC_OBJECT_ASYNC;
2160 }
2161
2162 if (pdevice->use_softpin)
2163 bo_flags |= EXEC_OBJECT_PINNED;
2164
2165 const VkImportMemoryFdInfoKHR *fd_info =
2166 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
2167
2168 /* The Vulkan spec permits handleType to be 0, in which case the struct is
2169 * ignored.
2170 */
2171 if (fd_info && fd_info->handleType) {
2172 /* At the moment, we support only the below handle types. */
2173 assert(fd_info->handleType ==
2174 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2175 fd_info->handleType ==
2176 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2177
2178 result = anv_bo_cache_import(device, &device->bo_cache,
2179 fd_info->fd, bo_flags, &mem->bo);
2180 if (result != VK_SUCCESS)
2181 goto fail;
2182
2183 VkDeviceSize aligned_alloc_size =
2184 align_u64(pAllocateInfo->allocationSize, 4096);
2185
2186 /* For security purposes, we reject importing the bo if it's smaller
2187 * than the requested allocation size. This prevents a malicious client
2188 * from passing a buffer to a trusted client, lying about the size, and
2189 * telling the trusted client to try and texture from an image that goes
2190 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
2191 * in the trusted client. The trusted client can protect itself against
2192 * this sort of attack but only if it can trust the buffer size.
2193 */
2194 if (mem->bo->size < aligned_alloc_size) {
2195 result = vk_errorf(device->instance, device,
2196 VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR,
2197 "aligned allocationSize too large for "
2198 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR: "
2199 "%"PRIu64"B > %"PRIu64"B",
2200 aligned_alloc_size, mem->bo->size);
2201 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2202 goto fail;
2203 }
2204
2205 /* From the Vulkan spec:
2206 *
2207 * "Importing memory from a file descriptor transfers ownership of
2208 * the file descriptor from the application to the Vulkan
2209 * implementation. The application must not perform any operations on
2210 * the file descriptor after a successful import."
2211 *
2212 * If the import fails, we leave the file descriptor open.
2213 */
2214 close(fd_info->fd);
2215 } else {
2216 result = anv_bo_cache_alloc(device, &device->bo_cache,
2217 pAllocateInfo->allocationSize, bo_flags,
2218 &mem->bo);
2219 if (result != VK_SUCCESS)
2220 goto fail;
2221
2222 const VkMemoryDedicatedAllocateInfoKHR *dedicated_info =
2223 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO_KHR);
2224 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
2225 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
2226
2227 /* Some legacy (non-modifiers) consumers need the tiling to be set on
2228 * the BO. In this case, we have a dedicated allocation.
2229 */
2230 if (image->needs_set_tiling) {
2231 const uint32_t i915_tiling =
2232 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
2233 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
2234 image->planes[0].surface.isl.row_pitch,
2235 i915_tiling);
2236 if (ret) {
2237 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2238 return vk_errorf(device->instance, NULL,
2239 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2240 "failed to set BO tiling: %m");
2241 }
2242 }
2243 }
2244 }
2245
2246 *pMem = anv_device_memory_to_handle(mem);
2247
2248 return VK_SUCCESS;
2249
2250 fail:
2251 vk_free2(&device->alloc, pAllocator, mem);
2252
2253 return result;
2254 }
2255
2256 VkResult anv_GetMemoryFdKHR(
2257 VkDevice device_h,
2258 const VkMemoryGetFdInfoKHR* pGetFdInfo,
2259 int* pFd)
2260 {
2261 ANV_FROM_HANDLE(anv_device, dev, device_h);
2262 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
2263
2264 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2265
2266 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2267 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2268
2269 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
2270 }
2271
2272 VkResult anv_GetMemoryFdPropertiesKHR(
2273 VkDevice _device,
2274 VkExternalMemoryHandleTypeFlagBitsKHR handleType,
2275 int fd,
2276 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
2277 {
2278 ANV_FROM_HANDLE(anv_device, device, _device);
2279 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2280
2281 switch (handleType) {
2282 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
2283 /* dma-buf can be imported as any memory type */
2284 pMemoryFdProperties->memoryTypeBits =
2285 (1 << pdevice->memory.type_count) - 1;
2286 return VK_SUCCESS;
2287
2288 default:
2289 /* The valid usage section for this function says:
2290 *
2291 * "handleType must not be one of the handle types defined as
2292 * opaque."
2293 *
2294 * So opaque handle types fall into the default "unsupported" case.
2295 */
2296 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2297 }
2298 }
2299
2300 void anv_FreeMemory(
2301 VkDevice _device,
2302 VkDeviceMemory _mem,
2303 const VkAllocationCallbacks* pAllocator)
2304 {
2305 ANV_FROM_HANDLE(anv_device, device, _device);
2306 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
2307
2308 if (mem == NULL)
2309 return;
2310
2311 if (mem->map)
2312 anv_UnmapMemory(_device, _mem);
2313
2314 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2315
2316 vk_free2(&device->alloc, pAllocator, mem);
2317 }
2318
2319 VkResult anv_MapMemory(
2320 VkDevice _device,
2321 VkDeviceMemory _memory,
2322 VkDeviceSize offset,
2323 VkDeviceSize size,
2324 VkMemoryMapFlags flags,
2325 void** ppData)
2326 {
2327 ANV_FROM_HANDLE(anv_device, device, _device);
2328 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2329
2330 if (mem == NULL) {
2331 *ppData = NULL;
2332 return VK_SUCCESS;
2333 }
2334
2335 if (size == VK_WHOLE_SIZE)
2336 size = mem->bo->size - offset;
2337
2338 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
2339 *
2340 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
2341 * assert(size != 0);
2342 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
2343 * equal to the size of the memory minus offset
2344 */
2345 assert(size > 0);
2346 assert(offset + size <= mem->bo->size);
2347
2348 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
2349 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
2350 * at a time is valid. We could just mmap up front and return an offset
2351 * pointer here, but that may exhaust virtual memory on 32 bit
2352 * userspace. */
2353
2354 uint32_t gem_flags = 0;
2355
2356 if (!device->info.has_llc &&
2357 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
2358 gem_flags |= I915_MMAP_WC;
2359
2360 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
2361 uint64_t map_offset = offset & ~4095ull;
2362 assert(offset >= map_offset);
2363 uint64_t map_size = (offset + size) - map_offset;
2364
2365 /* Let's map whole pages */
2366 map_size = align_u64(map_size, 4096);
2367
2368 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
2369 map_offset, map_size, gem_flags);
2370 if (map == MAP_FAILED)
2371 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
2372
2373 mem->map = map;
2374 mem->map_size = map_size;
2375
2376 *ppData = mem->map + (offset - map_offset);
2377
2378 return VK_SUCCESS;
2379 }
2380
2381 void anv_UnmapMemory(
2382 VkDevice _device,
2383 VkDeviceMemory _memory)
2384 {
2385 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2386
2387 if (mem == NULL)
2388 return;
2389
2390 anv_gem_munmap(mem->map, mem->map_size);
2391
2392 mem->map = NULL;
2393 mem->map_size = 0;
2394 }
2395
2396 static void
2397 clflush_mapped_ranges(struct anv_device *device,
2398 uint32_t count,
2399 const VkMappedMemoryRange *ranges)
2400 {
2401 for (uint32_t i = 0; i < count; i++) {
2402 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
2403 if (ranges[i].offset >= mem->map_size)
2404 continue;
2405
2406 gen_clflush_range(mem->map + ranges[i].offset,
2407 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
2408 }
2409 }
2410
2411 VkResult anv_FlushMappedMemoryRanges(
2412 VkDevice _device,
2413 uint32_t memoryRangeCount,
2414 const VkMappedMemoryRange* pMemoryRanges)
2415 {
2416 ANV_FROM_HANDLE(anv_device, device, _device);
2417
2418 if (device->info.has_llc)
2419 return VK_SUCCESS;
2420
2421 /* Make sure the writes we're flushing have landed. */
2422 __builtin_ia32_mfence();
2423
2424 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2425
2426 return VK_SUCCESS;
2427 }
2428
2429 VkResult anv_InvalidateMappedMemoryRanges(
2430 VkDevice _device,
2431 uint32_t memoryRangeCount,
2432 const VkMappedMemoryRange* pMemoryRanges)
2433 {
2434 ANV_FROM_HANDLE(anv_device, device, _device);
2435
2436 if (device->info.has_llc)
2437 return VK_SUCCESS;
2438
2439 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2440
2441 /* Make sure no reads get moved up above the invalidate. */
2442 __builtin_ia32_mfence();
2443
2444 return VK_SUCCESS;
2445 }
2446
2447 void anv_GetBufferMemoryRequirements(
2448 VkDevice _device,
2449 VkBuffer _buffer,
2450 VkMemoryRequirements* pMemoryRequirements)
2451 {
2452 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2453 ANV_FROM_HANDLE(anv_device, device, _device);
2454 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2455
2456 /* The Vulkan spec (git aaed022) says:
2457 *
2458 * memoryTypeBits is a bitfield and contains one bit set for every
2459 * supported memory type for the resource. The bit `1<<i` is set if and
2460 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2461 * structure for the physical device is supported.
2462 */
2463 uint32_t memory_types = 0;
2464 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
2465 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
2466 if ((valid_usage & buffer->usage) == buffer->usage)
2467 memory_types |= (1u << i);
2468 }
2469
2470 /* Base alignment requirement of a cache line */
2471 uint32_t alignment = 16;
2472
2473 /* We need an alignment of 32 for pushing UBOs */
2474 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
2475 alignment = MAX2(alignment, 32);
2476
2477 pMemoryRequirements->size = buffer->size;
2478 pMemoryRequirements->alignment = alignment;
2479
2480 /* Storage and Uniform buffers should have their size aligned to
2481 * 32-bits to avoid boundary checks when last DWord is not complete.
2482 * This would ensure that not internal padding would be needed for
2483 * 16-bit types.
2484 */
2485 if (device->robust_buffer_access &&
2486 (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
2487 buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
2488 pMemoryRequirements->size = align_u64(buffer->size, 4);
2489
2490 pMemoryRequirements->memoryTypeBits = memory_types;
2491 }
2492
2493 void anv_GetBufferMemoryRequirements2(
2494 VkDevice _device,
2495 const VkBufferMemoryRequirementsInfo2* pInfo,
2496 VkMemoryRequirements2* pMemoryRequirements)
2497 {
2498 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
2499 &pMemoryRequirements->memoryRequirements);
2500
2501 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2502 switch (ext->sType) {
2503 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2504 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2505 requirements->prefersDedicatedAllocation = VK_FALSE;
2506 requirements->requiresDedicatedAllocation = VK_FALSE;
2507 break;
2508 }
2509
2510 default:
2511 anv_debug_ignored_stype(ext->sType);
2512 break;
2513 }
2514 }
2515 }
2516
2517 void anv_GetImageMemoryRequirements(
2518 VkDevice _device,
2519 VkImage _image,
2520 VkMemoryRequirements* pMemoryRequirements)
2521 {
2522 ANV_FROM_HANDLE(anv_image, image, _image);
2523 ANV_FROM_HANDLE(anv_device, device, _device);
2524 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2525
2526 /* The Vulkan spec (git aaed022) says:
2527 *
2528 * memoryTypeBits is a bitfield and contains one bit set for every
2529 * supported memory type for the resource. The bit `1<<i` is set if and
2530 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2531 * structure for the physical device is supported.
2532 *
2533 * All types are currently supported for images.
2534 */
2535 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
2536
2537 pMemoryRequirements->size = image->size;
2538 pMemoryRequirements->alignment = image->alignment;
2539 pMemoryRequirements->memoryTypeBits = memory_types;
2540 }
2541
2542 void anv_GetImageMemoryRequirements2(
2543 VkDevice _device,
2544 const VkImageMemoryRequirementsInfo2* pInfo,
2545 VkMemoryRequirements2* pMemoryRequirements)
2546 {
2547 ANV_FROM_HANDLE(anv_device, device, _device);
2548 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
2549
2550 anv_GetImageMemoryRequirements(_device, pInfo->image,
2551 &pMemoryRequirements->memoryRequirements);
2552
2553 vk_foreach_struct_const(ext, pInfo->pNext) {
2554 switch (ext->sType) {
2555 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
2556 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2557 const VkImagePlaneMemoryRequirementsInfoKHR *plane_reqs =
2558 (const VkImagePlaneMemoryRequirementsInfoKHR *) ext;
2559 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
2560 plane_reqs->planeAspect);
2561
2562 assert(image->planes[plane].offset == 0);
2563
2564 /* The Vulkan spec (git aaed022) says:
2565 *
2566 * memoryTypeBits is a bitfield and contains one bit set for every
2567 * supported memory type for the resource. The bit `1<<i` is set
2568 * if and only if the memory type `i` in the
2569 * VkPhysicalDeviceMemoryProperties structure for the physical
2570 * device is supported.
2571 *
2572 * All types are currently supported for images.
2573 */
2574 pMemoryRequirements->memoryRequirements.memoryTypeBits =
2575 (1ull << pdevice->memory.type_count) - 1;
2576
2577 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
2578 pMemoryRequirements->memoryRequirements.alignment =
2579 image->planes[plane].alignment;
2580 break;
2581 }
2582
2583 default:
2584 anv_debug_ignored_stype(ext->sType);
2585 break;
2586 }
2587 }
2588
2589 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2590 switch (ext->sType) {
2591 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2592 VkMemoryDedicatedRequirements *requirements = (void *)ext;
2593 if (image->needs_set_tiling) {
2594 /* If we need to set the tiling for external consumers, we need a
2595 * dedicated allocation.
2596 *
2597 * See also anv_AllocateMemory.
2598 */
2599 requirements->prefersDedicatedAllocation = VK_TRUE;
2600 requirements->requiresDedicatedAllocation = VK_TRUE;
2601 } else {
2602 requirements->prefersDedicatedAllocation = VK_FALSE;
2603 requirements->requiresDedicatedAllocation = VK_FALSE;
2604 }
2605 break;
2606 }
2607
2608 default:
2609 anv_debug_ignored_stype(ext->sType);
2610 break;
2611 }
2612 }
2613 }
2614
2615 void anv_GetImageSparseMemoryRequirements(
2616 VkDevice device,
2617 VkImage image,
2618 uint32_t* pSparseMemoryRequirementCount,
2619 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
2620 {
2621 *pSparseMemoryRequirementCount = 0;
2622 }
2623
2624 void anv_GetImageSparseMemoryRequirements2(
2625 VkDevice device,
2626 const VkImageSparseMemoryRequirementsInfo2* pInfo,
2627 uint32_t* pSparseMemoryRequirementCount,
2628 VkSparseImageMemoryRequirements2* pSparseMemoryRequirements)
2629 {
2630 *pSparseMemoryRequirementCount = 0;
2631 }
2632
2633 void anv_GetDeviceMemoryCommitment(
2634 VkDevice device,
2635 VkDeviceMemory memory,
2636 VkDeviceSize* pCommittedMemoryInBytes)
2637 {
2638 *pCommittedMemoryInBytes = 0;
2639 }
2640
2641 static void
2642 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
2643 {
2644 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
2645 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
2646
2647 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
2648
2649 if (mem) {
2650 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
2651 buffer->address = (struct anv_address) {
2652 .bo = mem->bo,
2653 .offset = pBindInfo->memoryOffset,
2654 };
2655 } else {
2656 buffer->address = ANV_NULL_ADDRESS;
2657 }
2658 }
2659
2660 VkResult anv_BindBufferMemory(
2661 VkDevice device,
2662 VkBuffer buffer,
2663 VkDeviceMemory memory,
2664 VkDeviceSize memoryOffset)
2665 {
2666 anv_bind_buffer_memory(
2667 &(VkBindBufferMemoryInfo) {
2668 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
2669 .buffer = buffer,
2670 .memory = memory,
2671 .memoryOffset = memoryOffset,
2672 });
2673
2674 return VK_SUCCESS;
2675 }
2676
2677 VkResult anv_BindBufferMemory2(
2678 VkDevice device,
2679 uint32_t bindInfoCount,
2680 const VkBindBufferMemoryInfo* pBindInfos)
2681 {
2682 for (uint32_t i = 0; i < bindInfoCount; i++)
2683 anv_bind_buffer_memory(&pBindInfos[i]);
2684
2685 return VK_SUCCESS;
2686 }
2687
2688 VkResult anv_QueueBindSparse(
2689 VkQueue _queue,
2690 uint32_t bindInfoCount,
2691 const VkBindSparseInfo* pBindInfo,
2692 VkFence fence)
2693 {
2694 ANV_FROM_HANDLE(anv_queue, queue, _queue);
2695 if (unlikely(queue->device->lost))
2696 return VK_ERROR_DEVICE_LOST;
2697
2698 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2699 }
2700
2701 // Event functions
2702
2703 VkResult anv_CreateEvent(
2704 VkDevice _device,
2705 const VkEventCreateInfo* pCreateInfo,
2706 const VkAllocationCallbacks* pAllocator,
2707 VkEvent* pEvent)
2708 {
2709 ANV_FROM_HANDLE(anv_device, device, _device);
2710 struct anv_state state;
2711 struct anv_event *event;
2712
2713 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2714
2715 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2716 sizeof(*event), 8);
2717 event = state.map;
2718 event->state = state;
2719 event->semaphore = VK_EVENT_RESET;
2720
2721 if (!device->info.has_llc) {
2722 /* Make sure the writes we're flushing have landed. */
2723 __builtin_ia32_mfence();
2724 __builtin_ia32_clflush(event);
2725 }
2726
2727 *pEvent = anv_event_to_handle(event);
2728
2729 return VK_SUCCESS;
2730 }
2731
2732 void anv_DestroyEvent(
2733 VkDevice _device,
2734 VkEvent _event,
2735 const VkAllocationCallbacks* pAllocator)
2736 {
2737 ANV_FROM_HANDLE(anv_device, device, _device);
2738 ANV_FROM_HANDLE(anv_event, event, _event);
2739
2740 if (!event)
2741 return;
2742
2743 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2744 }
2745
2746 VkResult anv_GetEventStatus(
2747 VkDevice _device,
2748 VkEvent _event)
2749 {
2750 ANV_FROM_HANDLE(anv_device, device, _device);
2751 ANV_FROM_HANDLE(anv_event, event, _event);
2752
2753 if (unlikely(device->lost))
2754 return VK_ERROR_DEVICE_LOST;
2755
2756 if (!device->info.has_llc) {
2757 /* Invalidate read cache before reading event written by GPU. */
2758 __builtin_ia32_clflush(event);
2759 __builtin_ia32_mfence();
2760
2761 }
2762
2763 return event->semaphore;
2764 }
2765
2766 VkResult anv_SetEvent(
2767 VkDevice _device,
2768 VkEvent _event)
2769 {
2770 ANV_FROM_HANDLE(anv_device, device, _device);
2771 ANV_FROM_HANDLE(anv_event, event, _event);
2772
2773 event->semaphore = VK_EVENT_SET;
2774
2775 if (!device->info.has_llc) {
2776 /* Make sure the writes we're flushing have landed. */
2777 __builtin_ia32_mfence();
2778 __builtin_ia32_clflush(event);
2779 }
2780
2781 return VK_SUCCESS;
2782 }
2783
2784 VkResult anv_ResetEvent(
2785 VkDevice _device,
2786 VkEvent _event)
2787 {
2788 ANV_FROM_HANDLE(anv_device, device, _device);
2789 ANV_FROM_HANDLE(anv_event, event, _event);
2790
2791 event->semaphore = VK_EVENT_RESET;
2792
2793 if (!device->info.has_llc) {
2794 /* Make sure the writes we're flushing have landed. */
2795 __builtin_ia32_mfence();
2796 __builtin_ia32_clflush(event);
2797 }
2798
2799 return VK_SUCCESS;
2800 }
2801
2802 // Buffer functions
2803
2804 VkResult anv_CreateBuffer(
2805 VkDevice _device,
2806 const VkBufferCreateInfo* pCreateInfo,
2807 const VkAllocationCallbacks* pAllocator,
2808 VkBuffer* pBuffer)
2809 {
2810 ANV_FROM_HANDLE(anv_device, device, _device);
2811 struct anv_buffer *buffer;
2812
2813 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2814
2815 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2816 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2817 if (buffer == NULL)
2818 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2819
2820 buffer->size = pCreateInfo->size;
2821 buffer->usage = pCreateInfo->usage;
2822 buffer->address = ANV_NULL_ADDRESS;
2823
2824 *pBuffer = anv_buffer_to_handle(buffer);
2825
2826 return VK_SUCCESS;
2827 }
2828
2829 void anv_DestroyBuffer(
2830 VkDevice _device,
2831 VkBuffer _buffer,
2832 const VkAllocationCallbacks* pAllocator)
2833 {
2834 ANV_FROM_HANDLE(anv_device, device, _device);
2835 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2836
2837 if (!buffer)
2838 return;
2839
2840 vk_free2(&device->alloc, pAllocator, buffer);
2841 }
2842
2843 void
2844 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2845 enum isl_format format,
2846 struct anv_address address,
2847 uint32_t range, uint32_t stride)
2848 {
2849 isl_buffer_fill_state(&device->isl_dev, state.map,
2850 .address = anv_address_physical(address),
2851 .mocs = device->default_mocs,
2852 .size = range,
2853 .format = format,
2854 .stride = stride);
2855
2856 anv_state_flush(device, state);
2857 }
2858
2859 void anv_DestroySampler(
2860 VkDevice _device,
2861 VkSampler _sampler,
2862 const VkAllocationCallbacks* pAllocator)
2863 {
2864 ANV_FROM_HANDLE(anv_device, device, _device);
2865 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2866
2867 if (!sampler)
2868 return;
2869
2870 vk_free2(&device->alloc, pAllocator, sampler);
2871 }
2872
2873 VkResult anv_CreateFramebuffer(
2874 VkDevice _device,
2875 const VkFramebufferCreateInfo* pCreateInfo,
2876 const VkAllocationCallbacks* pAllocator,
2877 VkFramebuffer* pFramebuffer)
2878 {
2879 ANV_FROM_HANDLE(anv_device, device, _device);
2880 struct anv_framebuffer *framebuffer;
2881
2882 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2883
2884 size_t size = sizeof(*framebuffer) +
2885 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2886 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2887 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2888 if (framebuffer == NULL)
2889 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2890
2891 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2892 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2893 VkImageView _iview = pCreateInfo->pAttachments[i];
2894 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2895 }
2896
2897 framebuffer->width = pCreateInfo->width;
2898 framebuffer->height = pCreateInfo->height;
2899 framebuffer->layers = pCreateInfo->layers;
2900
2901 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2902
2903 return VK_SUCCESS;
2904 }
2905
2906 void anv_DestroyFramebuffer(
2907 VkDevice _device,
2908 VkFramebuffer _fb,
2909 const VkAllocationCallbacks* pAllocator)
2910 {
2911 ANV_FROM_HANDLE(anv_device, device, _device);
2912 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2913
2914 if (!fb)
2915 return;
2916
2917 vk_free2(&device->alloc, pAllocator, fb);
2918 }
2919
2920 /* vk_icd.h does not declare this function, so we declare it here to
2921 * suppress Wmissing-prototypes.
2922 */
2923 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2924 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2925
2926 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2927 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2928 {
2929 /* For the full details on loader interface versioning, see
2930 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2931 * What follows is a condensed summary, to help you navigate the large and
2932 * confusing official doc.
2933 *
2934 * - Loader interface v0 is incompatible with later versions. We don't
2935 * support it.
2936 *
2937 * - In loader interface v1:
2938 * - The first ICD entrypoint called by the loader is
2939 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2940 * entrypoint.
2941 * - The ICD must statically expose no other Vulkan symbol unless it is
2942 * linked with -Bsymbolic.
2943 * - Each dispatchable Vulkan handle created by the ICD must be
2944 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2945 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2946 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2947 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2948 * such loader-managed surfaces.
2949 *
2950 * - Loader interface v2 differs from v1 in:
2951 * - The first ICD entrypoint called by the loader is
2952 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2953 * statically expose this entrypoint.
2954 *
2955 * - Loader interface v3 differs from v2 in:
2956 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2957 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2958 * because the loader no longer does so.
2959 */
2960 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2961 return VK_SUCCESS;
2962 }