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