anv/device: Increase the UBO alignment requirement to 32
[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/mesa-sha1.h"
39 #include "vk_util.h"
40
41 #include "genxml/gen7_pack.h"
42
43 static void
44 compiler_debug_log(void *data, const char *fmt, ...)
45 { }
46
47 static void
48 compiler_perf_log(void *data, const char *fmt, ...)
49 {
50 va_list args;
51 va_start(args, fmt);
52
53 if (unlikely(INTEL_DEBUG & DEBUG_PERF))
54 intel_logd_v(fmt, args);
55
56 va_end(args);
57 }
58
59 static VkResult
60 anv_compute_heap_size(int fd, uint64_t *heap_size)
61 {
62 uint64_t gtt_size;
63 if (anv_gem_get_context_param(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE,
64 &gtt_size) == -1) {
65 /* If, for whatever reason, we can't actually get the GTT size from the
66 * kernel (too old?) fall back to the aperture size.
67 */
68 anv_perf_warn(NULL, NULL,
69 "Failed to get I915_CONTEXT_PARAM_GTT_SIZE: %m");
70
71 if (anv_gem_get_aperture(fd, &gtt_size) == -1) {
72 return vk_errorf(NULL, NULL, VK_ERROR_INITIALIZATION_FAILED,
73 "failed to get aperture size: %m");
74 }
75 }
76
77 /* Query the total ram from the system */
78 struct sysinfo info;
79 sysinfo(&info);
80
81 uint64_t total_ram = (uint64_t)info.totalram * (uint64_t)info.mem_unit;
82
83 /* We don't want to burn too much ram with the GPU. If the user has 4GiB
84 * or less, we use at most half. If they have more than 4GiB, we use 3/4.
85 */
86 uint64_t available_ram;
87 if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
88 available_ram = total_ram / 2;
89 else
90 available_ram = total_ram * 3 / 4;
91
92 /* We also want to leave some padding for things we allocate in the driver,
93 * so don't go over 3/4 of the GTT either.
94 */
95 uint64_t available_gtt = gtt_size * 3 / 4;
96
97 *heap_size = MIN2(available_ram, available_gtt);
98
99 return VK_SUCCESS;
100 }
101
102 static VkResult
103 anv_physical_device_init_heaps(struct anv_physical_device *device, int fd)
104 {
105 /* The kernel query only tells us whether or not the kernel supports the
106 * EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and not whether or not the
107 * hardware has actual 48bit address support.
108 */
109 device->supports_48bit_addresses =
110 (device->info.gen >= 8) && anv_gem_supports_48b_addresses(fd);
111
112 uint64_t heap_size;
113 VkResult result = anv_compute_heap_size(fd, &heap_size);
114 if (result != VK_SUCCESS)
115 return result;
116
117 if (heap_size > (2ull << 30) && !device->supports_48bit_addresses) {
118 /* When running with an overridden PCI ID, we may get a GTT size from
119 * the kernel that is greater than 2 GiB but the execbuf check for 48bit
120 * address support can still fail. Just clamp the address space size to
121 * 2 GiB if we don't have 48-bit support.
122 */
123 intel_logw("%s:%d: The kernel reported a GTT size larger than 2 GiB but "
124 "not support for 48-bit addresses",
125 __FILE__, __LINE__);
126 heap_size = 2ull << 30;
127 }
128
129 if (heap_size <= 3ull * (1ull << 30)) {
130 /* In this case, everything fits nicely into the 32-bit address space,
131 * so there's no need for supporting 48bit addresses on client-allocated
132 * memory objects.
133 */
134 device->memory.heap_count = 1;
135 device->memory.heaps[0] = (struct anv_memory_heap) {
136 .size = heap_size,
137 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
138 .supports_48bit_addresses = false,
139 };
140 } else {
141 /* Not everything will fit nicely into a 32-bit address space. In this
142 * case we need a 64-bit heap. Advertise a small 32-bit heap and a
143 * larger 48-bit heap. If we're in this case, then we have a total heap
144 * size larger than 3GiB which most likely means they have 8 GiB of
145 * video memory and so carving off 1 GiB for the 32-bit heap should be
146 * reasonable.
147 */
148 const uint64_t heap_size_32bit = 1ull << 30;
149 const uint64_t heap_size_48bit = heap_size - heap_size_32bit;
150
151 assert(device->supports_48bit_addresses);
152
153 device->memory.heap_count = 2;
154 device->memory.heaps[0] = (struct anv_memory_heap) {
155 .size = heap_size_48bit,
156 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
157 .supports_48bit_addresses = true,
158 };
159 device->memory.heaps[1] = (struct anv_memory_heap) {
160 .size = heap_size_32bit,
161 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
162 .supports_48bit_addresses = false,
163 };
164 }
165
166 uint32_t type_count = 0;
167 for (uint32_t heap = 0; heap < device->memory.heap_count; heap++) {
168 uint32_t valid_buffer_usage = ~0;
169
170 /* There appears to be a hardware issue in the VF cache where it only
171 * considers the bottom 32 bits of memory addresses. If you happen to
172 * have two vertex buffers which get placed exactly 4 GiB apart and use
173 * them in back-to-back draw calls, you can get collisions. In order to
174 * solve this problem, we require vertex and index buffers be bound to
175 * memory allocated out of the 32-bit heap.
176 */
177 if (device->memory.heaps[heap].supports_48bit_addresses) {
178 valid_buffer_usage &= ~(VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
179 VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
180 }
181
182 if (device->info.has_llc) {
183 /* Big core GPUs share LLC with the CPU and thus one memory type can be
184 * both cached and coherent at the same time.
185 */
186 device->memory.types[type_count++] = (struct anv_memory_type) {
187 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
188 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
189 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
190 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
191 .heapIndex = heap,
192 .valid_buffer_usage = valid_buffer_usage,
193 };
194 } else {
195 /* The spec requires that we expose a host-visible, coherent memory
196 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
197 * to give the application a choice between cached, but not coherent and
198 * coherent but uncached (WC though).
199 */
200 device->memory.types[type_count++] = (struct anv_memory_type) {
201 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
202 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
203 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
204 .heapIndex = heap,
205 .valid_buffer_usage = valid_buffer_usage,
206 };
207 device->memory.types[type_count++] = (struct anv_memory_type) {
208 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
209 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
210 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
211 .heapIndex = heap,
212 .valid_buffer_usage = valid_buffer_usage,
213 };
214 }
215 }
216 device->memory.type_count = type_count;
217
218 return VK_SUCCESS;
219 }
220
221 static VkResult
222 anv_physical_device_init_uuids(struct anv_physical_device *device)
223 {
224 const struct build_id_note *note =
225 build_id_find_nhdr_for_addr(anv_physical_device_init_uuids);
226 if (!note) {
227 return vk_errorf(device->instance, device,
228 VK_ERROR_INITIALIZATION_FAILED,
229 "Failed to find build-id");
230 }
231
232 unsigned build_id_len = build_id_length(note);
233 if (build_id_len < 20) {
234 return vk_errorf(device->instance, device,
235 VK_ERROR_INITIALIZATION_FAILED,
236 "build-id too short. It needs to be a SHA");
237 }
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 VkResult
278 anv_physical_device_init(struct anv_physical_device *device,
279 struct anv_instance *instance,
280 const char *path)
281 {
282 VkResult result;
283 int fd;
284
285 brw_process_intel_debug_variable();
286
287 fd = open(path, O_RDWR | O_CLOEXEC);
288 if (fd < 0)
289 return vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
290
291 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
292 device->instance = instance;
293
294 assert(strlen(path) < ARRAY_SIZE(device->path));
295 strncpy(device->path, path, ARRAY_SIZE(device->path));
296
297 device->chipset_id = anv_gem_get_param(fd, I915_PARAM_CHIPSET_ID);
298 if (!device->chipset_id) {
299 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
300 goto fail;
301 }
302
303 device->name = gen_get_device_name(device->chipset_id);
304 if (!gen_get_device_info(device->chipset_id, &device->info)) {
305 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
306 goto fail;
307 }
308
309 if (device->info.is_haswell) {
310 intel_logw("Haswell Vulkan support is incomplete");
311 } else if (device->info.gen == 7 && !device->info.is_baytrail) {
312 intel_logw("Ivy Bridge Vulkan support is incomplete");
313 } else if (device->info.gen == 7 && device->info.is_baytrail) {
314 intel_logw("Bay Trail Vulkan support is incomplete");
315 } else if (device->info.gen >= 8 && device->info.gen <= 9) {
316 /* Broadwell, Cherryview, Skylake, Broxton, Kabylake, Coffelake is as
317 * fully supported as anything */
318 } else if (device->info.gen == 10) {
319 intel_logw("Cannonlake Vulkan support is alpha");
320 } else {
321 result = vk_errorf(device->instance, device,
322 VK_ERROR_INCOMPATIBLE_DRIVER,
323 "Vulkan not yet supported on %s", device->name);
324 goto fail;
325 }
326
327 device->cmd_parser_version = -1;
328 if (device->info.gen == 7) {
329 device->cmd_parser_version =
330 anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
331 if (device->cmd_parser_version == -1) {
332 result = vk_errorf(device->instance, device,
333 VK_ERROR_INITIALIZATION_FAILED,
334 "failed to get command parser version");
335 goto fail;
336 }
337 }
338
339 if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
340 result = vk_errorf(device->instance, device,
341 VK_ERROR_INITIALIZATION_FAILED,
342 "kernel missing gem wait");
343 goto fail;
344 }
345
346 if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
347 result = vk_errorf(device->instance, device,
348 VK_ERROR_INITIALIZATION_FAILED,
349 "kernel missing execbuf2");
350 goto fail;
351 }
352
353 if (!device->info.has_llc &&
354 anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
355 result = vk_errorf(device->instance, device,
356 VK_ERROR_INITIALIZATION_FAILED,
357 "kernel missing wc mmap");
358 goto fail;
359 }
360
361 result = anv_physical_device_init_heaps(device, fd);
362 if (result != VK_SUCCESS)
363 goto fail;
364
365 device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
366 device->has_exec_capture = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_CAPTURE);
367 device->has_exec_fence = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE);
368 device->has_syncobj = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE_ARRAY);
369 device->has_syncobj_wait = device->has_syncobj &&
370 anv_gem_supports_syncobj_wait(fd);
371
372 bool swizzled = anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
373
374 /* Starting with Gen10, the timestamp frequency of the command streamer may
375 * vary from one part to another. We can query the value from the kernel.
376 */
377 if (device->info.gen >= 10) {
378 int timestamp_frequency =
379 anv_gem_get_param(fd, I915_PARAM_CS_TIMESTAMP_FREQUENCY);
380
381 if (timestamp_frequency < 0)
382 intel_logw("Kernel 4.16-rc1+ required to properly query CS timestamp frequency");
383 else
384 device->info.timestamp_frequency = timestamp_frequency;
385 }
386
387 /* GENs prior to 8 do not support EU/Subslice info */
388 if (device->info.gen >= 8) {
389 device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
390 device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
391
392 /* Without this information, we cannot get the right Braswell
393 * brandstrings, and we have to use conservative numbers for GPGPU on
394 * many platforms, but otherwise, things will just work.
395 */
396 if (device->subslice_total < 1 || device->eu_total < 1) {
397 intel_logw("Kernel 4.1 required to properly query GPU properties");
398 }
399 } else if (device->info.gen == 7) {
400 device->subslice_total = 1 << (device->info.gt - 1);
401 }
402
403 if (device->info.is_cherryview &&
404 device->subslice_total > 0 && device->eu_total > 0) {
405 /* Logical CS threads = EUs per subslice * num threads per EU */
406 uint32_t max_cs_threads =
407 device->eu_total / device->subslice_total * device->info.num_thread_per_eu;
408
409 /* Fuse configurations may give more threads than expected, never less. */
410 if (max_cs_threads > device->info.max_cs_threads)
411 device->info.max_cs_threads = max_cs_threads;
412 }
413
414 device->compiler = brw_compiler_create(NULL, &device->info);
415 if (device->compiler == NULL) {
416 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
417 goto fail;
418 }
419 device->compiler->shader_debug_log = compiler_debug_log;
420 device->compiler->shader_perf_log = compiler_perf_log;
421 device->compiler->supports_pull_constants = false;
422
423 isl_device_init(&device->isl_dev, &device->info, swizzled);
424
425 result = anv_physical_device_init_uuids(device);
426 if (result != VK_SUCCESS)
427 goto fail;
428
429 result = anv_init_wsi(device);
430 if (result != VK_SUCCESS) {
431 ralloc_free(device->compiler);
432 goto fail;
433 }
434
435 device->local_fd = fd;
436 return VK_SUCCESS;
437
438 fail:
439 close(fd);
440 return result;
441 }
442
443 static void
444 anv_physical_device_finish(struct anv_physical_device *device)
445 {
446 anv_finish_wsi(device);
447 ralloc_free(device->compiler);
448 close(device->local_fd);
449 }
450
451 static void *
452 default_alloc_func(void *pUserData, size_t size, size_t align,
453 VkSystemAllocationScope allocationScope)
454 {
455 return malloc(size);
456 }
457
458 static void *
459 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
460 size_t align, VkSystemAllocationScope allocationScope)
461 {
462 return realloc(pOriginal, size);
463 }
464
465 static void
466 default_free_func(void *pUserData, void *pMemory)
467 {
468 free(pMemory);
469 }
470
471 static const VkAllocationCallbacks default_alloc = {
472 .pUserData = NULL,
473 .pfnAllocation = default_alloc_func,
474 .pfnReallocation = default_realloc_func,
475 .pfnFree = default_free_func,
476 };
477
478 VkResult anv_CreateInstance(
479 const VkInstanceCreateInfo* pCreateInfo,
480 const VkAllocationCallbacks* pAllocator,
481 VkInstance* pInstance)
482 {
483 struct anv_instance *instance;
484
485 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
486
487 /* Check if user passed a debug report callback to be used during
488 * Create/Destroy of instance.
489 */
490 const VkDebugReportCallbackCreateInfoEXT *ctor_cb =
491 vk_find_struct_const(pCreateInfo->pNext,
492 DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT);
493
494 uint32_t client_version;
495 if (pCreateInfo->pApplicationInfo &&
496 pCreateInfo->pApplicationInfo->apiVersion != 0) {
497 client_version = pCreateInfo->pApplicationInfo->apiVersion;
498 } else {
499 client_version = VK_MAKE_VERSION(1, 0, 0);
500 }
501
502 if (VK_MAKE_VERSION(1, 0, 0) > client_version ||
503 client_version > VK_MAKE_VERSION(1, 0, 0xfff)) {
504
505 if (ctor_cb && ctor_cb->flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
506 ctor_cb->pfnCallback(VK_DEBUG_REPORT_ERROR_BIT_EXT,
507 VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT,
508 VK_NULL_HANDLE, /* No handle available yet. */
509 __LINE__,
510 0,
511 "anv",
512 "incompatible driver version",
513 ctor_cb->pUserData);
514
515 return vk_errorf(NULL, NULL, VK_ERROR_INCOMPATIBLE_DRIVER,
516 "Client requested version %d.%d.%d",
517 VK_VERSION_MAJOR(client_version),
518 VK_VERSION_MINOR(client_version),
519 VK_VERSION_PATCH(client_version));
520 }
521
522 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
523 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
524 if (!anv_instance_extension_supported(ext_name))
525 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
526 }
527
528 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
529 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
530 if (!instance)
531 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
532
533 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
534
535 if (pAllocator)
536 instance->alloc = *pAllocator;
537 else
538 instance->alloc = default_alloc;
539
540 instance->apiVersion = client_version;
541 instance->physicalDeviceCount = -1;
542
543 if (pthread_mutex_init(&instance->callbacks_mutex, NULL) != 0) {
544 vk_free2(&default_alloc, pAllocator, instance);
545 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
546 }
547
548 list_inithead(&instance->callbacks);
549
550 /* Store report debug callback to be used during DestroyInstance. */
551 if (ctor_cb) {
552 instance->destroy_debug_cb.flags = ctor_cb->flags;
553 instance->destroy_debug_cb.callback = ctor_cb->pfnCallback;
554 instance->destroy_debug_cb.data = ctor_cb->pUserData;
555 }
556
557 _mesa_locale_init();
558
559 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
560
561 *pInstance = anv_instance_to_handle(instance);
562
563 return VK_SUCCESS;
564 }
565
566 void anv_DestroyInstance(
567 VkInstance _instance,
568 const VkAllocationCallbacks* pAllocator)
569 {
570 ANV_FROM_HANDLE(anv_instance, instance, _instance);
571
572 if (!instance)
573 return;
574
575 if (instance->physicalDeviceCount > 0) {
576 /* We support at most one physical device. */
577 assert(instance->physicalDeviceCount == 1);
578 anv_physical_device_finish(&instance->physicalDevice);
579 }
580
581 VG(VALGRIND_DESTROY_MEMPOOL(instance));
582
583 pthread_mutex_destroy(&instance->callbacks_mutex);
584
585 _mesa_locale_fini();
586
587 vk_free(&instance->alloc, instance);
588 }
589
590 static VkResult
591 anv_enumerate_devices(struct anv_instance *instance)
592 {
593 /* TODO: Check for more devices ? */
594 drmDevicePtr devices[8];
595 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
596 int max_devices;
597
598 instance->physicalDeviceCount = 0;
599
600 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
601 if (max_devices < 1)
602 return VK_ERROR_INCOMPATIBLE_DRIVER;
603
604 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
605 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
606 devices[i]->bustype == DRM_BUS_PCI &&
607 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
608
609 result = anv_physical_device_init(&instance->physicalDevice,
610 instance,
611 devices[i]->nodes[DRM_NODE_RENDER]);
612 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
613 break;
614 }
615 }
616 drmFreeDevices(devices, max_devices);
617
618 if (result == VK_SUCCESS)
619 instance->physicalDeviceCount = 1;
620
621 return result;
622 }
623
624
625 VkResult anv_EnumeratePhysicalDevices(
626 VkInstance _instance,
627 uint32_t* pPhysicalDeviceCount,
628 VkPhysicalDevice* pPhysicalDevices)
629 {
630 ANV_FROM_HANDLE(anv_instance, instance, _instance);
631 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
632 VkResult result;
633
634 if (instance->physicalDeviceCount < 0) {
635 result = anv_enumerate_devices(instance);
636 if (result != VK_SUCCESS &&
637 result != VK_ERROR_INCOMPATIBLE_DRIVER)
638 return result;
639 }
640
641 if (instance->physicalDeviceCount > 0) {
642 assert(instance->physicalDeviceCount == 1);
643 vk_outarray_append(&out, i) {
644 *i = anv_physical_device_to_handle(&instance->physicalDevice);
645 }
646 }
647
648 return vk_outarray_status(&out);
649 }
650
651 void anv_GetPhysicalDeviceFeatures(
652 VkPhysicalDevice physicalDevice,
653 VkPhysicalDeviceFeatures* pFeatures)
654 {
655 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
656
657 *pFeatures = (VkPhysicalDeviceFeatures) {
658 .robustBufferAccess = true,
659 .fullDrawIndexUint32 = true,
660 .imageCubeArray = true,
661 .independentBlend = true,
662 .geometryShader = true,
663 .tessellationShader = true,
664 .sampleRateShading = true,
665 .dualSrcBlend = true,
666 .logicOp = true,
667 .multiDrawIndirect = true,
668 .drawIndirectFirstInstance = true,
669 .depthClamp = true,
670 .depthBiasClamp = true,
671 .fillModeNonSolid = true,
672 .depthBounds = false,
673 .wideLines = true,
674 .largePoints = true,
675 .alphaToOne = true,
676 .multiViewport = true,
677 .samplerAnisotropy = true,
678 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
679 pdevice->info.is_baytrail,
680 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
681 .textureCompressionBC = true,
682 .occlusionQueryPrecise = true,
683 .pipelineStatisticsQuery = true,
684 .fragmentStoresAndAtomics = true,
685 .shaderTessellationAndGeometryPointSize = true,
686 .shaderImageGatherExtended = true,
687 .shaderStorageImageExtendedFormats = true,
688 .shaderStorageImageMultisample = false,
689 .shaderStorageImageReadWithoutFormat = false,
690 .shaderStorageImageWriteWithoutFormat = true,
691 .shaderUniformBufferArrayDynamicIndexing = true,
692 .shaderSampledImageArrayDynamicIndexing = true,
693 .shaderStorageBufferArrayDynamicIndexing = true,
694 .shaderStorageImageArrayDynamicIndexing = true,
695 .shaderClipDistance = true,
696 .shaderCullDistance = true,
697 .shaderFloat64 = pdevice->info.gen >= 8,
698 .shaderInt64 = pdevice->info.gen >= 8,
699 .shaderInt16 = false,
700 .shaderResourceMinLod = false,
701 .variableMultisampleRate = false,
702 .inheritedQueries = true,
703 };
704
705 /* We can't do image stores in vec4 shaders */
706 pFeatures->vertexPipelineStoresAndAtomics =
707 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
708 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
709 }
710
711 void anv_GetPhysicalDeviceFeatures2KHR(
712 VkPhysicalDevice physicalDevice,
713 VkPhysicalDeviceFeatures2KHR* pFeatures)
714 {
715 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
716
717 vk_foreach_struct(ext, pFeatures->pNext) {
718 switch (ext->sType) {
719 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHX: {
720 VkPhysicalDeviceMultiviewFeaturesKHX *features =
721 (VkPhysicalDeviceMultiviewFeaturesKHX *)ext;
722 features->multiview = true;
723 features->multiviewGeometryShader = true;
724 features->multiviewTessellationShader = true;
725 break;
726 }
727
728 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR: {
729 VkPhysicalDeviceVariablePointerFeaturesKHR *features = (void *)ext;
730 features->variablePointersStorageBuffer = true;
731 features->variablePointers = true;
732 break;
733 }
734
735 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR: {
736 VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR *features =
737 (VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR *) ext;
738 features->samplerYcbcrConversion = true;
739 break;
740 }
741
742 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR: {
743 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
744
745 VkPhysicalDevice16BitStorageFeaturesKHR *features =
746 (VkPhysicalDevice16BitStorageFeaturesKHR *)ext;
747
748 features->storageBuffer16BitAccess = false;
749 features->uniformAndStorageBuffer16BitAccess = false;
750 features->storagePushConstant16 = false;
751 features->storageInputOutput16 = false;
752 break;
753 }
754
755 default:
756 anv_debug_ignored_stype(ext->sType);
757 break;
758 }
759 }
760 }
761
762 void anv_GetPhysicalDeviceProperties(
763 VkPhysicalDevice physicalDevice,
764 VkPhysicalDeviceProperties* pProperties)
765 {
766 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
767 const struct gen_device_info *devinfo = &pdevice->info;
768
769 /* See assertions made when programming the buffer surface state. */
770 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
771 (1ul << 30) : (1ul << 27);
772
773 const uint32_t max_samplers = (devinfo->gen >= 8 || devinfo->is_haswell) ?
774 128 : 16;
775
776 VkSampleCountFlags sample_counts =
777 isl_device_get_sample_counts(&pdevice->isl_dev);
778
779 VkPhysicalDeviceLimits limits = {
780 .maxImageDimension1D = (1 << 14),
781 .maxImageDimension2D = (1 << 14),
782 .maxImageDimension3D = (1 << 11),
783 .maxImageDimensionCube = (1 << 14),
784 .maxImageArrayLayers = (1 << 11),
785 .maxTexelBufferElements = 128 * 1024 * 1024,
786 .maxUniformBufferRange = (1ul << 27),
787 .maxStorageBufferRange = max_raw_buffer_sz,
788 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
789 .maxMemoryAllocationCount = UINT32_MAX,
790 .maxSamplerAllocationCount = 64 * 1024,
791 .bufferImageGranularity = 64, /* A cache line */
792 .sparseAddressSpaceSize = 0,
793 .maxBoundDescriptorSets = MAX_SETS,
794 .maxPerStageDescriptorSamplers = max_samplers,
795 .maxPerStageDescriptorUniformBuffers = 64,
796 .maxPerStageDescriptorStorageBuffers = 64,
797 .maxPerStageDescriptorSampledImages = max_samplers,
798 .maxPerStageDescriptorStorageImages = 64,
799 .maxPerStageDescriptorInputAttachments = 64,
800 .maxPerStageResources = 250,
801 .maxDescriptorSetSamplers = 256,
802 .maxDescriptorSetUniformBuffers = 256,
803 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
804 .maxDescriptorSetStorageBuffers = 256,
805 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
806 .maxDescriptorSetSampledImages = 256,
807 .maxDescriptorSetStorageImages = 256,
808 .maxDescriptorSetInputAttachments = 256,
809 .maxVertexInputAttributes = MAX_VBS,
810 .maxVertexInputBindings = MAX_VBS,
811 .maxVertexInputAttributeOffset = 2047,
812 .maxVertexInputBindingStride = 2048,
813 .maxVertexOutputComponents = 128,
814 .maxTessellationGenerationLevel = 64,
815 .maxTessellationPatchSize = 32,
816 .maxTessellationControlPerVertexInputComponents = 128,
817 .maxTessellationControlPerVertexOutputComponents = 128,
818 .maxTessellationControlPerPatchOutputComponents = 128,
819 .maxTessellationControlTotalOutputComponents = 2048,
820 .maxTessellationEvaluationInputComponents = 128,
821 .maxTessellationEvaluationOutputComponents = 128,
822 .maxGeometryShaderInvocations = 32,
823 .maxGeometryInputComponents = 64,
824 .maxGeometryOutputComponents = 128,
825 .maxGeometryOutputVertices = 256,
826 .maxGeometryTotalOutputComponents = 1024,
827 .maxFragmentInputComponents = 128,
828 .maxFragmentOutputAttachments = 8,
829 .maxFragmentDualSrcAttachments = 1,
830 .maxFragmentCombinedOutputResources = 8,
831 .maxComputeSharedMemorySize = 32768,
832 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
833 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
834 .maxComputeWorkGroupSize = {
835 16 * devinfo->max_cs_threads,
836 16 * devinfo->max_cs_threads,
837 16 * devinfo->max_cs_threads,
838 },
839 .subPixelPrecisionBits = 4 /* FIXME */,
840 .subTexelPrecisionBits = 4 /* FIXME */,
841 .mipmapPrecisionBits = 4 /* FIXME */,
842 .maxDrawIndexedIndexValue = UINT32_MAX,
843 .maxDrawIndirectCount = UINT32_MAX,
844 .maxSamplerLodBias = 16,
845 .maxSamplerAnisotropy = 16,
846 .maxViewports = MAX_VIEWPORTS,
847 .maxViewportDimensions = { (1 << 14), (1 << 14) },
848 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
849 .viewportSubPixelBits = 13, /* We take a float? */
850 .minMemoryMapAlignment = 4096, /* A page */
851 .minTexelBufferOffsetAlignment = 1,
852 /* We need 16 for UBO block reads to work and 32 for push UBOs */
853 .minUniformBufferOffsetAlignment = 32,
854 .minStorageBufferOffsetAlignment = 4,
855 .minTexelOffset = -8,
856 .maxTexelOffset = 7,
857 .minTexelGatherOffset = -32,
858 .maxTexelGatherOffset = 31,
859 .minInterpolationOffset = -0.5,
860 .maxInterpolationOffset = 0.4375,
861 .subPixelInterpolationOffsetBits = 4,
862 .maxFramebufferWidth = (1 << 14),
863 .maxFramebufferHeight = (1 << 14),
864 .maxFramebufferLayers = (1 << 11),
865 .framebufferColorSampleCounts = sample_counts,
866 .framebufferDepthSampleCounts = sample_counts,
867 .framebufferStencilSampleCounts = sample_counts,
868 .framebufferNoAttachmentsSampleCounts = sample_counts,
869 .maxColorAttachments = MAX_RTS,
870 .sampledImageColorSampleCounts = sample_counts,
871 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
872 .sampledImageDepthSampleCounts = sample_counts,
873 .sampledImageStencilSampleCounts = sample_counts,
874 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
875 .maxSampleMaskWords = 1,
876 .timestampComputeAndGraphics = false,
877 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
878 .maxClipDistances = 8,
879 .maxCullDistances = 8,
880 .maxCombinedClipAndCullDistances = 8,
881 .discreteQueuePriorities = 1,
882 .pointSizeRange = { 0.125, 255.875 },
883 .lineWidthRange = { 0.0, 7.9921875 },
884 .pointSizeGranularity = (1.0 / 8.0),
885 .lineWidthGranularity = (1.0 / 128.0),
886 .strictLines = false, /* FINISHME */
887 .standardSampleLocations = true,
888 .optimalBufferCopyOffsetAlignment = 128,
889 .optimalBufferCopyRowPitchAlignment = 128,
890 .nonCoherentAtomSize = 64,
891 };
892
893 *pProperties = (VkPhysicalDeviceProperties) {
894 .apiVersion = anv_physical_device_api_version(pdevice),
895 .driverVersion = vk_get_driver_version(),
896 .vendorID = 0x8086,
897 .deviceID = pdevice->chipset_id,
898 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
899 .limits = limits,
900 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
901 };
902
903 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
904 "%s", pdevice->name);
905 memcpy(pProperties->pipelineCacheUUID,
906 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
907 }
908
909 void anv_GetPhysicalDeviceProperties2KHR(
910 VkPhysicalDevice physicalDevice,
911 VkPhysicalDeviceProperties2KHR* pProperties)
912 {
913 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
914
915 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
916
917 vk_foreach_struct(ext, pProperties->pNext) {
918 switch (ext->sType) {
919 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
920 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
921 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
922
923 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
924 break;
925 }
926
927 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR: {
928 VkPhysicalDeviceIDPropertiesKHR *id_props =
929 (VkPhysicalDeviceIDPropertiesKHR *)ext;
930 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
931 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
932 /* The LUID is for Windows. */
933 id_props->deviceLUIDValid = false;
934 break;
935 }
936
937 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHX: {
938 VkPhysicalDeviceMultiviewPropertiesKHX *properties =
939 (VkPhysicalDeviceMultiviewPropertiesKHX *)ext;
940 properties->maxMultiviewViewCount = 16;
941 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
942 break;
943 }
944
945 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES_KHR: {
946 VkPhysicalDevicePointClippingPropertiesKHR *properties =
947 (VkPhysicalDevicePointClippingPropertiesKHR *) ext;
948 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES_KHR;
949 anv_finishme("Implement pop-free point clipping");
950 break;
951 }
952
953 default:
954 anv_debug_ignored_stype(ext->sType);
955 break;
956 }
957 }
958 }
959
960 /* We support exactly one queue family. */
961 static const VkQueueFamilyProperties
962 anv_queue_family_properties = {
963 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
964 VK_QUEUE_COMPUTE_BIT |
965 VK_QUEUE_TRANSFER_BIT,
966 .queueCount = 1,
967 .timestampValidBits = 36, /* XXX: Real value here */
968 .minImageTransferGranularity = { 1, 1, 1 },
969 };
970
971 void anv_GetPhysicalDeviceQueueFamilyProperties(
972 VkPhysicalDevice physicalDevice,
973 uint32_t* pCount,
974 VkQueueFamilyProperties* pQueueFamilyProperties)
975 {
976 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
977
978 vk_outarray_append(&out, p) {
979 *p = anv_queue_family_properties;
980 }
981 }
982
983 void anv_GetPhysicalDeviceQueueFamilyProperties2KHR(
984 VkPhysicalDevice physicalDevice,
985 uint32_t* pQueueFamilyPropertyCount,
986 VkQueueFamilyProperties2KHR* pQueueFamilyProperties)
987 {
988
989 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
990
991 vk_outarray_append(&out, p) {
992 p->queueFamilyProperties = anv_queue_family_properties;
993
994 vk_foreach_struct(s, p->pNext) {
995 anv_debug_ignored_stype(s->sType);
996 }
997 }
998 }
999
1000 void anv_GetPhysicalDeviceMemoryProperties(
1001 VkPhysicalDevice physicalDevice,
1002 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
1003 {
1004 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1005
1006 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
1007 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
1008 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
1009 .propertyFlags = physical_device->memory.types[i].propertyFlags,
1010 .heapIndex = physical_device->memory.types[i].heapIndex,
1011 };
1012 }
1013
1014 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
1015 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
1016 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
1017 .size = physical_device->memory.heaps[i].size,
1018 .flags = physical_device->memory.heaps[i].flags,
1019 };
1020 }
1021 }
1022
1023 void anv_GetPhysicalDeviceMemoryProperties2KHR(
1024 VkPhysicalDevice physicalDevice,
1025 VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties)
1026 {
1027 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1028 &pMemoryProperties->memoryProperties);
1029
1030 vk_foreach_struct(ext, pMemoryProperties->pNext) {
1031 switch (ext->sType) {
1032 default:
1033 anv_debug_ignored_stype(ext->sType);
1034 break;
1035 }
1036 }
1037 }
1038
1039 PFN_vkVoidFunction anv_GetInstanceProcAddr(
1040 VkInstance instance,
1041 const char* pName)
1042 {
1043 return anv_lookup_entrypoint(NULL, pName);
1044 }
1045
1046 /* With version 1+ of the loader interface the ICD should expose
1047 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
1048 */
1049 PUBLIC
1050 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1051 VkInstance instance,
1052 const char* pName);
1053
1054 PUBLIC
1055 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1056 VkInstance instance,
1057 const char* pName)
1058 {
1059 return anv_GetInstanceProcAddr(instance, pName);
1060 }
1061
1062 PFN_vkVoidFunction anv_GetDeviceProcAddr(
1063 VkDevice _device,
1064 const char* pName)
1065 {
1066 ANV_FROM_HANDLE(anv_device, device, _device);
1067 return anv_lookup_entrypoint(&device->info, pName);
1068 }
1069
1070 static void
1071 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
1072 {
1073 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1074 queue->device = device;
1075 queue->pool = &device->surface_state_pool;
1076 }
1077
1078 static void
1079 anv_queue_finish(struct anv_queue *queue)
1080 {
1081 }
1082
1083 static struct anv_state
1084 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
1085 {
1086 struct anv_state state;
1087
1088 state = anv_state_pool_alloc(pool, size, align);
1089 memcpy(state.map, p, size);
1090
1091 anv_state_flush(pool->block_pool.device, state);
1092
1093 return state;
1094 }
1095
1096 struct gen8_border_color {
1097 union {
1098 float float32[4];
1099 uint32_t uint32[4];
1100 };
1101 /* Pad out to 64 bytes */
1102 uint32_t _pad[12];
1103 };
1104
1105 static void
1106 anv_device_init_border_colors(struct anv_device *device)
1107 {
1108 static const struct gen8_border_color border_colors[] = {
1109 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1110 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1111 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1112 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1113 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1114 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1115 };
1116
1117 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1118 sizeof(border_colors), 64,
1119 border_colors);
1120 }
1121
1122 static void
1123 anv_device_init_trivial_batch(struct anv_device *device)
1124 {
1125 anv_bo_init_new(&device->trivial_batch_bo, device, 4096);
1126
1127 if (device->instance->physicalDevice.has_exec_async)
1128 device->trivial_batch_bo.flags |= EXEC_OBJECT_ASYNC;
1129
1130 void *map = anv_gem_mmap(device, device->trivial_batch_bo.gem_handle,
1131 0, 4096, 0);
1132
1133 struct anv_batch batch = {
1134 .start = map,
1135 .next = map,
1136 .end = map + 4096,
1137 };
1138
1139 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1140 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1141
1142 if (!device->info.has_llc)
1143 gen_clflush_range(map, batch.next - map);
1144
1145 anv_gem_munmap(map, device->trivial_batch_bo.size);
1146 }
1147
1148 VkResult anv_CreateDevice(
1149 VkPhysicalDevice physicalDevice,
1150 const VkDeviceCreateInfo* pCreateInfo,
1151 const VkAllocationCallbacks* pAllocator,
1152 VkDevice* pDevice)
1153 {
1154 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1155 VkResult result;
1156 struct anv_device *device;
1157
1158 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1159
1160 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1161 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
1162 if (!anv_physical_device_extension_supported(physical_device, ext_name))
1163 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1164 }
1165
1166 /* Check enabled features */
1167 if (pCreateInfo->pEnabledFeatures) {
1168 VkPhysicalDeviceFeatures supported_features;
1169 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1170 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1171 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1172 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1173 for (uint32_t i = 0; i < num_features; i++) {
1174 if (enabled_feature[i] && !supported_feature[i])
1175 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1176 }
1177 }
1178
1179 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1180 sizeof(*device), 8,
1181 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1182 if (!device)
1183 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1184
1185 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1186 device->instance = physical_device->instance;
1187 device->chipset_id = physical_device->chipset_id;
1188 device->lost = false;
1189
1190 if (pAllocator)
1191 device->alloc = *pAllocator;
1192 else
1193 device->alloc = physical_device->instance->alloc;
1194
1195 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1196 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1197 if (device->fd == -1) {
1198 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1199 goto fail_device;
1200 }
1201
1202 device->context_id = anv_gem_create_context(device);
1203 if (device->context_id == -1) {
1204 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1205 goto fail_fd;
1206 }
1207
1208 device->info = physical_device->info;
1209 device->isl_dev = physical_device->isl_dev;
1210
1211 /* On Broadwell and later, we can use batch chaining to more efficiently
1212 * implement growing command buffers. Prior to Haswell, the kernel
1213 * command parser gets in the way and we have to fall back to growing
1214 * the batch.
1215 */
1216 device->can_chain_batches = device->info.gen >= 8;
1217
1218 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1219 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1220
1221 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1222 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1223 goto fail_context_id;
1224 }
1225
1226 pthread_condattr_t condattr;
1227 if (pthread_condattr_init(&condattr) != 0) {
1228 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1229 goto fail_mutex;
1230 }
1231 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1232 pthread_condattr_destroy(&condattr);
1233 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1234 goto fail_mutex;
1235 }
1236 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1237 pthread_condattr_destroy(&condattr);
1238 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1239 goto fail_mutex;
1240 }
1241 pthread_condattr_destroy(&condattr);
1242
1243 uint64_t bo_flags =
1244 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
1245 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
1246 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0);
1247
1248 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
1249
1250 result = anv_bo_cache_init(&device->bo_cache);
1251 if (result != VK_SUCCESS)
1252 goto fail_batch_bo_pool;
1253
1254 /* For the state pools we explicitly disable 48bit. */
1255 bo_flags = physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0;
1256
1257 result = anv_state_pool_init(&device->dynamic_state_pool, device, 16384,
1258 bo_flags);
1259 if (result != VK_SUCCESS)
1260 goto fail_bo_cache;
1261
1262 result = anv_state_pool_init(&device->instruction_state_pool, device, 16384,
1263 bo_flags |
1264 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0));
1265 if (result != VK_SUCCESS)
1266 goto fail_dynamic_state_pool;
1267
1268 result = anv_state_pool_init(&device->surface_state_pool, device, 4096,
1269 bo_flags);
1270 if (result != VK_SUCCESS)
1271 goto fail_instruction_state_pool;
1272
1273 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1274 if (result != VK_SUCCESS)
1275 goto fail_surface_state_pool;
1276
1277 anv_device_init_trivial_batch(device);
1278
1279 anv_scratch_pool_init(device, &device->scratch_pool);
1280
1281 anv_queue_init(device, &device->queue);
1282
1283 switch (device->info.gen) {
1284 case 7:
1285 if (!device->info.is_haswell)
1286 result = gen7_init_device_state(device);
1287 else
1288 result = gen75_init_device_state(device);
1289 break;
1290 case 8:
1291 result = gen8_init_device_state(device);
1292 break;
1293 case 9:
1294 result = gen9_init_device_state(device);
1295 break;
1296 case 10:
1297 result = gen10_init_device_state(device);
1298 break;
1299 default:
1300 /* Shouldn't get here as we don't create physical devices for any other
1301 * gens. */
1302 unreachable("unhandled gen");
1303 }
1304 if (result != VK_SUCCESS)
1305 goto fail_workaround_bo;
1306
1307 anv_device_init_blorp(device);
1308
1309 anv_device_init_border_colors(device);
1310
1311 *pDevice = anv_device_to_handle(device);
1312
1313 return VK_SUCCESS;
1314
1315 fail_workaround_bo:
1316 anv_queue_finish(&device->queue);
1317 anv_scratch_pool_finish(device, &device->scratch_pool);
1318 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1319 anv_gem_close(device, device->workaround_bo.gem_handle);
1320 fail_surface_state_pool:
1321 anv_state_pool_finish(&device->surface_state_pool);
1322 fail_instruction_state_pool:
1323 anv_state_pool_finish(&device->instruction_state_pool);
1324 fail_dynamic_state_pool:
1325 anv_state_pool_finish(&device->dynamic_state_pool);
1326 fail_bo_cache:
1327 anv_bo_cache_finish(&device->bo_cache);
1328 fail_batch_bo_pool:
1329 anv_bo_pool_finish(&device->batch_bo_pool);
1330 pthread_cond_destroy(&device->queue_submit);
1331 fail_mutex:
1332 pthread_mutex_destroy(&device->mutex);
1333 fail_context_id:
1334 anv_gem_destroy_context(device, device->context_id);
1335 fail_fd:
1336 close(device->fd);
1337 fail_device:
1338 vk_free(&device->alloc, device);
1339
1340 return result;
1341 }
1342
1343 void anv_DestroyDevice(
1344 VkDevice _device,
1345 const VkAllocationCallbacks* pAllocator)
1346 {
1347 ANV_FROM_HANDLE(anv_device, device, _device);
1348
1349 if (!device)
1350 return;
1351
1352 anv_device_finish_blorp(device);
1353
1354 anv_queue_finish(&device->queue);
1355
1356 #ifdef HAVE_VALGRIND
1357 /* We only need to free these to prevent valgrind errors. The backing
1358 * BO will go away in a couple of lines so we don't actually leak.
1359 */
1360 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1361 #endif
1362
1363 anv_scratch_pool_finish(device, &device->scratch_pool);
1364
1365 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1366 anv_gem_close(device, device->workaround_bo.gem_handle);
1367
1368 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
1369
1370 anv_state_pool_finish(&device->surface_state_pool);
1371 anv_state_pool_finish(&device->instruction_state_pool);
1372 anv_state_pool_finish(&device->dynamic_state_pool);
1373
1374 anv_bo_cache_finish(&device->bo_cache);
1375
1376 anv_bo_pool_finish(&device->batch_bo_pool);
1377
1378 pthread_cond_destroy(&device->queue_submit);
1379 pthread_mutex_destroy(&device->mutex);
1380
1381 anv_gem_destroy_context(device, device->context_id);
1382
1383 close(device->fd);
1384
1385 vk_free(&device->alloc, device);
1386 }
1387
1388 VkResult anv_EnumerateInstanceLayerProperties(
1389 uint32_t* pPropertyCount,
1390 VkLayerProperties* pProperties)
1391 {
1392 if (pProperties == NULL) {
1393 *pPropertyCount = 0;
1394 return VK_SUCCESS;
1395 }
1396
1397 /* None supported at this time */
1398 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1399 }
1400
1401 VkResult anv_EnumerateDeviceLayerProperties(
1402 VkPhysicalDevice physicalDevice,
1403 uint32_t* pPropertyCount,
1404 VkLayerProperties* pProperties)
1405 {
1406 if (pProperties == NULL) {
1407 *pPropertyCount = 0;
1408 return VK_SUCCESS;
1409 }
1410
1411 /* None supported at this time */
1412 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1413 }
1414
1415 void anv_GetDeviceQueue(
1416 VkDevice _device,
1417 uint32_t queueNodeIndex,
1418 uint32_t queueIndex,
1419 VkQueue* pQueue)
1420 {
1421 ANV_FROM_HANDLE(anv_device, device, _device);
1422
1423 assert(queueIndex == 0);
1424
1425 *pQueue = anv_queue_to_handle(&device->queue);
1426 }
1427
1428 VkResult
1429 anv_device_query_status(struct anv_device *device)
1430 {
1431 /* This isn't likely as most of the callers of this function already check
1432 * for it. However, it doesn't hurt to check and it potentially lets us
1433 * avoid an ioctl.
1434 */
1435 if (unlikely(device->lost))
1436 return VK_ERROR_DEVICE_LOST;
1437
1438 uint32_t active, pending;
1439 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
1440 if (ret == -1) {
1441 /* We don't know the real error. */
1442 device->lost = true;
1443 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1444 "get_reset_stats failed: %m");
1445 }
1446
1447 if (active) {
1448 device->lost = true;
1449 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1450 "GPU hung on one of our command buffers");
1451 } else if (pending) {
1452 device->lost = true;
1453 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1454 "GPU hung with commands in-flight");
1455 }
1456
1457 return VK_SUCCESS;
1458 }
1459
1460 VkResult
1461 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
1462 {
1463 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
1464 * Other usages of the BO (such as on different hardware) will not be
1465 * flagged as "busy" by this ioctl. Use with care.
1466 */
1467 int ret = anv_gem_busy(device, bo->gem_handle);
1468 if (ret == 1) {
1469 return VK_NOT_READY;
1470 } else if (ret == -1) {
1471 /* We don't know the real error. */
1472 device->lost = true;
1473 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1474 "gem wait failed: %m");
1475 }
1476
1477 /* Query for device status after the busy call. If the BO we're checking
1478 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
1479 * client because it clearly doesn't have valid data. Yes, this most
1480 * likely means an ioctl, but we just did an ioctl to query the busy status
1481 * so it's no great loss.
1482 */
1483 return anv_device_query_status(device);
1484 }
1485
1486 VkResult
1487 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
1488 int64_t timeout)
1489 {
1490 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
1491 if (ret == -1 && errno == ETIME) {
1492 return VK_TIMEOUT;
1493 } else if (ret == -1) {
1494 /* We don't know the real error. */
1495 device->lost = true;
1496 return vk_errorf(device->instance, device, VK_ERROR_DEVICE_LOST,
1497 "gem wait failed: %m");
1498 }
1499
1500 /* Query for device status after the wait. If the BO we're waiting on got
1501 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
1502 * because it clearly doesn't have valid data. Yes, this most likely means
1503 * an ioctl, but we just did an ioctl to wait so it's no great loss.
1504 */
1505 return anv_device_query_status(device);
1506 }
1507
1508 VkResult anv_DeviceWaitIdle(
1509 VkDevice _device)
1510 {
1511 ANV_FROM_HANDLE(anv_device, device, _device);
1512 if (unlikely(device->lost))
1513 return VK_ERROR_DEVICE_LOST;
1514
1515 struct anv_batch batch;
1516
1517 uint32_t cmds[8];
1518 batch.start = batch.next = cmds;
1519 batch.end = (void *) cmds + sizeof(cmds);
1520
1521 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1522 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1523
1524 return anv_device_submit_simple_batch(device, &batch);
1525 }
1526
1527 VkResult
1528 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
1529 {
1530 uint32_t gem_handle = anv_gem_create(device, size);
1531 if (!gem_handle)
1532 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1533
1534 anv_bo_init(bo, gem_handle, size);
1535
1536 return VK_SUCCESS;
1537 }
1538
1539 VkResult anv_AllocateMemory(
1540 VkDevice _device,
1541 const VkMemoryAllocateInfo* pAllocateInfo,
1542 const VkAllocationCallbacks* pAllocator,
1543 VkDeviceMemory* pMem)
1544 {
1545 ANV_FROM_HANDLE(anv_device, device, _device);
1546 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1547 struct anv_device_memory *mem;
1548 VkResult result = VK_SUCCESS;
1549
1550 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1551
1552 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
1553 assert(pAllocateInfo->allocationSize > 0);
1554
1555 /* The kernel relocation API has a limitation of a 32-bit delta value
1556 * applied to the address before it is written which, in spite of it being
1557 * unsigned, is treated as signed . Because of the way that this maps to
1558 * the Vulkan API, we cannot handle an offset into a buffer that does not
1559 * fit into a signed 32 bits. The only mechanism we have for dealing with
1560 * this at the moment is to limit all VkDeviceMemory objects to a maximum
1561 * of 2GB each. The Vulkan spec allows us to do this:
1562 *
1563 * "Some platforms may have a limit on the maximum size of a single
1564 * allocation. For example, certain systems may fail to create
1565 * allocations with a size greater than or equal to 4GB. Such a limit is
1566 * implementation-dependent, and if such a failure occurs then the error
1567 * VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
1568 *
1569 * We don't use vk_error here because it's not an error so much as an
1570 * indication to the application that the allocation is too large.
1571 */
1572 if (pAllocateInfo->allocationSize > (1ull << 31))
1573 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1574
1575 /* FINISHME: Fail if allocation request exceeds heap size. */
1576
1577 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1578 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1579 if (mem == NULL)
1580 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1581
1582 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
1583 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
1584 mem->map = NULL;
1585 mem->map_size = 0;
1586
1587 const VkImportMemoryFdInfoKHR *fd_info =
1588 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
1589
1590 /* The Vulkan spec permits handleType to be 0, in which case the struct is
1591 * ignored.
1592 */
1593 if (fd_info && fd_info->handleType) {
1594 /* At the moment, we support only the below handle types. */
1595 assert(fd_info->handleType ==
1596 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR ||
1597 fd_info->handleType ==
1598 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1599
1600 result = anv_bo_cache_import(device, &device->bo_cache,
1601 fd_info->fd, &mem->bo);
1602 if (result != VK_SUCCESS)
1603 goto fail;
1604
1605 VkDeviceSize aligned_alloc_size =
1606 align_u64(pAllocateInfo->allocationSize, 4096);
1607
1608 /* For security purposes, we reject importing the bo if it's smaller
1609 * than the requested allocation size. This prevents a malicious client
1610 * from passing a buffer to a trusted client, lying about the size, and
1611 * telling the trusted client to try and texture from an image that goes
1612 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
1613 * in the trusted client. The trusted client can protect itself against
1614 * this sort of attack but only if it can trust the buffer size.
1615 */
1616 if (mem->bo->size < aligned_alloc_size) {
1617 result = vk_errorf(device->instance, device,
1618 VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR,
1619 "aligned allocationSize too large for "
1620 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR: "
1621 "%"PRIu64"B > %"PRIu64"B",
1622 aligned_alloc_size, mem->bo->size);
1623 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1624 goto fail;
1625 }
1626
1627 /* From the Vulkan spec:
1628 *
1629 * "Importing memory from a file descriptor transfers ownership of
1630 * the file descriptor from the application to the Vulkan
1631 * implementation. The application must not perform any operations on
1632 * the file descriptor after a successful import."
1633 *
1634 * If the import fails, we leave the file descriptor open.
1635 */
1636 close(fd_info->fd);
1637 } else {
1638 result = anv_bo_cache_alloc(device, &device->bo_cache,
1639 pAllocateInfo->allocationSize,
1640 &mem->bo);
1641 if (result != VK_SUCCESS)
1642 goto fail;
1643
1644 const VkMemoryDedicatedAllocateInfoKHR *dedicated_info =
1645 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO_KHR);
1646 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
1647 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
1648
1649 /* For images using modifiers, we require a dedicated allocation
1650 * and we set the BO tiling to match the tiling of the underlying
1651 * modifier. This is a bit unfortunate as this is completely
1652 * pointless for Vulkan. However, GL needs to be able to map things
1653 * so it needs the tiling to be set. The only way to do this in a
1654 * non-racy way is to set the tiling in the creator of the BO so that
1655 * makes it our job.
1656 *
1657 * One of these days, once the GL driver learns to not map things
1658 * through the GTT in random places, we can drop this and start
1659 * allowing multiple modified images in the same BO.
1660 */
1661 if (image->drm_format_mod != DRM_FORMAT_MOD_INVALID) {
1662 assert(isl_drm_modifier_get_info(image->drm_format_mod)->tiling ==
1663 image->planes[0].surface.isl.tiling);
1664 const uint32_t i915_tiling =
1665 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
1666 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
1667 image->planes[0].surface.isl.row_pitch,
1668 i915_tiling);
1669 if (ret) {
1670 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1671 return vk_errorf(device->instance, NULL,
1672 VK_ERROR_OUT_OF_DEVICE_MEMORY,
1673 "failed to set BO tiling: %m");
1674 }
1675 }
1676 }
1677 }
1678
1679 assert(mem->type->heapIndex < pdevice->memory.heap_count);
1680 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
1681 mem->bo->flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1682
1683 const struct wsi_memory_allocate_info *wsi_info =
1684 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
1685 if (wsi_info && wsi_info->implicit_sync) {
1686 /* We need to set the WRITE flag on window system buffers so that GEM
1687 * will know we're writing to them and synchronize uses on other rings
1688 * (eg if the display server uses the blitter ring).
1689 */
1690 mem->bo->flags |= EXEC_OBJECT_WRITE;
1691 } else if (pdevice->has_exec_async) {
1692 mem->bo->flags |= EXEC_OBJECT_ASYNC;
1693 }
1694
1695 *pMem = anv_device_memory_to_handle(mem);
1696
1697 return VK_SUCCESS;
1698
1699 fail:
1700 vk_free2(&device->alloc, pAllocator, mem);
1701
1702 return result;
1703 }
1704
1705 VkResult anv_GetMemoryFdKHR(
1706 VkDevice device_h,
1707 const VkMemoryGetFdInfoKHR* pGetFdInfo,
1708 int* pFd)
1709 {
1710 ANV_FROM_HANDLE(anv_device, dev, device_h);
1711 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
1712
1713 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
1714
1715 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR ||
1716 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
1717
1718 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
1719 }
1720
1721 VkResult anv_GetMemoryFdPropertiesKHR(
1722 VkDevice _device,
1723 VkExternalMemoryHandleTypeFlagBitsKHR handleType,
1724 int fd,
1725 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
1726 {
1727 ANV_FROM_HANDLE(anv_device, device, _device);
1728 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1729
1730 switch (handleType) {
1731 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
1732 /* dma-buf can be imported as any memory type */
1733 pMemoryFdProperties->memoryTypeBits =
1734 (1 << pdevice->memory.type_count) - 1;
1735 return VK_SUCCESS;
1736
1737 default:
1738 /* The valid usage section for this function says:
1739 *
1740 * "handleType must not be one of the handle types defined as
1741 * opaque."
1742 *
1743 * So opaque handle types fall into the default "unsupported" case.
1744 */
1745 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR);
1746 }
1747 }
1748
1749 void anv_FreeMemory(
1750 VkDevice _device,
1751 VkDeviceMemory _mem,
1752 const VkAllocationCallbacks* pAllocator)
1753 {
1754 ANV_FROM_HANDLE(anv_device, device, _device);
1755 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
1756
1757 if (mem == NULL)
1758 return;
1759
1760 if (mem->map)
1761 anv_UnmapMemory(_device, _mem);
1762
1763 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1764
1765 vk_free2(&device->alloc, pAllocator, mem);
1766 }
1767
1768 VkResult anv_MapMemory(
1769 VkDevice _device,
1770 VkDeviceMemory _memory,
1771 VkDeviceSize offset,
1772 VkDeviceSize size,
1773 VkMemoryMapFlags flags,
1774 void** ppData)
1775 {
1776 ANV_FROM_HANDLE(anv_device, device, _device);
1777 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1778
1779 if (mem == NULL) {
1780 *ppData = NULL;
1781 return VK_SUCCESS;
1782 }
1783
1784 if (size == VK_WHOLE_SIZE)
1785 size = mem->bo->size - offset;
1786
1787 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
1788 *
1789 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
1790 * assert(size != 0);
1791 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
1792 * equal to the size of the memory minus offset
1793 */
1794 assert(size > 0);
1795 assert(offset + size <= mem->bo->size);
1796
1797 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
1798 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
1799 * at a time is valid. We could just mmap up front and return an offset
1800 * pointer here, but that may exhaust virtual memory on 32 bit
1801 * userspace. */
1802
1803 uint32_t gem_flags = 0;
1804
1805 if (!device->info.has_llc &&
1806 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
1807 gem_flags |= I915_MMAP_WC;
1808
1809 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
1810 uint64_t map_offset = offset & ~4095ull;
1811 assert(offset >= map_offset);
1812 uint64_t map_size = (offset + size) - map_offset;
1813
1814 /* Let's map whole pages */
1815 map_size = align_u64(map_size, 4096);
1816
1817 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
1818 map_offset, map_size, gem_flags);
1819 if (map == MAP_FAILED)
1820 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1821
1822 mem->map = map;
1823 mem->map_size = map_size;
1824
1825 *ppData = mem->map + (offset - map_offset);
1826
1827 return VK_SUCCESS;
1828 }
1829
1830 void anv_UnmapMemory(
1831 VkDevice _device,
1832 VkDeviceMemory _memory)
1833 {
1834 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1835
1836 if (mem == NULL)
1837 return;
1838
1839 anv_gem_munmap(mem->map, mem->map_size);
1840
1841 mem->map = NULL;
1842 mem->map_size = 0;
1843 }
1844
1845 static void
1846 clflush_mapped_ranges(struct anv_device *device,
1847 uint32_t count,
1848 const VkMappedMemoryRange *ranges)
1849 {
1850 for (uint32_t i = 0; i < count; i++) {
1851 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
1852 if (ranges[i].offset >= mem->map_size)
1853 continue;
1854
1855 gen_clflush_range(mem->map + ranges[i].offset,
1856 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
1857 }
1858 }
1859
1860 VkResult anv_FlushMappedMemoryRanges(
1861 VkDevice _device,
1862 uint32_t memoryRangeCount,
1863 const VkMappedMemoryRange* pMemoryRanges)
1864 {
1865 ANV_FROM_HANDLE(anv_device, device, _device);
1866
1867 if (device->info.has_llc)
1868 return VK_SUCCESS;
1869
1870 /* Make sure the writes we're flushing have landed. */
1871 __builtin_ia32_mfence();
1872
1873 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1874
1875 return VK_SUCCESS;
1876 }
1877
1878 VkResult anv_InvalidateMappedMemoryRanges(
1879 VkDevice _device,
1880 uint32_t memoryRangeCount,
1881 const VkMappedMemoryRange* pMemoryRanges)
1882 {
1883 ANV_FROM_HANDLE(anv_device, device, _device);
1884
1885 if (device->info.has_llc)
1886 return VK_SUCCESS;
1887
1888 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1889
1890 /* Make sure no reads get moved up above the invalidate. */
1891 __builtin_ia32_mfence();
1892
1893 return VK_SUCCESS;
1894 }
1895
1896 void anv_GetBufferMemoryRequirements(
1897 VkDevice _device,
1898 VkBuffer _buffer,
1899 VkMemoryRequirements* pMemoryRequirements)
1900 {
1901 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1902 ANV_FROM_HANDLE(anv_device, device, _device);
1903 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1904
1905 /* The Vulkan spec (git aaed022) says:
1906 *
1907 * memoryTypeBits is a bitfield and contains one bit set for every
1908 * supported memory type for the resource. The bit `1<<i` is set if and
1909 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1910 * structure for the physical device is supported.
1911 */
1912 uint32_t memory_types = 0;
1913 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
1914 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
1915 if ((valid_usage & buffer->usage) == buffer->usage)
1916 memory_types |= (1u << i);
1917 }
1918
1919 /* Base alignment requirement of a cache line */
1920 uint32_t alignment = 16;
1921
1922 /* We need an alignment of 32 for pushing UBOs */
1923 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
1924 alignment = MAX2(alignment, 32);
1925
1926 pMemoryRequirements->size = buffer->size;
1927 pMemoryRequirements->alignment = alignment;
1928 pMemoryRequirements->memoryTypeBits = memory_types;
1929 }
1930
1931 void anv_GetBufferMemoryRequirements2KHR(
1932 VkDevice _device,
1933 const VkBufferMemoryRequirementsInfo2KHR* pInfo,
1934 VkMemoryRequirements2KHR* pMemoryRequirements)
1935 {
1936 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
1937 &pMemoryRequirements->memoryRequirements);
1938
1939 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
1940 switch (ext->sType) {
1941 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
1942 VkMemoryDedicatedRequirementsKHR *requirements = (void *)ext;
1943 requirements->prefersDedicatedAllocation = VK_FALSE;
1944 requirements->requiresDedicatedAllocation = VK_FALSE;
1945 break;
1946 }
1947
1948 default:
1949 anv_debug_ignored_stype(ext->sType);
1950 break;
1951 }
1952 }
1953 }
1954
1955 void anv_GetImageMemoryRequirements(
1956 VkDevice _device,
1957 VkImage _image,
1958 VkMemoryRequirements* pMemoryRequirements)
1959 {
1960 ANV_FROM_HANDLE(anv_image, image, _image);
1961 ANV_FROM_HANDLE(anv_device, device, _device);
1962 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1963
1964 /* The Vulkan spec (git aaed022) says:
1965 *
1966 * memoryTypeBits is a bitfield and contains one bit set for every
1967 * supported memory type for the resource. The bit `1<<i` is set if and
1968 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1969 * structure for the physical device is supported.
1970 *
1971 * All types are currently supported for images.
1972 */
1973 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
1974
1975 pMemoryRequirements->size = image->size;
1976 pMemoryRequirements->alignment = image->alignment;
1977 pMemoryRequirements->memoryTypeBits = memory_types;
1978 }
1979
1980 void anv_GetImageMemoryRequirements2KHR(
1981 VkDevice _device,
1982 const VkImageMemoryRequirementsInfo2KHR* pInfo,
1983 VkMemoryRequirements2KHR* pMemoryRequirements)
1984 {
1985 ANV_FROM_HANDLE(anv_device, device, _device);
1986 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
1987
1988 anv_GetImageMemoryRequirements(_device, pInfo->image,
1989 &pMemoryRequirements->memoryRequirements);
1990
1991 vk_foreach_struct_const(ext, pInfo->pNext) {
1992 switch (ext->sType) {
1993 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO_KHR: {
1994 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
1995 const VkImagePlaneMemoryRequirementsInfoKHR *plane_reqs =
1996 (const VkImagePlaneMemoryRequirementsInfoKHR *) ext;
1997 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
1998 plane_reqs->planeAspect);
1999
2000 assert(image->planes[plane].offset == 0);
2001
2002 /* The Vulkan spec (git aaed022) says:
2003 *
2004 * memoryTypeBits is a bitfield and contains one bit set for every
2005 * supported memory type for the resource. The bit `1<<i` is set
2006 * if and only if the memory type `i` in the
2007 * VkPhysicalDeviceMemoryProperties structure for the physical
2008 * device is supported.
2009 *
2010 * All types are currently supported for images.
2011 */
2012 pMemoryRequirements->memoryRequirements.memoryTypeBits =
2013 (1ull << pdevice->memory.type_count) - 1;
2014
2015 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
2016 pMemoryRequirements->memoryRequirements.alignment =
2017 image->planes[plane].alignment;
2018 break;
2019 }
2020
2021 default:
2022 anv_debug_ignored_stype(ext->sType);
2023 break;
2024 }
2025 }
2026
2027 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2028 switch (ext->sType) {
2029 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
2030 VkMemoryDedicatedRequirementsKHR *requirements = (void *)ext;
2031 if (image->drm_format_mod != DRM_FORMAT_MOD_INVALID) {
2032 /* Require a dedicated allocation for images with modifiers.
2033 *
2034 * See also anv_AllocateMemory.
2035 */
2036 requirements->prefersDedicatedAllocation = VK_TRUE;
2037 requirements->requiresDedicatedAllocation = VK_TRUE;
2038 } else {
2039 requirements->prefersDedicatedAllocation = VK_FALSE;
2040 requirements->requiresDedicatedAllocation = VK_FALSE;
2041 }
2042 break;
2043 }
2044
2045 default:
2046 anv_debug_ignored_stype(ext->sType);
2047 break;
2048 }
2049 }
2050 }
2051
2052 void anv_GetImageSparseMemoryRequirements(
2053 VkDevice device,
2054 VkImage image,
2055 uint32_t* pSparseMemoryRequirementCount,
2056 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
2057 {
2058 *pSparseMemoryRequirementCount = 0;
2059 }
2060
2061 void anv_GetImageSparseMemoryRequirements2KHR(
2062 VkDevice device,
2063 const VkImageSparseMemoryRequirementsInfo2KHR* pInfo,
2064 uint32_t* pSparseMemoryRequirementCount,
2065 VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements)
2066 {
2067 *pSparseMemoryRequirementCount = 0;
2068 }
2069
2070 void anv_GetDeviceMemoryCommitment(
2071 VkDevice device,
2072 VkDeviceMemory memory,
2073 VkDeviceSize* pCommittedMemoryInBytes)
2074 {
2075 *pCommittedMemoryInBytes = 0;
2076 }
2077
2078 static void
2079 anv_bind_buffer_memory(const VkBindBufferMemoryInfoKHR *pBindInfo)
2080 {
2081 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
2082 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
2083
2084 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR);
2085
2086 if (mem) {
2087 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
2088 buffer->bo = mem->bo;
2089 buffer->offset = pBindInfo->memoryOffset;
2090 } else {
2091 buffer->bo = NULL;
2092 buffer->offset = 0;
2093 }
2094 }
2095
2096 VkResult anv_BindBufferMemory(
2097 VkDevice device,
2098 VkBuffer buffer,
2099 VkDeviceMemory memory,
2100 VkDeviceSize memoryOffset)
2101 {
2102 anv_bind_buffer_memory(
2103 &(VkBindBufferMemoryInfoKHR) {
2104 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR,
2105 .buffer = buffer,
2106 .memory = memory,
2107 .memoryOffset = memoryOffset,
2108 });
2109
2110 return VK_SUCCESS;
2111 }
2112
2113 VkResult anv_BindBufferMemory2KHR(
2114 VkDevice device,
2115 uint32_t bindInfoCount,
2116 const VkBindBufferMemoryInfoKHR* pBindInfos)
2117 {
2118 for (uint32_t i = 0; i < bindInfoCount; i++)
2119 anv_bind_buffer_memory(&pBindInfos[i]);
2120
2121 return VK_SUCCESS;
2122 }
2123
2124 VkResult anv_QueueBindSparse(
2125 VkQueue _queue,
2126 uint32_t bindInfoCount,
2127 const VkBindSparseInfo* pBindInfo,
2128 VkFence fence)
2129 {
2130 ANV_FROM_HANDLE(anv_queue, queue, _queue);
2131 if (unlikely(queue->device->lost))
2132 return VK_ERROR_DEVICE_LOST;
2133
2134 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2135 }
2136
2137 // Event functions
2138
2139 VkResult anv_CreateEvent(
2140 VkDevice _device,
2141 const VkEventCreateInfo* pCreateInfo,
2142 const VkAllocationCallbacks* pAllocator,
2143 VkEvent* pEvent)
2144 {
2145 ANV_FROM_HANDLE(anv_device, device, _device);
2146 struct anv_state state;
2147 struct anv_event *event;
2148
2149 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2150
2151 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2152 sizeof(*event), 8);
2153 event = state.map;
2154 event->state = state;
2155 event->semaphore = VK_EVENT_RESET;
2156
2157 if (!device->info.has_llc) {
2158 /* Make sure the writes we're flushing have landed. */
2159 __builtin_ia32_mfence();
2160 __builtin_ia32_clflush(event);
2161 }
2162
2163 *pEvent = anv_event_to_handle(event);
2164
2165 return VK_SUCCESS;
2166 }
2167
2168 void anv_DestroyEvent(
2169 VkDevice _device,
2170 VkEvent _event,
2171 const VkAllocationCallbacks* pAllocator)
2172 {
2173 ANV_FROM_HANDLE(anv_device, device, _device);
2174 ANV_FROM_HANDLE(anv_event, event, _event);
2175
2176 if (!event)
2177 return;
2178
2179 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2180 }
2181
2182 VkResult anv_GetEventStatus(
2183 VkDevice _device,
2184 VkEvent _event)
2185 {
2186 ANV_FROM_HANDLE(anv_device, device, _device);
2187 ANV_FROM_HANDLE(anv_event, event, _event);
2188
2189 if (unlikely(device->lost))
2190 return VK_ERROR_DEVICE_LOST;
2191
2192 if (!device->info.has_llc) {
2193 /* Invalidate read cache before reading event written by GPU. */
2194 __builtin_ia32_clflush(event);
2195 __builtin_ia32_mfence();
2196
2197 }
2198
2199 return event->semaphore;
2200 }
2201
2202 VkResult anv_SetEvent(
2203 VkDevice _device,
2204 VkEvent _event)
2205 {
2206 ANV_FROM_HANDLE(anv_device, device, _device);
2207 ANV_FROM_HANDLE(anv_event, event, _event);
2208
2209 event->semaphore = VK_EVENT_SET;
2210
2211 if (!device->info.has_llc) {
2212 /* Make sure the writes we're flushing have landed. */
2213 __builtin_ia32_mfence();
2214 __builtin_ia32_clflush(event);
2215 }
2216
2217 return VK_SUCCESS;
2218 }
2219
2220 VkResult anv_ResetEvent(
2221 VkDevice _device,
2222 VkEvent _event)
2223 {
2224 ANV_FROM_HANDLE(anv_device, device, _device);
2225 ANV_FROM_HANDLE(anv_event, event, _event);
2226
2227 event->semaphore = VK_EVENT_RESET;
2228
2229 if (!device->info.has_llc) {
2230 /* Make sure the writes we're flushing have landed. */
2231 __builtin_ia32_mfence();
2232 __builtin_ia32_clflush(event);
2233 }
2234
2235 return VK_SUCCESS;
2236 }
2237
2238 // Buffer functions
2239
2240 VkResult anv_CreateBuffer(
2241 VkDevice _device,
2242 const VkBufferCreateInfo* pCreateInfo,
2243 const VkAllocationCallbacks* pAllocator,
2244 VkBuffer* pBuffer)
2245 {
2246 ANV_FROM_HANDLE(anv_device, device, _device);
2247 struct anv_buffer *buffer;
2248
2249 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2250
2251 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2252 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2253 if (buffer == NULL)
2254 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2255
2256 buffer->size = pCreateInfo->size;
2257 buffer->usage = pCreateInfo->usage;
2258 buffer->bo = NULL;
2259 buffer->offset = 0;
2260
2261 *pBuffer = anv_buffer_to_handle(buffer);
2262
2263 return VK_SUCCESS;
2264 }
2265
2266 void anv_DestroyBuffer(
2267 VkDevice _device,
2268 VkBuffer _buffer,
2269 const VkAllocationCallbacks* pAllocator)
2270 {
2271 ANV_FROM_HANDLE(anv_device, device, _device);
2272 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2273
2274 if (!buffer)
2275 return;
2276
2277 vk_free2(&device->alloc, pAllocator, buffer);
2278 }
2279
2280 void
2281 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2282 enum isl_format format,
2283 uint32_t offset, uint32_t range, uint32_t stride)
2284 {
2285 isl_buffer_fill_state(&device->isl_dev, state.map,
2286 .address = offset,
2287 .mocs = device->default_mocs,
2288 .size = range,
2289 .format = format,
2290 .stride = stride);
2291
2292 anv_state_flush(device, state);
2293 }
2294
2295 void anv_DestroySampler(
2296 VkDevice _device,
2297 VkSampler _sampler,
2298 const VkAllocationCallbacks* pAllocator)
2299 {
2300 ANV_FROM_HANDLE(anv_device, device, _device);
2301 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2302
2303 if (!sampler)
2304 return;
2305
2306 vk_free2(&device->alloc, pAllocator, sampler);
2307 }
2308
2309 VkResult anv_CreateFramebuffer(
2310 VkDevice _device,
2311 const VkFramebufferCreateInfo* pCreateInfo,
2312 const VkAllocationCallbacks* pAllocator,
2313 VkFramebuffer* pFramebuffer)
2314 {
2315 ANV_FROM_HANDLE(anv_device, device, _device);
2316 struct anv_framebuffer *framebuffer;
2317
2318 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2319
2320 size_t size = sizeof(*framebuffer) +
2321 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2322 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2323 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2324 if (framebuffer == NULL)
2325 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2326
2327 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2328 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2329 VkImageView _iview = pCreateInfo->pAttachments[i];
2330 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2331 }
2332
2333 framebuffer->width = pCreateInfo->width;
2334 framebuffer->height = pCreateInfo->height;
2335 framebuffer->layers = pCreateInfo->layers;
2336
2337 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2338
2339 return VK_SUCCESS;
2340 }
2341
2342 void anv_DestroyFramebuffer(
2343 VkDevice _device,
2344 VkFramebuffer _fb,
2345 const VkAllocationCallbacks* pAllocator)
2346 {
2347 ANV_FROM_HANDLE(anv_device, device, _device);
2348 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2349
2350 if (!fb)
2351 return;
2352
2353 vk_free2(&device->alloc, pAllocator, fb);
2354 }
2355
2356 /* vk_icd.h does not declare this function, so we declare it here to
2357 * suppress Wmissing-prototypes.
2358 */
2359 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2360 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2361
2362 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2363 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2364 {
2365 /* For the full details on loader interface versioning, see
2366 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2367 * What follows is a condensed summary, to help you navigate the large and
2368 * confusing official doc.
2369 *
2370 * - Loader interface v0 is incompatible with later versions. We don't
2371 * support it.
2372 *
2373 * - In loader interface v1:
2374 * - The first ICD entrypoint called by the loader is
2375 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2376 * entrypoint.
2377 * - The ICD must statically expose no other Vulkan symbol unless it is
2378 * linked with -Bsymbolic.
2379 * - Each dispatchable Vulkan handle created by the ICD must be
2380 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2381 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2382 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2383 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2384 * such loader-managed surfaces.
2385 *
2386 * - Loader interface v2 differs from v1 in:
2387 * - The first ICD entrypoint called by the loader is
2388 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2389 * statically expose this entrypoint.
2390 *
2391 * - Loader interface v3 differs from v2 in:
2392 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2393 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2394 * because the loader no longer does so.
2395 */
2396 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2397 return VK_SUCCESS;
2398 }