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