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