anv: Make all VkDeviceMemory BOs resident permanently
[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 features->storageBuffer8BitAccess = pdevice->info.gen >= 8;
942 features->uniformAndStorageBuffer8BitAccess = pdevice->info.gen >= 8;
943 features->storagePushConstant8 = pdevice->info.gen >= 8;
944 break;
945 }
946
947 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
948 VkPhysicalDevice16BitStorageFeatures *features =
949 (VkPhysicalDevice16BitStorageFeatures *)ext;
950 features->storageBuffer16BitAccess = pdevice->info.gen >= 8;
951 features->uniformAndStorageBuffer16BitAccess = pdevice->info.gen >= 8;
952 features->storagePushConstant16 = pdevice->info.gen >= 8;
953 features->storageInputOutput16 = false;
954 break;
955 }
956
957 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT: {
958 VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *features = (void *)ext;
959 features->bufferDeviceAddress = pdevice->use_softpin &&
960 pdevice->info.gen >= 8;
961 features->bufferDeviceAddressCaptureReplay = false;
962 features->bufferDeviceAddressMultiDevice = false;
963 break;
964 }
965
966 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV: {
967 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *features =
968 (VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *)ext;
969 features->computeDerivativeGroupQuads = true;
970 features->computeDerivativeGroupLinear = true;
971 break;
972 }
973
974 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
975 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
976 (VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
977 features->conditionalRendering = pdevice->info.gen >= 8 ||
978 pdevice->info.is_haswell;
979 features->inheritedConditionalRendering = pdevice->info.gen >= 8 ||
980 pdevice->info.is_haswell;
981 break;
982 }
983
984 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT: {
985 VkPhysicalDeviceDepthClipEnableFeaturesEXT *features =
986 (VkPhysicalDeviceDepthClipEnableFeaturesEXT *)ext;
987 features->depthClipEnable = true;
988 break;
989 }
990
991 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR: {
992 VkPhysicalDeviceFloat16Int8FeaturesKHR *features = (void *)ext;
993 features->shaderFloat16 = pdevice->info.gen >= 8;
994 features->shaderInt8 = pdevice->info.gen >= 8;
995 break;
996 }
997
998 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT: {
999 VkPhysicalDeviceHostQueryResetFeaturesEXT *features =
1000 (VkPhysicalDeviceHostQueryResetFeaturesEXT *)ext;
1001 features->hostQueryReset = true;
1002 break;
1003 }
1004
1005 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT: {
1006 VkPhysicalDeviceInlineUniformBlockFeaturesEXT *features =
1007 (VkPhysicalDeviceInlineUniformBlockFeaturesEXT *)ext;
1008 features->inlineUniformBlock = true;
1009 features->descriptorBindingInlineUniformBlockUpdateAfterBind = false;
1010 break;
1011 }
1012
1013 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
1014 VkPhysicalDeviceMultiviewFeatures *features =
1015 (VkPhysicalDeviceMultiviewFeatures *)ext;
1016 features->multiview = true;
1017 features->multiviewGeometryShader = true;
1018 features->multiviewTessellationShader = true;
1019 break;
1020 }
1021
1022 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
1023 VkPhysicalDeviceProtectedMemoryFeatures *features = (void *)ext;
1024 features->protectedMemory = false;
1025 break;
1026 }
1027
1028 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
1029 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
1030 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
1031 features->samplerYcbcrConversion = true;
1032 break;
1033 }
1034
1035 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
1036 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
1037 (VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
1038 features->scalarBlockLayout = true;
1039 break;
1040 }
1041
1042 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
1043 VkPhysicalDeviceShaderDrawParametersFeatures *features = (void *)ext;
1044 features->shaderDrawParameters = true;
1045 break;
1046 }
1047
1048 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
1049 VkPhysicalDeviceVariablePointersFeatures *features = (void *)ext;
1050 features->variablePointersStorageBuffer = true;
1051 features->variablePointers = true;
1052 break;
1053 }
1054
1055 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
1056 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
1057 (VkPhysicalDeviceTransformFeedbackFeaturesEXT *)ext;
1058 features->transformFeedback = true;
1059 features->geometryStreams = true;
1060 break;
1061 }
1062
1063 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
1064 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
1065 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
1066 features->vertexAttributeInstanceRateDivisor = true;
1067 features->vertexAttributeInstanceRateZeroDivisor = true;
1068 break;
1069 }
1070
1071 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT: {
1072 VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *features =
1073 (VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *)ext;
1074 features->ycbcrImageArrays = true;
1075 break;
1076 }
1077
1078 default:
1079 anv_debug_ignored_stype(ext->sType);
1080 break;
1081 }
1082 }
1083 }
1084
1085 void anv_GetPhysicalDeviceProperties(
1086 VkPhysicalDevice physicalDevice,
1087 VkPhysicalDeviceProperties* pProperties)
1088 {
1089 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1090 const struct gen_device_info *devinfo = &pdevice->info;
1091
1092 /* See assertions made when programming the buffer surface state. */
1093 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
1094 (1ul << 30) : (1ul << 27);
1095
1096 const uint32_t max_samplers = (devinfo->gen >= 8 || devinfo->is_haswell) ?
1097 128 : 16;
1098
1099 const uint32_t max_images = devinfo->gen < 9 ? MAX_GEN8_IMAGES : MAX_IMAGES;
1100
1101 VkSampleCountFlags sample_counts =
1102 isl_device_get_sample_counts(&pdevice->isl_dev);
1103
1104
1105 VkPhysicalDeviceLimits limits = {
1106 .maxImageDimension1D = (1 << 14),
1107 .maxImageDimension2D = (1 << 14),
1108 .maxImageDimension3D = (1 << 11),
1109 .maxImageDimensionCube = (1 << 14),
1110 .maxImageArrayLayers = (1 << 11),
1111 .maxTexelBufferElements = 128 * 1024 * 1024,
1112 .maxUniformBufferRange = (1ul << 27),
1113 .maxStorageBufferRange = max_raw_buffer_sz,
1114 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
1115 .maxMemoryAllocationCount = UINT32_MAX,
1116 .maxSamplerAllocationCount = 64 * 1024,
1117 .bufferImageGranularity = 64, /* A cache line */
1118 .sparseAddressSpaceSize = 0,
1119 .maxBoundDescriptorSets = MAX_SETS,
1120 .maxPerStageDescriptorSamplers = max_samplers,
1121 .maxPerStageDescriptorUniformBuffers = 64,
1122 .maxPerStageDescriptorStorageBuffers = 64,
1123 .maxPerStageDescriptorSampledImages = max_samplers,
1124 .maxPerStageDescriptorStorageImages = max_images,
1125 .maxPerStageDescriptorInputAttachments = 64,
1126 .maxPerStageResources = 250,
1127 .maxDescriptorSetSamplers = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
1128 .maxDescriptorSetUniformBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorUniformBuffers */
1129 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
1130 .maxDescriptorSetStorageBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorStorageBuffers */
1131 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
1132 .maxDescriptorSetSampledImages = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSampledImages */
1133 .maxDescriptorSetStorageImages = 6 * max_images, /* number of stages * maxPerStageDescriptorStorageImages */
1134 .maxDescriptorSetInputAttachments = 256,
1135 .maxVertexInputAttributes = MAX_VBS,
1136 .maxVertexInputBindings = MAX_VBS,
1137 .maxVertexInputAttributeOffset = 2047,
1138 .maxVertexInputBindingStride = 2048,
1139 .maxVertexOutputComponents = 128,
1140 .maxTessellationGenerationLevel = 64,
1141 .maxTessellationPatchSize = 32,
1142 .maxTessellationControlPerVertexInputComponents = 128,
1143 .maxTessellationControlPerVertexOutputComponents = 128,
1144 .maxTessellationControlPerPatchOutputComponents = 128,
1145 .maxTessellationControlTotalOutputComponents = 2048,
1146 .maxTessellationEvaluationInputComponents = 128,
1147 .maxTessellationEvaluationOutputComponents = 128,
1148 .maxGeometryShaderInvocations = 32,
1149 .maxGeometryInputComponents = 64,
1150 .maxGeometryOutputComponents = 128,
1151 .maxGeometryOutputVertices = 256,
1152 .maxGeometryTotalOutputComponents = 1024,
1153 .maxFragmentInputComponents = 112, /* 128 components - (POS, PSIZ, CLIP_DIST0, CLIP_DIST1) */
1154 .maxFragmentOutputAttachments = 8,
1155 .maxFragmentDualSrcAttachments = 1,
1156 .maxFragmentCombinedOutputResources = 8,
1157 .maxComputeSharedMemorySize = 32768,
1158 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
1159 .maxComputeWorkGroupInvocations = 32 * devinfo->max_cs_threads,
1160 .maxComputeWorkGroupSize = {
1161 16 * devinfo->max_cs_threads,
1162 16 * devinfo->max_cs_threads,
1163 16 * devinfo->max_cs_threads,
1164 },
1165 .subPixelPrecisionBits = 8,
1166 .subTexelPrecisionBits = 8,
1167 .mipmapPrecisionBits = 8,
1168 .maxDrawIndexedIndexValue = UINT32_MAX,
1169 .maxDrawIndirectCount = UINT32_MAX,
1170 .maxSamplerLodBias = 16,
1171 .maxSamplerAnisotropy = 16,
1172 .maxViewports = MAX_VIEWPORTS,
1173 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1174 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1175 .viewportSubPixelBits = 13, /* We take a float? */
1176 .minMemoryMapAlignment = 4096, /* A page */
1177 .minTexelBufferOffsetAlignment = 1,
1178 /* We need 16 for UBO block reads to work and 32 for push UBOs */
1179 .minUniformBufferOffsetAlignment = 32,
1180 .minStorageBufferOffsetAlignment = 4,
1181 .minTexelOffset = -8,
1182 .maxTexelOffset = 7,
1183 .minTexelGatherOffset = -32,
1184 .maxTexelGatherOffset = 31,
1185 .minInterpolationOffset = -0.5,
1186 .maxInterpolationOffset = 0.4375,
1187 .subPixelInterpolationOffsetBits = 4,
1188 .maxFramebufferWidth = (1 << 14),
1189 .maxFramebufferHeight = (1 << 14),
1190 .maxFramebufferLayers = (1 << 11),
1191 .framebufferColorSampleCounts = sample_counts,
1192 .framebufferDepthSampleCounts = sample_counts,
1193 .framebufferStencilSampleCounts = sample_counts,
1194 .framebufferNoAttachmentsSampleCounts = sample_counts,
1195 .maxColorAttachments = MAX_RTS,
1196 .sampledImageColorSampleCounts = sample_counts,
1197 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1198 .sampledImageDepthSampleCounts = sample_counts,
1199 .sampledImageStencilSampleCounts = sample_counts,
1200 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1201 .maxSampleMaskWords = 1,
1202 .timestampComputeAndGraphics = false,
1203 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
1204 .maxClipDistances = 8,
1205 .maxCullDistances = 8,
1206 .maxCombinedClipAndCullDistances = 8,
1207 .discreteQueuePriorities = 2,
1208 .pointSizeRange = { 0.125, 255.875 },
1209 .lineWidthRange = { 0.0, 7.9921875 },
1210 .pointSizeGranularity = (1.0 / 8.0),
1211 .lineWidthGranularity = (1.0 / 128.0),
1212 .strictLines = false, /* FINISHME */
1213 .standardSampleLocations = true,
1214 .optimalBufferCopyOffsetAlignment = 128,
1215 .optimalBufferCopyRowPitchAlignment = 128,
1216 .nonCoherentAtomSize = 64,
1217 };
1218
1219 *pProperties = (VkPhysicalDeviceProperties) {
1220 .apiVersion = anv_physical_device_api_version(pdevice),
1221 .driverVersion = vk_get_driver_version(),
1222 .vendorID = 0x8086,
1223 .deviceID = pdevice->chipset_id,
1224 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1225 .limits = limits,
1226 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
1227 };
1228
1229 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
1230 "%s", pdevice->name);
1231 memcpy(pProperties->pipelineCacheUUID,
1232 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
1233 }
1234
1235 void anv_GetPhysicalDeviceProperties2(
1236 VkPhysicalDevice physicalDevice,
1237 VkPhysicalDeviceProperties2* pProperties)
1238 {
1239 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1240
1241 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1242
1243 vk_foreach_struct(ext, pProperties->pNext) {
1244 switch (ext->sType) {
1245 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR: {
1246 VkPhysicalDeviceDepthStencilResolvePropertiesKHR *props =
1247 (VkPhysicalDeviceDepthStencilResolvePropertiesKHR *)ext;
1248
1249 /* We support all of the depth resolve modes */
1250 props->supportedDepthResolveModes =
1251 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1252 VK_RESOLVE_MODE_AVERAGE_BIT_KHR |
1253 VK_RESOLVE_MODE_MIN_BIT_KHR |
1254 VK_RESOLVE_MODE_MAX_BIT_KHR;
1255
1256 /* Average doesn't make sense for stencil so we don't support that */
1257 props->supportedStencilResolveModes =
1258 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR;
1259 if (pdevice->info.gen >= 8) {
1260 /* The advanced stencil resolve modes currently require stencil
1261 * sampling be supported by the hardware.
1262 */
1263 props->supportedStencilResolveModes |=
1264 VK_RESOLVE_MODE_MIN_BIT_KHR |
1265 VK_RESOLVE_MODE_MAX_BIT_KHR;
1266 }
1267
1268 props->independentResolveNone = true;
1269 props->independentResolve = true;
1270 break;
1271 }
1272
1273 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
1274 VkPhysicalDeviceDriverPropertiesKHR *driver_props =
1275 (VkPhysicalDeviceDriverPropertiesKHR *) ext;
1276
1277 driver_props->driverID = VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA_KHR;
1278 util_snprintf(driver_props->driverName, VK_MAX_DRIVER_NAME_SIZE_KHR,
1279 "Intel open-source Mesa driver");
1280
1281 util_snprintf(driver_props->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1282 "Mesa " PACKAGE_VERSION MESA_GIT_SHA1);
1283
1284 driver_props->conformanceVersion = (VkConformanceVersionKHR) {
1285 .major = 1,
1286 .minor = 1,
1287 .subminor = 2,
1288 .patch = 0,
1289 };
1290 break;
1291 }
1292
1293 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1294 VkPhysicalDeviceExternalMemoryHostPropertiesEXT *props =
1295 (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1296 /* Userptr needs page aligned memory. */
1297 props->minImportedHostPointerAlignment = 4096;
1298 break;
1299 }
1300
1301 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1302 VkPhysicalDeviceIDProperties *id_props =
1303 (VkPhysicalDeviceIDProperties *)ext;
1304 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1305 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1306 /* The LUID is for Windows. */
1307 id_props->deviceLUIDValid = false;
1308 break;
1309 }
1310
1311 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT: {
1312 VkPhysicalDeviceInlineUniformBlockPropertiesEXT *props =
1313 (VkPhysicalDeviceInlineUniformBlockPropertiesEXT *)ext;
1314 props->maxInlineUniformBlockSize = MAX_INLINE_UNIFORM_BLOCK_SIZE;
1315 props->maxPerStageDescriptorInlineUniformBlocks =
1316 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1317 props->maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks =
1318 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1319 props->maxDescriptorSetInlineUniformBlocks =
1320 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1321 props->maxDescriptorSetUpdateAfterBindInlineUniformBlocks =
1322 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1323 break;
1324 }
1325
1326 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1327 VkPhysicalDeviceMaintenance3Properties *props =
1328 (VkPhysicalDeviceMaintenance3Properties *)ext;
1329 /* This value doesn't matter for us today as our per-stage
1330 * descriptors are the real limit.
1331 */
1332 props->maxPerSetDescriptors = 1024;
1333 props->maxMemoryAllocationSize = MAX_MEMORY_ALLOCATION_SIZE;
1334 break;
1335 }
1336
1337 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1338 VkPhysicalDeviceMultiviewProperties *properties =
1339 (VkPhysicalDeviceMultiviewProperties *)ext;
1340 properties->maxMultiviewViewCount = 16;
1341 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
1342 break;
1343 }
1344
1345 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1346 VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1347 (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1348 properties->pciDomain = pdevice->pci_info.domain;
1349 properties->pciBus = pdevice->pci_info.bus;
1350 properties->pciDevice = pdevice->pci_info.device;
1351 properties->pciFunction = pdevice->pci_info.function;
1352 break;
1353 }
1354
1355 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1356 VkPhysicalDevicePointClippingProperties *properties =
1357 (VkPhysicalDevicePointClippingProperties *) ext;
1358 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1359 anv_finishme("Implement pop-free point clipping");
1360 break;
1361 }
1362
1363 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
1364 VkPhysicalDeviceProtectedMemoryProperties *props =
1365 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
1366 props->protectedNoFault = false;
1367 break;
1368 }
1369
1370 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1371 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1372 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1373
1374 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1375 break;
1376 }
1377
1378 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
1379 VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
1380 (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
1381 properties->filterMinmaxImageComponentMapping = pdevice->info.gen >= 9;
1382 properties->filterMinmaxSingleComponentFormats = true;
1383 break;
1384 }
1385
1386 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1387 VkPhysicalDeviceSubgroupProperties *properties = (void *)ext;
1388
1389 properties->subgroupSize = BRW_SUBGROUP_SIZE;
1390
1391 VkShaderStageFlags scalar_stages = 0;
1392 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1393 if (pdevice->compiler->scalar_stage[stage])
1394 scalar_stages |= mesa_to_vk_shader_stage(stage);
1395 }
1396 properties->supportedStages = scalar_stages;
1397
1398 properties->supportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1399 VK_SUBGROUP_FEATURE_VOTE_BIT |
1400 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1401 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1402 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1403 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
1404 VK_SUBGROUP_FEATURE_CLUSTERED_BIT |
1405 VK_SUBGROUP_FEATURE_QUAD_BIT;
1406 properties->quadOperationsInAllStages = true;
1407 break;
1408 }
1409
1410 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
1411 VkPhysicalDeviceTransformFeedbackPropertiesEXT *props =
1412 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
1413
1414 props->maxTransformFeedbackStreams = MAX_XFB_STREAMS;
1415 props->maxTransformFeedbackBuffers = MAX_XFB_BUFFERS;
1416 props->maxTransformFeedbackBufferSize = (1ull << 32);
1417 props->maxTransformFeedbackStreamDataSize = 128 * 4;
1418 props->maxTransformFeedbackBufferDataSize = 128 * 4;
1419 props->maxTransformFeedbackBufferDataStride = 2048;
1420 props->transformFeedbackQueries = true;
1421 props->transformFeedbackStreamsLinesTriangles = false;
1422 props->transformFeedbackRasterizationStreamSelect = false;
1423 props->transformFeedbackDraw = true;
1424 break;
1425 }
1426
1427 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1428 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *props =
1429 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1430 /* We have to restrict this a bit for multiview */
1431 props->maxVertexAttribDivisor = UINT32_MAX / 16;
1432 break;
1433 }
1434
1435 default:
1436 anv_debug_ignored_stype(ext->sType);
1437 break;
1438 }
1439 }
1440 }
1441
1442 /* We support exactly one queue family. */
1443 static const VkQueueFamilyProperties
1444 anv_queue_family_properties = {
1445 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1446 VK_QUEUE_COMPUTE_BIT |
1447 VK_QUEUE_TRANSFER_BIT,
1448 .queueCount = 1,
1449 .timestampValidBits = 36, /* XXX: Real value here */
1450 .minImageTransferGranularity = { 1, 1, 1 },
1451 };
1452
1453 void anv_GetPhysicalDeviceQueueFamilyProperties(
1454 VkPhysicalDevice physicalDevice,
1455 uint32_t* pCount,
1456 VkQueueFamilyProperties* pQueueFamilyProperties)
1457 {
1458 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
1459
1460 vk_outarray_append(&out, p) {
1461 *p = anv_queue_family_properties;
1462 }
1463 }
1464
1465 void anv_GetPhysicalDeviceQueueFamilyProperties2(
1466 VkPhysicalDevice physicalDevice,
1467 uint32_t* pQueueFamilyPropertyCount,
1468 VkQueueFamilyProperties2* pQueueFamilyProperties)
1469 {
1470
1471 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1472
1473 vk_outarray_append(&out, p) {
1474 p->queueFamilyProperties = anv_queue_family_properties;
1475
1476 vk_foreach_struct(s, p->pNext) {
1477 anv_debug_ignored_stype(s->sType);
1478 }
1479 }
1480 }
1481
1482 void anv_GetPhysicalDeviceMemoryProperties(
1483 VkPhysicalDevice physicalDevice,
1484 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
1485 {
1486 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1487
1488 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
1489 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
1490 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
1491 .propertyFlags = physical_device->memory.types[i].propertyFlags,
1492 .heapIndex = physical_device->memory.types[i].heapIndex,
1493 };
1494 }
1495
1496 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
1497 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
1498 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
1499 .size = physical_device->memory.heaps[i].size,
1500 .flags = physical_device->memory.heaps[i].flags,
1501 };
1502 }
1503 }
1504
1505 void anv_GetPhysicalDeviceMemoryProperties2(
1506 VkPhysicalDevice physicalDevice,
1507 VkPhysicalDeviceMemoryProperties2* pMemoryProperties)
1508 {
1509 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1510 &pMemoryProperties->memoryProperties);
1511
1512 vk_foreach_struct(ext, pMemoryProperties->pNext) {
1513 switch (ext->sType) {
1514 default:
1515 anv_debug_ignored_stype(ext->sType);
1516 break;
1517 }
1518 }
1519 }
1520
1521 void
1522 anv_GetDeviceGroupPeerMemoryFeatures(
1523 VkDevice device,
1524 uint32_t heapIndex,
1525 uint32_t localDeviceIndex,
1526 uint32_t remoteDeviceIndex,
1527 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
1528 {
1529 assert(localDeviceIndex == 0 && remoteDeviceIndex == 0);
1530 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
1531 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
1532 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
1533 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
1534 }
1535
1536 PFN_vkVoidFunction anv_GetInstanceProcAddr(
1537 VkInstance _instance,
1538 const char* pName)
1539 {
1540 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1541
1542 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
1543 * when we have to return valid function pointers, NULL, or it's left
1544 * undefined. See the table for exact details.
1545 */
1546 if (pName == NULL)
1547 return NULL;
1548
1549 #define LOOKUP_ANV_ENTRYPOINT(entrypoint) \
1550 if (strcmp(pName, "vk" #entrypoint) == 0) \
1551 return (PFN_vkVoidFunction)anv_##entrypoint
1552
1553 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
1554 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceLayerProperties);
1555 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceVersion);
1556 LOOKUP_ANV_ENTRYPOINT(CreateInstance);
1557
1558 #undef LOOKUP_ANV_ENTRYPOINT
1559
1560 if (instance == NULL)
1561 return NULL;
1562
1563 int idx = anv_get_instance_entrypoint_index(pName);
1564 if (idx >= 0)
1565 return instance->dispatch.entrypoints[idx];
1566
1567 idx = anv_get_device_entrypoint_index(pName);
1568 if (idx >= 0)
1569 return instance->device_dispatch.entrypoints[idx];
1570
1571 return NULL;
1572 }
1573
1574 /* With version 1+ of the loader interface the ICD should expose
1575 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
1576 */
1577 PUBLIC
1578 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1579 VkInstance instance,
1580 const char* pName);
1581
1582 PUBLIC
1583 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1584 VkInstance instance,
1585 const char* pName)
1586 {
1587 return anv_GetInstanceProcAddr(instance, pName);
1588 }
1589
1590 PFN_vkVoidFunction anv_GetDeviceProcAddr(
1591 VkDevice _device,
1592 const char* pName)
1593 {
1594 ANV_FROM_HANDLE(anv_device, device, _device);
1595
1596 if (!device || !pName)
1597 return NULL;
1598
1599 int idx = anv_get_device_entrypoint_index(pName);
1600 if (idx < 0)
1601 return NULL;
1602
1603 return device->dispatch.entrypoints[idx];
1604 }
1605
1606 VkResult
1607 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
1608 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
1609 const VkAllocationCallbacks* pAllocator,
1610 VkDebugReportCallbackEXT* pCallback)
1611 {
1612 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1613 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
1614 pCreateInfo, pAllocator, &instance->alloc,
1615 pCallback);
1616 }
1617
1618 void
1619 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
1620 VkDebugReportCallbackEXT _callback,
1621 const VkAllocationCallbacks* pAllocator)
1622 {
1623 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1624 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
1625 _callback, pAllocator, &instance->alloc);
1626 }
1627
1628 void
1629 anv_DebugReportMessageEXT(VkInstance _instance,
1630 VkDebugReportFlagsEXT flags,
1631 VkDebugReportObjectTypeEXT objectType,
1632 uint64_t object,
1633 size_t location,
1634 int32_t messageCode,
1635 const char* pLayerPrefix,
1636 const char* pMessage)
1637 {
1638 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1639 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
1640 object, location, messageCode, pLayerPrefix, pMessage);
1641 }
1642
1643 static void
1644 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
1645 {
1646 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1647 queue->device = device;
1648 queue->flags = 0;
1649 }
1650
1651 static void
1652 anv_queue_finish(struct anv_queue *queue)
1653 {
1654 }
1655
1656 static struct anv_state
1657 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
1658 {
1659 struct anv_state state;
1660
1661 state = anv_state_pool_alloc(pool, size, align);
1662 memcpy(state.map, p, size);
1663
1664 return state;
1665 }
1666
1667 struct gen8_border_color {
1668 union {
1669 float float32[4];
1670 uint32_t uint32[4];
1671 };
1672 /* Pad out to 64 bytes */
1673 uint32_t _pad[12];
1674 };
1675
1676 static void
1677 anv_device_init_border_colors(struct anv_device *device)
1678 {
1679 static const struct gen8_border_color border_colors[] = {
1680 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1681 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1682 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1683 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1684 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1685 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1686 };
1687
1688 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1689 sizeof(border_colors), 64,
1690 border_colors);
1691 }
1692
1693 static void
1694 anv_device_init_trivial_batch(struct anv_device *device)
1695 {
1696 anv_bo_init_new(&device->trivial_batch_bo, device, 4096);
1697
1698 if (device->instance->physicalDevice.has_exec_async)
1699 device->trivial_batch_bo.flags |= EXEC_OBJECT_ASYNC;
1700
1701 if (device->instance->physicalDevice.use_softpin)
1702 device->trivial_batch_bo.flags |= EXEC_OBJECT_PINNED;
1703
1704 anv_vma_alloc(device, &device->trivial_batch_bo);
1705
1706 void *map = anv_gem_mmap(device, device->trivial_batch_bo.gem_handle,
1707 0, 4096, 0);
1708
1709 struct anv_batch batch = {
1710 .start = map,
1711 .next = map,
1712 .end = map + 4096,
1713 };
1714
1715 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1716 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1717
1718 if (!device->info.has_llc)
1719 gen_clflush_range(map, batch.next - map);
1720
1721 anv_gem_munmap(map, device->trivial_batch_bo.size);
1722 }
1723
1724 VkResult anv_EnumerateDeviceExtensionProperties(
1725 VkPhysicalDevice physicalDevice,
1726 const char* pLayerName,
1727 uint32_t* pPropertyCount,
1728 VkExtensionProperties* pProperties)
1729 {
1730 ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
1731 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1732
1733 for (int i = 0; i < ANV_DEVICE_EXTENSION_COUNT; i++) {
1734 if (device->supported_extensions.extensions[i]) {
1735 vk_outarray_append(&out, prop) {
1736 *prop = anv_device_extensions[i];
1737 }
1738 }
1739 }
1740
1741 return vk_outarray_status(&out);
1742 }
1743
1744 static void
1745 anv_device_init_dispatch(struct anv_device *device)
1746 {
1747 const struct anv_device_dispatch_table *genX_table;
1748 switch (device->info.gen) {
1749 case 11:
1750 genX_table = &gen11_device_dispatch_table;
1751 break;
1752 case 10:
1753 genX_table = &gen10_device_dispatch_table;
1754 break;
1755 case 9:
1756 genX_table = &gen9_device_dispatch_table;
1757 break;
1758 case 8:
1759 genX_table = &gen8_device_dispatch_table;
1760 break;
1761 case 7:
1762 if (device->info.is_haswell)
1763 genX_table = &gen75_device_dispatch_table;
1764 else
1765 genX_table = &gen7_device_dispatch_table;
1766 break;
1767 default:
1768 unreachable("unsupported gen\n");
1769 }
1770
1771 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
1772 /* Vulkan requires that entrypoints for extensions which have not been
1773 * enabled must not be advertised.
1774 */
1775 if (!anv_device_entrypoint_is_enabled(i, device->instance->app_info.api_version,
1776 &device->instance->enabled_extensions,
1777 &device->enabled_extensions)) {
1778 device->dispatch.entrypoints[i] = NULL;
1779 } else if (genX_table->entrypoints[i]) {
1780 device->dispatch.entrypoints[i] = genX_table->entrypoints[i];
1781 } else {
1782 device->dispatch.entrypoints[i] =
1783 anv_device_dispatch_table.entrypoints[i];
1784 }
1785 }
1786 }
1787
1788 static int
1789 vk_priority_to_gen(int priority)
1790 {
1791 switch (priority) {
1792 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1793 return GEN_CONTEXT_LOW_PRIORITY;
1794 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1795 return GEN_CONTEXT_MEDIUM_PRIORITY;
1796 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1797 return GEN_CONTEXT_HIGH_PRIORITY;
1798 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1799 return GEN_CONTEXT_REALTIME_PRIORITY;
1800 default:
1801 unreachable("Invalid priority");
1802 }
1803 }
1804
1805 static void
1806 anv_device_init_hiz_clear_value_bo(struct anv_device *device)
1807 {
1808 anv_bo_init_new(&device->hiz_clear_bo, device, 4096);
1809
1810 if (device->instance->physicalDevice.has_exec_async)
1811 device->hiz_clear_bo.flags |= EXEC_OBJECT_ASYNC;
1812
1813 if (device->instance->physicalDevice.use_softpin)
1814 device->hiz_clear_bo.flags |= EXEC_OBJECT_PINNED;
1815
1816 anv_vma_alloc(device, &device->hiz_clear_bo);
1817
1818 uint32_t *map = anv_gem_mmap(device, device->hiz_clear_bo.gem_handle,
1819 0, 4096, 0);
1820
1821 union isl_color_value hiz_clear = { .u32 = { 0, } };
1822 hiz_clear.f32[0] = ANV_HZ_FC_VAL;
1823
1824 memcpy(map, hiz_clear.u32, sizeof(hiz_clear.u32));
1825 anv_gem_munmap(map, device->hiz_clear_bo.size);
1826 }
1827
1828 static bool
1829 get_bo_from_pool(struct gen_batch_decode_bo *ret,
1830 struct anv_block_pool *pool,
1831 uint64_t address)
1832 {
1833 for (uint32_t i = 0; i < pool->nbos; i++) {
1834 uint64_t bo_address = pool->bos[i].offset & (~0ull >> 16);
1835 uint32_t bo_size = pool->bos[i].size;
1836 if (address >= bo_address && address < (bo_address + bo_size)) {
1837 *ret = (struct gen_batch_decode_bo) {
1838 .addr = bo_address,
1839 .size = bo_size,
1840 .map = pool->bos[i].map,
1841 };
1842 return true;
1843 }
1844 }
1845 return false;
1846 }
1847
1848 /* Finding a buffer for batch decoding */
1849 static struct gen_batch_decode_bo
1850 decode_get_bo(void *v_batch, bool ppgtt, uint64_t address)
1851 {
1852 struct anv_device *device = v_batch;
1853 struct gen_batch_decode_bo ret_bo = {};
1854
1855 assert(ppgtt);
1856
1857 if (get_bo_from_pool(&ret_bo, &device->dynamic_state_pool.block_pool, address))
1858 return ret_bo;
1859 if (get_bo_from_pool(&ret_bo, &device->instruction_state_pool.block_pool, address))
1860 return ret_bo;
1861 if (get_bo_from_pool(&ret_bo, &device->binding_table_pool.block_pool, address))
1862 return ret_bo;
1863 if (get_bo_from_pool(&ret_bo, &device->surface_state_pool.block_pool, address))
1864 return ret_bo;
1865
1866 if (!device->cmd_buffer_being_decoded)
1867 return (struct gen_batch_decode_bo) { };
1868
1869 struct anv_batch_bo **bo;
1870
1871 u_vector_foreach(bo, &device->cmd_buffer_being_decoded->seen_bbos) {
1872 /* The decoder zeroes out the top 16 bits, so we need to as well */
1873 uint64_t bo_address = (*bo)->bo.offset & (~0ull >> 16);
1874
1875 if (address >= bo_address && address < bo_address + (*bo)->bo.size) {
1876 return (struct gen_batch_decode_bo) {
1877 .addr = bo_address,
1878 .size = (*bo)->bo.size,
1879 .map = (*bo)->bo.map,
1880 };
1881 }
1882 }
1883
1884 return (struct gen_batch_decode_bo) { };
1885 }
1886
1887 VkResult anv_CreateDevice(
1888 VkPhysicalDevice physicalDevice,
1889 const VkDeviceCreateInfo* pCreateInfo,
1890 const VkAllocationCallbacks* pAllocator,
1891 VkDevice* pDevice)
1892 {
1893 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1894 VkResult result;
1895 struct anv_device *device;
1896
1897 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1898
1899 struct anv_device_extension_table enabled_extensions = { };
1900 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1901 int idx;
1902 for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
1903 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1904 anv_device_extensions[idx].extensionName) == 0)
1905 break;
1906 }
1907
1908 if (idx >= ANV_DEVICE_EXTENSION_COUNT)
1909 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1910
1911 if (!physical_device->supported_extensions.extensions[idx])
1912 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1913
1914 enabled_extensions.extensions[idx] = true;
1915 }
1916
1917 /* Check enabled features */
1918 if (pCreateInfo->pEnabledFeatures) {
1919 VkPhysicalDeviceFeatures supported_features;
1920 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1921 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1922 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1923 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1924 for (uint32_t i = 0; i < num_features; i++) {
1925 if (enabled_feature[i] && !supported_feature[i])
1926 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1927 }
1928 }
1929
1930 /* Check requested queues and fail if we are requested to create any
1931 * queues with flags we don't support.
1932 */
1933 assert(pCreateInfo->queueCreateInfoCount > 0);
1934 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1935 if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
1936 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
1937 }
1938
1939 /* Check if client specified queue priority. */
1940 const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
1941 vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
1942 DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
1943
1944 VkQueueGlobalPriorityEXT priority =
1945 queue_priority ? queue_priority->globalPriority :
1946 VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
1947
1948 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1949 sizeof(*device), 8,
1950 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1951 if (!device)
1952 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1953
1954 const unsigned decode_flags =
1955 GEN_BATCH_DECODE_FULL |
1956 ((INTEL_DEBUG & DEBUG_COLOR) ? GEN_BATCH_DECODE_IN_COLOR : 0) |
1957 GEN_BATCH_DECODE_OFFSETS |
1958 GEN_BATCH_DECODE_FLOATS;
1959
1960 gen_batch_decode_ctx_init(&device->decoder_ctx,
1961 &physical_device->info,
1962 stderr, decode_flags, NULL,
1963 decode_get_bo, NULL, device);
1964
1965 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1966 device->instance = physical_device->instance;
1967 device->chipset_id = physical_device->chipset_id;
1968 device->no_hw = physical_device->no_hw;
1969 device->_lost = false;
1970
1971 if (pAllocator)
1972 device->alloc = *pAllocator;
1973 else
1974 device->alloc = physical_device->instance->alloc;
1975
1976 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1977 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1978 if (device->fd == -1) {
1979 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1980 goto fail_device;
1981 }
1982
1983 device->context_id = anv_gem_create_context(device);
1984 if (device->context_id == -1) {
1985 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1986 goto fail_fd;
1987 }
1988
1989 if (physical_device->use_softpin) {
1990 if (pthread_mutex_init(&device->vma_mutex, NULL) != 0) {
1991 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1992 goto fail_fd;
1993 }
1994
1995 /* keep the page with address zero out of the allocator */
1996 struct anv_memory_heap *low_heap =
1997 &physical_device->memory.heaps[physical_device->memory.heap_count - 1];
1998 util_vma_heap_init(&device->vma_lo, low_heap->vma_start, low_heap->vma_size);
1999 device->vma_lo_available = low_heap->size;
2000
2001 struct anv_memory_heap *high_heap =
2002 &physical_device->memory.heaps[0];
2003 util_vma_heap_init(&device->vma_hi, high_heap->vma_start, high_heap->vma_size);
2004 device->vma_hi_available = physical_device->memory.heap_count == 1 ? 0 :
2005 high_heap->size;
2006 }
2007
2008 list_inithead(&device->memory_objects);
2009
2010 /* As per spec, the driver implementation may deny requests to acquire
2011 * a priority above the default priority (MEDIUM) if the caller does not
2012 * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
2013 * is returned.
2014 */
2015 if (physical_device->has_context_priority) {
2016 int err = anv_gem_set_context_param(device->fd, device->context_id,
2017 I915_CONTEXT_PARAM_PRIORITY,
2018 vk_priority_to_gen(priority));
2019 if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
2020 result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
2021 goto fail_fd;
2022 }
2023 }
2024
2025 device->info = physical_device->info;
2026 device->isl_dev = physical_device->isl_dev;
2027
2028 /* On Broadwell and later, we can use batch chaining to more efficiently
2029 * implement growing command buffers. Prior to Haswell, the kernel
2030 * command parser gets in the way and we have to fall back to growing
2031 * the batch.
2032 */
2033 device->can_chain_batches = device->info.gen >= 8;
2034
2035 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
2036 pCreateInfo->pEnabledFeatures->robustBufferAccess;
2037 device->enabled_extensions = enabled_extensions;
2038
2039 anv_device_init_dispatch(device);
2040
2041 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
2042 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2043 goto fail_context_id;
2044 }
2045
2046 pthread_condattr_t condattr;
2047 if (pthread_condattr_init(&condattr) != 0) {
2048 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2049 goto fail_mutex;
2050 }
2051 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
2052 pthread_condattr_destroy(&condattr);
2053 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2054 goto fail_mutex;
2055 }
2056 if (pthread_cond_init(&device->queue_submit, &condattr) != 0) {
2057 pthread_condattr_destroy(&condattr);
2058 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2059 goto fail_mutex;
2060 }
2061 pthread_condattr_destroy(&condattr);
2062
2063 uint64_t bo_flags =
2064 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
2065 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
2066 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0) |
2067 (physical_device->use_softpin ? EXEC_OBJECT_PINNED : 0);
2068
2069 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
2070
2071 result = anv_bo_cache_init(&device->bo_cache);
2072 if (result != VK_SUCCESS)
2073 goto fail_batch_bo_pool;
2074
2075 if (!physical_device->use_softpin)
2076 bo_flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2077
2078 result = anv_state_pool_init(&device->dynamic_state_pool, device,
2079 DYNAMIC_STATE_POOL_MIN_ADDRESS,
2080 16384,
2081 bo_flags);
2082 if (result != VK_SUCCESS)
2083 goto fail_bo_cache;
2084
2085 result = anv_state_pool_init(&device->instruction_state_pool, device,
2086 INSTRUCTION_STATE_POOL_MIN_ADDRESS,
2087 16384,
2088 bo_flags);
2089 if (result != VK_SUCCESS)
2090 goto fail_dynamic_state_pool;
2091
2092 result = anv_state_pool_init(&device->surface_state_pool, device,
2093 SURFACE_STATE_POOL_MIN_ADDRESS,
2094 4096,
2095 bo_flags);
2096 if (result != VK_SUCCESS)
2097 goto fail_instruction_state_pool;
2098
2099 if (physical_device->use_softpin) {
2100 result = anv_state_pool_init(&device->binding_table_pool, device,
2101 BINDING_TABLE_POOL_MIN_ADDRESS,
2102 4096,
2103 bo_flags);
2104 if (result != VK_SUCCESS)
2105 goto fail_surface_state_pool;
2106 }
2107
2108 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
2109 if (result != VK_SUCCESS)
2110 goto fail_binding_table_pool;
2111
2112 if (physical_device->use_softpin)
2113 device->workaround_bo.flags |= EXEC_OBJECT_PINNED;
2114
2115 if (!anv_vma_alloc(device, &device->workaround_bo))
2116 goto fail_workaround_bo;
2117
2118 anv_device_init_trivial_batch(device);
2119
2120 if (device->info.gen >= 10)
2121 anv_device_init_hiz_clear_value_bo(device);
2122
2123 anv_scratch_pool_init(device, &device->scratch_pool);
2124
2125 anv_queue_init(device, &device->queue);
2126
2127 switch (device->info.gen) {
2128 case 7:
2129 if (!device->info.is_haswell)
2130 result = gen7_init_device_state(device);
2131 else
2132 result = gen75_init_device_state(device);
2133 break;
2134 case 8:
2135 result = gen8_init_device_state(device);
2136 break;
2137 case 9:
2138 result = gen9_init_device_state(device);
2139 break;
2140 case 10:
2141 result = gen10_init_device_state(device);
2142 break;
2143 case 11:
2144 result = gen11_init_device_state(device);
2145 break;
2146 default:
2147 /* Shouldn't get here as we don't create physical devices for any other
2148 * gens. */
2149 unreachable("unhandled gen");
2150 }
2151 if (result != VK_SUCCESS)
2152 goto fail_workaround_bo;
2153
2154 anv_pipeline_cache_init(&device->default_pipeline_cache, device, true);
2155
2156 anv_device_init_blorp(device);
2157
2158 anv_device_init_border_colors(device);
2159
2160 *pDevice = anv_device_to_handle(device);
2161
2162 return VK_SUCCESS;
2163
2164 fail_workaround_bo:
2165 anv_queue_finish(&device->queue);
2166 anv_scratch_pool_finish(device, &device->scratch_pool);
2167 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
2168 anv_gem_close(device, device->workaround_bo.gem_handle);
2169 fail_binding_table_pool:
2170 if (physical_device->use_softpin)
2171 anv_state_pool_finish(&device->binding_table_pool);
2172 fail_surface_state_pool:
2173 anv_state_pool_finish(&device->surface_state_pool);
2174 fail_instruction_state_pool:
2175 anv_state_pool_finish(&device->instruction_state_pool);
2176 fail_dynamic_state_pool:
2177 anv_state_pool_finish(&device->dynamic_state_pool);
2178 fail_bo_cache:
2179 anv_bo_cache_finish(&device->bo_cache);
2180 fail_batch_bo_pool:
2181 anv_bo_pool_finish(&device->batch_bo_pool);
2182 pthread_cond_destroy(&device->queue_submit);
2183 fail_mutex:
2184 pthread_mutex_destroy(&device->mutex);
2185 fail_context_id:
2186 anv_gem_destroy_context(device, device->context_id);
2187 fail_fd:
2188 close(device->fd);
2189 fail_device:
2190 vk_free(&device->alloc, device);
2191
2192 return result;
2193 }
2194
2195 void anv_DestroyDevice(
2196 VkDevice _device,
2197 const VkAllocationCallbacks* pAllocator)
2198 {
2199 ANV_FROM_HANDLE(anv_device, device, _device);
2200 struct anv_physical_device *physical_device;
2201
2202 if (!device)
2203 return;
2204
2205 physical_device = &device->instance->physicalDevice;
2206
2207 anv_device_finish_blorp(device);
2208
2209 anv_pipeline_cache_finish(&device->default_pipeline_cache);
2210
2211 anv_queue_finish(&device->queue);
2212
2213 #ifdef HAVE_VALGRIND
2214 /* We only need to free these to prevent valgrind errors. The backing
2215 * BO will go away in a couple of lines so we don't actually leak.
2216 */
2217 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
2218 #endif
2219
2220 anv_scratch_pool_finish(device, &device->scratch_pool);
2221
2222 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
2223 anv_vma_free(device, &device->workaround_bo);
2224 anv_gem_close(device, device->workaround_bo.gem_handle);
2225
2226 anv_vma_free(device, &device->trivial_batch_bo);
2227 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
2228 if (device->info.gen >= 10)
2229 anv_gem_close(device, device->hiz_clear_bo.gem_handle);
2230
2231 if (physical_device->use_softpin)
2232 anv_state_pool_finish(&device->binding_table_pool);
2233 anv_state_pool_finish(&device->surface_state_pool);
2234 anv_state_pool_finish(&device->instruction_state_pool);
2235 anv_state_pool_finish(&device->dynamic_state_pool);
2236
2237 anv_bo_cache_finish(&device->bo_cache);
2238
2239 anv_bo_pool_finish(&device->batch_bo_pool);
2240
2241 pthread_cond_destroy(&device->queue_submit);
2242 pthread_mutex_destroy(&device->mutex);
2243
2244 anv_gem_destroy_context(device, device->context_id);
2245
2246 gen_batch_decode_ctx_finish(&device->decoder_ctx);
2247
2248 close(device->fd);
2249
2250 vk_free(&device->alloc, device);
2251 }
2252
2253 VkResult anv_EnumerateInstanceLayerProperties(
2254 uint32_t* pPropertyCount,
2255 VkLayerProperties* pProperties)
2256 {
2257 if (pProperties == NULL) {
2258 *pPropertyCount = 0;
2259 return VK_SUCCESS;
2260 }
2261
2262 /* None supported at this time */
2263 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
2264 }
2265
2266 VkResult anv_EnumerateDeviceLayerProperties(
2267 VkPhysicalDevice physicalDevice,
2268 uint32_t* pPropertyCount,
2269 VkLayerProperties* pProperties)
2270 {
2271 if (pProperties == NULL) {
2272 *pPropertyCount = 0;
2273 return VK_SUCCESS;
2274 }
2275
2276 /* None supported at this time */
2277 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
2278 }
2279
2280 void anv_GetDeviceQueue(
2281 VkDevice _device,
2282 uint32_t queueNodeIndex,
2283 uint32_t queueIndex,
2284 VkQueue* pQueue)
2285 {
2286 ANV_FROM_HANDLE(anv_device, device, _device);
2287
2288 assert(queueIndex == 0);
2289
2290 *pQueue = anv_queue_to_handle(&device->queue);
2291 }
2292
2293 void anv_GetDeviceQueue2(
2294 VkDevice _device,
2295 const VkDeviceQueueInfo2* pQueueInfo,
2296 VkQueue* pQueue)
2297 {
2298 ANV_FROM_HANDLE(anv_device, device, _device);
2299
2300 assert(pQueueInfo->queueIndex == 0);
2301
2302 if (pQueueInfo->flags == device->queue.flags)
2303 *pQueue = anv_queue_to_handle(&device->queue);
2304 else
2305 *pQueue = NULL;
2306 }
2307
2308 VkResult
2309 _anv_device_set_lost(struct anv_device *device,
2310 const char *file, int line,
2311 const char *msg, ...)
2312 {
2313 VkResult err;
2314 va_list ap;
2315
2316 device->_lost = true;
2317
2318 va_start(ap, msg);
2319 err = __vk_errorv(device->instance, device,
2320 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
2321 VK_ERROR_DEVICE_LOST, file, line, msg, ap);
2322 va_end(ap);
2323
2324 if (env_var_as_boolean("ANV_ABORT_ON_DEVICE_LOSS", false))
2325 abort();
2326
2327 return err;
2328 }
2329
2330 VkResult
2331 anv_device_query_status(struct anv_device *device)
2332 {
2333 /* This isn't likely as most of the callers of this function already check
2334 * for it. However, it doesn't hurt to check and it potentially lets us
2335 * avoid an ioctl.
2336 */
2337 if (anv_device_is_lost(device))
2338 return VK_ERROR_DEVICE_LOST;
2339
2340 uint32_t active, pending;
2341 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
2342 if (ret == -1) {
2343 /* We don't know the real error. */
2344 return anv_device_set_lost(device, "get_reset_stats failed: %m");
2345 }
2346
2347 if (active) {
2348 return anv_device_set_lost(device, "GPU hung on one of our command buffers");
2349 } else if (pending) {
2350 return anv_device_set_lost(device, "GPU hung with commands in-flight");
2351 }
2352
2353 return VK_SUCCESS;
2354 }
2355
2356 VkResult
2357 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
2358 {
2359 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
2360 * Other usages of the BO (such as on different hardware) will not be
2361 * flagged as "busy" by this ioctl. Use with care.
2362 */
2363 int ret = anv_gem_busy(device, bo->gem_handle);
2364 if (ret == 1) {
2365 return VK_NOT_READY;
2366 } else if (ret == -1) {
2367 /* We don't know the real error. */
2368 return anv_device_set_lost(device, "gem wait failed: %m");
2369 }
2370
2371 /* Query for device status after the busy call. If the BO we're checking
2372 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
2373 * client because it clearly doesn't have valid data. Yes, this most
2374 * likely means an ioctl, but we just did an ioctl to query the busy status
2375 * so it's no great loss.
2376 */
2377 return anv_device_query_status(device);
2378 }
2379
2380 VkResult
2381 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
2382 int64_t timeout)
2383 {
2384 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
2385 if (ret == -1 && errno == ETIME) {
2386 return VK_TIMEOUT;
2387 } else if (ret == -1) {
2388 /* We don't know the real error. */
2389 return anv_device_set_lost(device, "gem wait failed: %m");
2390 }
2391
2392 /* Query for device status after the wait. If the BO we're waiting on got
2393 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
2394 * because it clearly doesn't have valid data. Yes, this most likely means
2395 * an ioctl, but we just did an ioctl to wait so it's no great loss.
2396 */
2397 return anv_device_query_status(device);
2398 }
2399
2400 VkResult anv_DeviceWaitIdle(
2401 VkDevice _device)
2402 {
2403 ANV_FROM_HANDLE(anv_device, device, _device);
2404 if (anv_device_is_lost(device))
2405 return VK_ERROR_DEVICE_LOST;
2406
2407 struct anv_batch batch;
2408
2409 uint32_t cmds[8];
2410 batch.start = batch.next = cmds;
2411 batch.end = (void *) cmds + sizeof(cmds);
2412
2413 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
2414 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
2415
2416 return anv_device_submit_simple_batch(device, &batch);
2417 }
2418
2419 bool
2420 anv_vma_alloc(struct anv_device *device, struct anv_bo *bo)
2421 {
2422 if (!(bo->flags & EXEC_OBJECT_PINNED))
2423 return true;
2424
2425 pthread_mutex_lock(&device->vma_mutex);
2426
2427 bo->offset = 0;
2428
2429 if (bo->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS &&
2430 device->vma_hi_available >= bo->size) {
2431 uint64_t addr = util_vma_heap_alloc(&device->vma_hi, bo->size, 4096);
2432 if (addr) {
2433 bo->offset = gen_canonical_address(addr);
2434 assert(addr == gen_48b_address(bo->offset));
2435 device->vma_hi_available -= bo->size;
2436 }
2437 }
2438
2439 if (bo->offset == 0 && device->vma_lo_available >= bo->size) {
2440 uint64_t addr = util_vma_heap_alloc(&device->vma_lo, bo->size, 4096);
2441 if (addr) {
2442 bo->offset = gen_canonical_address(addr);
2443 assert(addr == gen_48b_address(bo->offset));
2444 device->vma_lo_available -= bo->size;
2445 }
2446 }
2447
2448 pthread_mutex_unlock(&device->vma_mutex);
2449
2450 return bo->offset != 0;
2451 }
2452
2453 void
2454 anv_vma_free(struct anv_device *device, struct anv_bo *bo)
2455 {
2456 if (!(bo->flags & EXEC_OBJECT_PINNED))
2457 return;
2458
2459 const uint64_t addr_48b = gen_48b_address(bo->offset);
2460
2461 pthread_mutex_lock(&device->vma_mutex);
2462
2463 if (addr_48b >= LOW_HEAP_MIN_ADDRESS &&
2464 addr_48b <= LOW_HEAP_MAX_ADDRESS) {
2465 util_vma_heap_free(&device->vma_lo, addr_48b, bo->size);
2466 device->vma_lo_available += bo->size;
2467 } else {
2468 MAYBE_UNUSED const struct anv_physical_device *physical_device =
2469 &device->instance->physicalDevice;
2470 assert(addr_48b >= physical_device->memory.heaps[0].vma_start &&
2471 addr_48b < (physical_device->memory.heaps[0].vma_start +
2472 physical_device->memory.heaps[0].vma_size));
2473 util_vma_heap_free(&device->vma_hi, addr_48b, bo->size);
2474 device->vma_hi_available += bo->size;
2475 }
2476
2477 pthread_mutex_unlock(&device->vma_mutex);
2478
2479 bo->offset = 0;
2480 }
2481
2482 VkResult
2483 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
2484 {
2485 uint32_t gem_handle = anv_gem_create(device, size);
2486 if (!gem_handle)
2487 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
2488
2489 anv_bo_init(bo, gem_handle, size);
2490
2491 return VK_SUCCESS;
2492 }
2493
2494 VkResult anv_AllocateMemory(
2495 VkDevice _device,
2496 const VkMemoryAllocateInfo* pAllocateInfo,
2497 const VkAllocationCallbacks* pAllocator,
2498 VkDeviceMemory* pMem)
2499 {
2500 ANV_FROM_HANDLE(anv_device, device, _device);
2501 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2502 struct anv_device_memory *mem;
2503 VkResult result = VK_SUCCESS;
2504
2505 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
2506
2507 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
2508 assert(pAllocateInfo->allocationSize > 0);
2509
2510 if (pAllocateInfo->allocationSize > MAX_MEMORY_ALLOCATION_SIZE)
2511 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2512
2513 /* FINISHME: Fail if allocation request exceeds heap size. */
2514
2515 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
2516 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2517 if (mem == NULL)
2518 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2519
2520 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
2521 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
2522 mem->map = NULL;
2523 mem->map_size = 0;
2524 mem->ahw = NULL;
2525 mem->host_ptr = NULL;
2526
2527 uint64_t bo_flags = 0;
2528
2529 assert(mem->type->heapIndex < pdevice->memory.heap_count);
2530 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
2531 bo_flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2532
2533 const struct wsi_memory_allocate_info *wsi_info =
2534 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
2535 if (wsi_info && wsi_info->implicit_sync) {
2536 /* We need to set the WRITE flag on window system buffers so that GEM
2537 * will know we're writing to them and synchronize uses on other rings
2538 * (eg if the display server uses the blitter ring).
2539 */
2540 bo_flags |= EXEC_OBJECT_WRITE;
2541 } else if (pdevice->has_exec_async) {
2542 bo_flags |= EXEC_OBJECT_ASYNC;
2543 }
2544
2545 if (pdevice->use_softpin)
2546 bo_flags |= EXEC_OBJECT_PINNED;
2547
2548 const VkExportMemoryAllocateInfo *export_info =
2549 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
2550
2551 /* Check if we need to support Android HW buffer export. If so,
2552 * create AHardwareBuffer and import memory from it.
2553 */
2554 bool android_export = false;
2555 if (export_info && export_info->handleTypes &
2556 VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)
2557 android_export = true;
2558
2559 /* Android memory import. */
2560 const struct VkImportAndroidHardwareBufferInfoANDROID *ahw_import_info =
2561 vk_find_struct_const(pAllocateInfo->pNext,
2562 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
2563
2564 if (ahw_import_info) {
2565 result = anv_import_ahw_memory(_device, mem, ahw_import_info);
2566 if (result != VK_SUCCESS)
2567 goto fail;
2568
2569 goto success;
2570 } else if (android_export) {
2571 result = anv_create_ahw_memory(_device, mem, pAllocateInfo);
2572 if (result != VK_SUCCESS)
2573 goto fail;
2574
2575 const struct VkImportAndroidHardwareBufferInfoANDROID import_info = {
2576 .buffer = mem->ahw,
2577 };
2578 result = anv_import_ahw_memory(_device, mem, &import_info);
2579 if (result != VK_SUCCESS)
2580 goto fail;
2581
2582 goto success;
2583 }
2584
2585 const VkImportMemoryFdInfoKHR *fd_info =
2586 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
2587
2588 /* The Vulkan spec permits handleType to be 0, in which case the struct is
2589 * ignored.
2590 */
2591 if (fd_info && fd_info->handleType) {
2592 /* At the moment, we support only the below handle types. */
2593 assert(fd_info->handleType ==
2594 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2595 fd_info->handleType ==
2596 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2597
2598 result = anv_bo_cache_import(device, &device->bo_cache, fd_info->fd,
2599 bo_flags | ANV_BO_EXTERNAL, &mem->bo);
2600 if (result != VK_SUCCESS)
2601 goto fail;
2602
2603 VkDeviceSize aligned_alloc_size =
2604 align_u64(pAllocateInfo->allocationSize, 4096);
2605
2606 /* For security purposes, we reject importing the bo if it's smaller
2607 * than the requested allocation size. This prevents a malicious client
2608 * from passing a buffer to a trusted client, lying about the size, and
2609 * telling the trusted client to try and texture from an image that goes
2610 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
2611 * in the trusted client. The trusted client can protect itself against
2612 * this sort of attack but only if it can trust the buffer size.
2613 */
2614 if (mem->bo->size < aligned_alloc_size) {
2615 result = vk_errorf(device->instance, device,
2616 VK_ERROR_INVALID_EXTERNAL_HANDLE,
2617 "aligned allocationSize too large for "
2618 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT: "
2619 "%"PRIu64"B > %"PRIu64"B",
2620 aligned_alloc_size, mem->bo->size);
2621 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2622 goto fail;
2623 }
2624
2625 /* From the Vulkan spec:
2626 *
2627 * "Importing memory from a file descriptor transfers ownership of
2628 * the file descriptor from the application to the Vulkan
2629 * implementation. The application must not perform any operations on
2630 * the file descriptor after a successful import."
2631 *
2632 * If the import fails, we leave the file descriptor open.
2633 */
2634 close(fd_info->fd);
2635 goto success;
2636 }
2637
2638 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
2639 vk_find_struct_const(pAllocateInfo->pNext,
2640 IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
2641 if (host_ptr_info && host_ptr_info->handleType) {
2642 if (host_ptr_info->handleType ==
2643 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT) {
2644 result = vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2645 goto fail;
2646 }
2647
2648 assert(host_ptr_info->handleType ==
2649 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
2650
2651 result = anv_bo_cache_import_host_ptr(
2652 device, &device->bo_cache, host_ptr_info->pHostPointer,
2653 pAllocateInfo->allocationSize, bo_flags, &mem->bo);
2654
2655 if (result != VK_SUCCESS)
2656 goto fail;
2657
2658 mem->host_ptr = host_ptr_info->pHostPointer;
2659 goto success;
2660 }
2661
2662 /* Regular allocate (not importing memory). */
2663
2664 if (export_info && export_info->handleTypes)
2665 bo_flags |= ANV_BO_EXTERNAL;
2666
2667 result = anv_bo_cache_alloc(device, &device->bo_cache,
2668 pAllocateInfo->allocationSize, bo_flags,
2669 &mem->bo);
2670 if (result != VK_SUCCESS)
2671 goto fail;
2672
2673 const VkMemoryDedicatedAllocateInfo *dedicated_info =
2674 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
2675 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
2676 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
2677
2678 /* Some legacy (non-modifiers) consumers need the tiling to be set on
2679 * the BO. In this case, we have a dedicated allocation.
2680 */
2681 if (image->needs_set_tiling) {
2682 const uint32_t i915_tiling =
2683 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
2684 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
2685 image->planes[0].surface.isl.row_pitch_B,
2686 i915_tiling);
2687 if (ret) {
2688 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2689 return vk_errorf(device->instance, NULL,
2690 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2691 "failed to set BO tiling: %m");
2692 }
2693 }
2694 }
2695
2696 success:
2697 pthread_mutex_lock(&device->mutex);
2698 list_addtail(&mem->link, &device->memory_objects);
2699 pthread_mutex_unlock(&device->mutex);
2700
2701 *pMem = anv_device_memory_to_handle(mem);
2702
2703 return VK_SUCCESS;
2704
2705 fail:
2706 vk_free2(&device->alloc, pAllocator, mem);
2707
2708 return result;
2709 }
2710
2711 VkResult anv_GetMemoryFdKHR(
2712 VkDevice device_h,
2713 const VkMemoryGetFdInfoKHR* pGetFdInfo,
2714 int* pFd)
2715 {
2716 ANV_FROM_HANDLE(anv_device, dev, device_h);
2717 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
2718
2719 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2720
2721 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2722 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2723
2724 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
2725 }
2726
2727 VkResult anv_GetMemoryFdPropertiesKHR(
2728 VkDevice _device,
2729 VkExternalMemoryHandleTypeFlagBits handleType,
2730 int fd,
2731 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
2732 {
2733 ANV_FROM_HANDLE(anv_device, device, _device);
2734 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2735
2736 switch (handleType) {
2737 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
2738 /* dma-buf can be imported as any memory type */
2739 pMemoryFdProperties->memoryTypeBits =
2740 (1 << pdevice->memory.type_count) - 1;
2741 return VK_SUCCESS;
2742
2743 default:
2744 /* The valid usage section for this function says:
2745 *
2746 * "handleType must not be one of the handle types defined as
2747 * opaque."
2748 *
2749 * So opaque handle types fall into the default "unsupported" case.
2750 */
2751 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2752 }
2753 }
2754
2755 VkResult anv_GetMemoryHostPointerPropertiesEXT(
2756 VkDevice _device,
2757 VkExternalMemoryHandleTypeFlagBits handleType,
2758 const void* pHostPointer,
2759 VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties)
2760 {
2761 ANV_FROM_HANDLE(anv_device, device, _device);
2762
2763 assert(pMemoryHostPointerProperties->sType ==
2764 VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT);
2765
2766 switch (handleType) {
2767 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT: {
2768 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2769
2770 /* Host memory can be imported as any memory type. */
2771 pMemoryHostPointerProperties->memoryTypeBits =
2772 (1ull << pdevice->memory.type_count) - 1;
2773
2774 return VK_SUCCESS;
2775 }
2776 default:
2777 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
2778 }
2779 }
2780
2781 void anv_FreeMemory(
2782 VkDevice _device,
2783 VkDeviceMemory _mem,
2784 const VkAllocationCallbacks* pAllocator)
2785 {
2786 ANV_FROM_HANDLE(anv_device, device, _device);
2787 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
2788
2789 if (mem == NULL)
2790 return;
2791
2792 pthread_mutex_lock(&device->mutex);
2793 list_del(&mem->link);
2794 pthread_mutex_unlock(&device->mutex);
2795
2796 if (mem->map)
2797 anv_UnmapMemory(_device, _mem);
2798
2799 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2800
2801 #if defined(ANDROID) && ANDROID_API_LEVEL >= 26
2802 if (mem->ahw)
2803 AHardwareBuffer_release(mem->ahw);
2804 #endif
2805
2806 vk_free2(&device->alloc, pAllocator, mem);
2807 }
2808
2809 VkResult anv_MapMemory(
2810 VkDevice _device,
2811 VkDeviceMemory _memory,
2812 VkDeviceSize offset,
2813 VkDeviceSize size,
2814 VkMemoryMapFlags flags,
2815 void** ppData)
2816 {
2817 ANV_FROM_HANDLE(anv_device, device, _device);
2818 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2819
2820 if (mem == NULL) {
2821 *ppData = NULL;
2822 return VK_SUCCESS;
2823 }
2824
2825 if (mem->host_ptr) {
2826 *ppData = mem->host_ptr + offset;
2827 return VK_SUCCESS;
2828 }
2829
2830 if (size == VK_WHOLE_SIZE)
2831 size = mem->bo->size - offset;
2832
2833 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
2834 *
2835 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
2836 * assert(size != 0);
2837 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
2838 * equal to the size of the memory minus offset
2839 */
2840 assert(size > 0);
2841 assert(offset + size <= mem->bo->size);
2842
2843 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
2844 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
2845 * at a time is valid. We could just mmap up front and return an offset
2846 * pointer here, but that may exhaust virtual memory on 32 bit
2847 * userspace. */
2848
2849 uint32_t gem_flags = 0;
2850
2851 if (!device->info.has_llc &&
2852 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
2853 gem_flags |= I915_MMAP_WC;
2854
2855 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
2856 uint64_t map_offset = offset & ~4095ull;
2857 assert(offset >= map_offset);
2858 uint64_t map_size = (offset + size) - map_offset;
2859
2860 /* Let's map whole pages */
2861 map_size = align_u64(map_size, 4096);
2862
2863 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
2864 map_offset, map_size, gem_flags);
2865 if (map == MAP_FAILED)
2866 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
2867
2868 mem->map = map;
2869 mem->map_size = map_size;
2870
2871 *ppData = mem->map + (offset - map_offset);
2872
2873 return VK_SUCCESS;
2874 }
2875
2876 void anv_UnmapMemory(
2877 VkDevice _device,
2878 VkDeviceMemory _memory)
2879 {
2880 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2881
2882 if (mem == NULL || mem->host_ptr)
2883 return;
2884
2885 anv_gem_munmap(mem->map, mem->map_size);
2886
2887 mem->map = NULL;
2888 mem->map_size = 0;
2889 }
2890
2891 static void
2892 clflush_mapped_ranges(struct anv_device *device,
2893 uint32_t count,
2894 const VkMappedMemoryRange *ranges)
2895 {
2896 for (uint32_t i = 0; i < count; i++) {
2897 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
2898 if (ranges[i].offset >= mem->map_size)
2899 continue;
2900
2901 gen_clflush_range(mem->map + ranges[i].offset,
2902 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
2903 }
2904 }
2905
2906 VkResult anv_FlushMappedMemoryRanges(
2907 VkDevice _device,
2908 uint32_t memoryRangeCount,
2909 const VkMappedMemoryRange* pMemoryRanges)
2910 {
2911 ANV_FROM_HANDLE(anv_device, device, _device);
2912
2913 if (device->info.has_llc)
2914 return VK_SUCCESS;
2915
2916 /* Make sure the writes we're flushing have landed. */
2917 __builtin_ia32_mfence();
2918
2919 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2920
2921 return VK_SUCCESS;
2922 }
2923
2924 VkResult anv_InvalidateMappedMemoryRanges(
2925 VkDevice _device,
2926 uint32_t memoryRangeCount,
2927 const VkMappedMemoryRange* pMemoryRanges)
2928 {
2929 ANV_FROM_HANDLE(anv_device, device, _device);
2930
2931 if (device->info.has_llc)
2932 return VK_SUCCESS;
2933
2934 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
2935
2936 /* Make sure no reads get moved up above the invalidate. */
2937 __builtin_ia32_mfence();
2938
2939 return VK_SUCCESS;
2940 }
2941
2942 void anv_GetBufferMemoryRequirements(
2943 VkDevice _device,
2944 VkBuffer _buffer,
2945 VkMemoryRequirements* pMemoryRequirements)
2946 {
2947 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2948 ANV_FROM_HANDLE(anv_device, device, _device);
2949 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2950
2951 /* The Vulkan spec (git aaed022) says:
2952 *
2953 * memoryTypeBits is a bitfield and contains one bit set for every
2954 * supported memory type for the resource. The bit `1<<i` is set if and
2955 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
2956 * structure for the physical device is supported.
2957 */
2958 uint32_t memory_types = 0;
2959 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
2960 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
2961 if ((valid_usage & buffer->usage) == buffer->usage)
2962 memory_types |= (1u << i);
2963 }
2964
2965 /* Base alignment requirement of a cache line */
2966 uint32_t alignment = 16;
2967
2968 /* We need an alignment of 32 for pushing UBOs */
2969 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
2970 alignment = MAX2(alignment, 32);
2971
2972 pMemoryRequirements->size = buffer->size;
2973 pMemoryRequirements->alignment = alignment;
2974
2975 /* Storage and Uniform buffers should have their size aligned to
2976 * 32-bits to avoid boundary checks when last DWord is not complete.
2977 * This would ensure that not internal padding would be needed for
2978 * 16-bit types.
2979 */
2980 if (device->robust_buffer_access &&
2981 (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
2982 buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
2983 pMemoryRequirements->size = align_u64(buffer->size, 4);
2984
2985 pMemoryRequirements->memoryTypeBits = memory_types;
2986 }
2987
2988 void anv_GetBufferMemoryRequirements2(
2989 VkDevice _device,
2990 const VkBufferMemoryRequirementsInfo2* pInfo,
2991 VkMemoryRequirements2* pMemoryRequirements)
2992 {
2993 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
2994 &pMemoryRequirements->memoryRequirements);
2995
2996 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2997 switch (ext->sType) {
2998 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
2999 VkMemoryDedicatedRequirements *requirements = (void *)ext;
3000 requirements->prefersDedicatedAllocation = false;
3001 requirements->requiresDedicatedAllocation = false;
3002 break;
3003 }
3004
3005 default:
3006 anv_debug_ignored_stype(ext->sType);
3007 break;
3008 }
3009 }
3010 }
3011
3012 void anv_GetImageMemoryRequirements(
3013 VkDevice _device,
3014 VkImage _image,
3015 VkMemoryRequirements* pMemoryRequirements)
3016 {
3017 ANV_FROM_HANDLE(anv_image, image, _image);
3018 ANV_FROM_HANDLE(anv_device, device, _device);
3019 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
3020
3021 /* The Vulkan spec (git aaed022) says:
3022 *
3023 * memoryTypeBits is a bitfield and contains one bit set for every
3024 * supported memory type for the resource. The bit `1<<i` is set if and
3025 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
3026 * structure for the physical device is supported.
3027 *
3028 * All types are currently supported for images.
3029 */
3030 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
3031
3032 /* We must have image allocated or imported at this point. According to the
3033 * specification, external images must have been bound to memory before
3034 * calling GetImageMemoryRequirements.
3035 */
3036 assert(image->size > 0);
3037
3038 pMemoryRequirements->size = image->size;
3039 pMemoryRequirements->alignment = image->alignment;
3040 pMemoryRequirements->memoryTypeBits = memory_types;
3041 }
3042
3043 void anv_GetImageMemoryRequirements2(
3044 VkDevice _device,
3045 const VkImageMemoryRequirementsInfo2* pInfo,
3046 VkMemoryRequirements2* pMemoryRequirements)
3047 {
3048 ANV_FROM_HANDLE(anv_device, device, _device);
3049 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
3050
3051 anv_GetImageMemoryRequirements(_device, pInfo->image,
3052 &pMemoryRequirements->memoryRequirements);
3053
3054 vk_foreach_struct_const(ext, pInfo->pNext) {
3055 switch (ext->sType) {
3056 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
3057 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
3058 const VkImagePlaneMemoryRequirementsInfo *plane_reqs =
3059 (const VkImagePlaneMemoryRequirementsInfo *) ext;
3060 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
3061 plane_reqs->planeAspect);
3062
3063 assert(image->planes[plane].offset == 0);
3064
3065 /* The Vulkan spec (git aaed022) says:
3066 *
3067 * memoryTypeBits is a bitfield and contains one bit set for every
3068 * supported memory type for the resource. The bit `1<<i` is set
3069 * if and only if the memory type `i` in the
3070 * VkPhysicalDeviceMemoryProperties structure for the physical
3071 * device is supported.
3072 *
3073 * All types are currently supported for images.
3074 */
3075 pMemoryRequirements->memoryRequirements.memoryTypeBits =
3076 (1ull << pdevice->memory.type_count) - 1;
3077
3078 /* We must have image allocated or imported at this point. According to the
3079 * specification, external images must have been bound to memory before
3080 * calling GetImageMemoryRequirements.
3081 */
3082 assert(image->planes[plane].size > 0);
3083
3084 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
3085 pMemoryRequirements->memoryRequirements.alignment =
3086 image->planes[plane].alignment;
3087 break;
3088 }
3089
3090 default:
3091 anv_debug_ignored_stype(ext->sType);
3092 break;
3093 }
3094 }
3095
3096 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3097 switch (ext->sType) {
3098 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3099 VkMemoryDedicatedRequirements *requirements = (void *)ext;
3100 if (image->needs_set_tiling || image->external_format) {
3101 /* If we need to set the tiling for external consumers, we need a
3102 * dedicated allocation.
3103 *
3104 * See also anv_AllocateMemory.
3105 */
3106 requirements->prefersDedicatedAllocation = true;
3107 requirements->requiresDedicatedAllocation = true;
3108 } else {
3109 requirements->prefersDedicatedAllocation = false;
3110 requirements->requiresDedicatedAllocation = false;
3111 }
3112 break;
3113 }
3114
3115 default:
3116 anv_debug_ignored_stype(ext->sType);
3117 break;
3118 }
3119 }
3120 }
3121
3122 void anv_GetImageSparseMemoryRequirements(
3123 VkDevice device,
3124 VkImage image,
3125 uint32_t* pSparseMemoryRequirementCount,
3126 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
3127 {
3128 *pSparseMemoryRequirementCount = 0;
3129 }
3130
3131 void anv_GetImageSparseMemoryRequirements2(
3132 VkDevice device,
3133 const VkImageSparseMemoryRequirementsInfo2* pInfo,
3134 uint32_t* pSparseMemoryRequirementCount,
3135 VkSparseImageMemoryRequirements2* pSparseMemoryRequirements)
3136 {
3137 *pSparseMemoryRequirementCount = 0;
3138 }
3139
3140 void anv_GetDeviceMemoryCommitment(
3141 VkDevice device,
3142 VkDeviceMemory memory,
3143 VkDeviceSize* pCommittedMemoryInBytes)
3144 {
3145 *pCommittedMemoryInBytes = 0;
3146 }
3147
3148 static void
3149 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
3150 {
3151 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
3152 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
3153
3154 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
3155
3156 if (mem) {
3157 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
3158 buffer->address = (struct anv_address) {
3159 .bo = mem->bo,
3160 .offset = pBindInfo->memoryOffset,
3161 };
3162 } else {
3163 buffer->address = ANV_NULL_ADDRESS;
3164 }
3165 }
3166
3167 VkResult anv_BindBufferMemory(
3168 VkDevice device,
3169 VkBuffer buffer,
3170 VkDeviceMemory memory,
3171 VkDeviceSize memoryOffset)
3172 {
3173 anv_bind_buffer_memory(
3174 &(VkBindBufferMemoryInfo) {
3175 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
3176 .buffer = buffer,
3177 .memory = memory,
3178 .memoryOffset = memoryOffset,
3179 });
3180
3181 return VK_SUCCESS;
3182 }
3183
3184 VkResult anv_BindBufferMemory2(
3185 VkDevice device,
3186 uint32_t bindInfoCount,
3187 const VkBindBufferMemoryInfo* pBindInfos)
3188 {
3189 for (uint32_t i = 0; i < bindInfoCount; i++)
3190 anv_bind_buffer_memory(&pBindInfos[i]);
3191
3192 return VK_SUCCESS;
3193 }
3194
3195 VkResult anv_QueueBindSparse(
3196 VkQueue _queue,
3197 uint32_t bindInfoCount,
3198 const VkBindSparseInfo* pBindInfo,
3199 VkFence fence)
3200 {
3201 ANV_FROM_HANDLE(anv_queue, queue, _queue);
3202 if (anv_device_is_lost(queue->device))
3203 return VK_ERROR_DEVICE_LOST;
3204
3205 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
3206 }
3207
3208 // Event functions
3209
3210 VkResult anv_CreateEvent(
3211 VkDevice _device,
3212 const VkEventCreateInfo* pCreateInfo,
3213 const VkAllocationCallbacks* pAllocator,
3214 VkEvent* pEvent)
3215 {
3216 ANV_FROM_HANDLE(anv_device, device, _device);
3217 struct anv_state state;
3218 struct anv_event *event;
3219
3220 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
3221
3222 state = anv_state_pool_alloc(&device->dynamic_state_pool,
3223 sizeof(*event), 8);
3224 event = state.map;
3225 event->state = state;
3226 event->semaphore = VK_EVENT_RESET;
3227
3228 if (!device->info.has_llc) {
3229 /* Make sure the writes we're flushing have landed. */
3230 __builtin_ia32_mfence();
3231 __builtin_ia32_clflush(event);
3232 }
3233
3234 *pEvent = anv_event_to_handle(event);
3235
3236 return VK_SUCCESS;
3237 }
3238
3239 void anv_DestroyEvent(
3240 VkDevice _device,
3241 VkEvent _event,
3242 const VkAllocationCallbacks* pAllocator)
3243 {
3244 ANV_FROM_HANDLE(anv_device, device, _device);
3245 ANV_FROM_HANDLE(anv_event, event, _event);
3246
3247 if (!event)
3248 return;
3249
3250 anv_state_pool_free(&device->dynamic_state_pool, event->state);
3251 }
3252
3253 VkResult anv_GetEventStatus(
3254 VkDevice _device,
3255 VkEvent _event)
3256 {
3257 ANV_FROM_HANDLE(anv_device, device, _device);
3258 ANV_FROM_HANDLE(anv_event, event, _event);
3259
3260 if (anv_device_is_lost(device))
3261 return VK_ERROR_DEVICE_LOST;
3262
3263 if (!device->info.has_llc) {
3264 /* Invalidate read cache before reading event written by GPU. */
3265 __builtin_ia32_clflush(event);
3266 __builtin_ia32_mfence();
3267
3268 }
3269
3270 return event->semaphore;
3271 }
3272
3273 VkResult anv_SetEvent(
3274 VkDevice _device,
3275 VkEvent _event)
3276 {
3277 ANV_FROM_HANDLE(anv_device, device, _device);
3278 ANV_FROM_HANDLE(anv_event, event, _event);
3279
3280 event->semaphore = VK_EVENT_SET;
3281
3282 if (!device->info.has_llc) {
3283 /* Make sure the writes we're flushing have landed. */
3284 __builtin_ia32_mfence();
3285 __builtin_ia32_clflush(event);
3286 }
3287
3288 return VK_SUCCESS;
3289 }
3290
3291 VkResult anv_ResetEvent(
3292 VkDevice _device,
3293 VkEvent _event)
3294 {
3295 ANV_FROM_HANDLE(anv_device, device, _device);
3296 ANV_FROM_HANDLE(anv_event, event, _event);
3297
3298 event->semaphore = VK_EVENT_RESET;
3299
3300 if (!device->info.has_llc) {
3301 /* Make sure the writes we're flushing have landed. */
3302 __builtin_ia32_mfence();
3303 __builtin_ia32_clflush(event);
3304 }
3305
3306 return VK_SUCCESS;
3307 }
3308
3309 // Buffer functions
3310
3311 VkResult anv_CreateBuffer(
3312 VkDevice _device,
3313 const VkBufferCreateInfo* pCreateInfo,
3314 const VkAllocationCallbacks* pAllocator,
3315 VkBuffer* pBuffer)
3316 {
3317 ANV_FROM_HANDLE(anv_device, device, _device);
3318 struct anv_buffer *buffer;
3319
3320 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
3321
3322 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
3323 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3324 if (buffer == NULL)
3325 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3326
3327 buffer->size = pCreateInfo->size;
3328 buffer->usage = pCreateInfo->usage;
3329 buffer->address = ANV_NULL_ADDRESS;
3330
3331 *pBuffer = anv_buffer_to_handle(buffer);
3332
3333 return VK_SUCCESS;
3334 }
3335
3336 void anv_DestroyBuffer(
3337 VkDevice _device,
3338 VkBuffer _buffer,
3339 const VkAllocationCallbacks* pAllocator)
3340 {
3341 ANV_FROM_HANDLE(anv_device, device, _device);
3342 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3343
3344 if (!buffer)
3345 return;
3346
3347 vk_free2(&device->alloc, pAllocator, buffer);
3348 }
3349
3350 VkDeviceAddress anv_GetBufferDeviceAddressEXT(
3351 VkDevice device,
3352 const VkBufferDeviceAddressInfoEXT* pInfo)
3353 {
3354 ANV_FROM_HANDLE(anv_buffer, buffer, pInfo->buffer);
3355
3356 assert(buffer->address.bo->flags & EXEC_OBJECT_PINNED);
3357
3358 return anv_address_physical(buffer->address);
3359 }
3360
3361 void
3362 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
3363 enum isl_format format,
3364 struct anv_address address,
3365 uint32_t range, uint32_t stride)
3366 {
3367 isl_buffer_fill_state(&device->isl_dev, state.map,
3368 .address = anv_address_physical(address),
3369 .mocs = device->default_mocs,
3370 .size_B = range,
3371 .format = format,
3372 .swizzle = ISL_SWIZZLE_IDENTITY,
3373 .stride_B = stride);
3374 }
3375
3376 void anv_DestroySampler(
3377 VkDevice _device,
3378 VkSampler _sampler,
3379 const VkAllocationCallbacks* pAllocator)
3380 {
3381 ANV_FROM_HANDLE(anv_device, device, _device);
3382 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
3383
3384 if (!sampler)
3385 return;
3386
3387 vk_free2(&device->alloc, pAllocator, sampler);
3388 }
3389
3390 VkResult anv_CreateFramebuffer(
3391 VkDevice _device,
3392 const VkFramebufferCreateInfo* pCreateInfo,
3393 const VkAllocationCallbacks* pAllocator,
3394 VkFramebuffer* pFramebuffer)
3395 {
3396 ANV_FROM_HANDLE(anv_device, device, _device);
3397 struct anv_framebuffer *framebuffer;
3398
3399 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
3400
3401 size_t size = sizeof(*framebuffer) +
3402 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
3403 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
3404 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3405 if (framebuffer == NULL)
3406 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3407
3408 framebuffer->attachment_count = pCreateInfo->attachmentCount;
3409 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
3410 VkImageView _iview = pCreateInfo->pAttachments[i];
3411 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
3412 }
3413
3414 framebuffer->width = pCreateInfo->width;
3415 framebuffer->height = pCreateInfo->height;
3416 framebuffer->layers = pCreateInfo->layers;
3417
3418 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
3419
3420 return VK_SUCCESS;
3421 }
3422
3423 void anv_DestroyFramebuffer(
3424 VkDevice _device,
3425 VkFramebuffer _fb,
3426 const VkAllocationCallbacks* pAllocator)
3427 {
3428 ANV_FROM_HANDLE(anv_device, device, _device);
3429 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
3430
3431 if (!fb)
3432 return;
3433
3434 vk_free2(&device->alloc, pAllocator, fb);
3435 }
3436
3437 static const VkTimeDomainEXT anv_time_domains[] = {
3438 VK_TIME_DOMAIN_DEVICE_EXT,
3439 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
3440 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
3441 };
3442
3443 VkResult anv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
3444 VkPhysicalDevice physicalDevice,
3445 uint32_t *pTimeDomainCount,
3446 VkTimeDomainEXT *pTimeDomains)
3447 {
3448 int d;
3449 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
3450
3451 for (d = 0; d < ARRAY_SIZE(anv_time_domains); d++) {
3452 vk_outarray_append(&out, i) {
3453 *i = anv_time_domains[d];
3454 }
3455 }
3456
3457 return vk_outarray_status(&out);
3458 }
3459
3460 static uint64_t
3461 anv_clock_gettime(clockid_t clock_id)
3462 {
3463 struct timespec current;
3464 int ret;
3465
3466 ret = clock_gettime(clock_id, &current);
3467 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
3468 ret = clock_gettime(CLOCK_MONOTONIC, &current);
3469 if (ret < 0)
3470 return 0;
3471
3472 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
3473 }
3474
3475 #define TIMESTAMP 0x2358
3476
3477 VkResult anv_GetCalibratedTimestampsEXT(
3478 VkDevice _device,
3479 uint32_t timestampCount,
3480 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
3481 uint64_t *pTimestamps,
3482 uint64_t *pMaxDeviation)
3483 {
3484 ANV_FROM_HANDLE(anv_device, device, _device);
3485 uint64_t timestamp_frequency = device->info.timestamp_frequency;
3486 int ret;
3487 int d;
3488 uint64_t begin, end;
3489 uint64_t max_clock_period = 0;
3490
3491 begin = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
3492
3493 for (d = 0; d < timestampCount; d++) {
3494 switch (pTimestampInfos[d].timeDomain) {
3495 case VK_TIME_DOMAIN_DEVICE_EXT:
3496 ret = anv_gem_reg_read(device, TIMESTAMP | 1,
3497 &pTimestamps[d]);
3498
3499 if (ret != 0) {
3500 return anv_device_set_lost(device, "Failed to read the TIMESTAMP "
3501 "register: %m");
3502 }
3503 uint64_t device_period = DIV_ROUND_UP(1000000000, timestamp_frequency);
3504 max_clock_period = MAX2(max_clock_period, device_period);
3505 break;
3506 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
3507 pTimestamps[d] = anv_clock_gettime(CLOCK_MONOTONIC);
3508 max_clock_period = MAX2(max_clock_period, 1);
3509 break;
3510
3511 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
3512 pTimestamps[d] = begin;
3513 break;
3514 default:
3515 pTimestamps[d] = 0;
3516 break;
3517 }
3518 }
3519
3520 end = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
3521
3522 /*
3523 * The maximum deviation is the sum of the interval over which we
3524 * perform the sampling and the maximum period of any sampled
3525 * clock. That's because the maximum skew between any two sampled
3526 * clock edges is when the sampled clock with the largest period is
3527 * sampled at the end of that period but right at the beginning of the
3528 * sampling interval and some other clock is sampled right at the
3529 * begining of its sampling period and right at the end of the
3530 * sampling interval. Let's assume the GPU has the longest clock
3531 * period and that the application is sampling GPU and monotonic:
3532 *
3533 * s e
3534 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
3535 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
3536 *
3537 * g
3538 * 0 1 2 3
3539 * GPU -----_____-----_____-----_____-----_____
3540 *
3541 * m
3542 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
3543 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
3544 *
3545 * Interval <----------------->
3546 * Deviation <-------------------------->
3547 *
3548 * s = read(raw) 2
3549 * g = read(GPU) 1
3550 * m = read(monotonic) 2
3551 * e = read(raw) b
3552 *
3553 * We round the sample interval up by one tick to cover sampling error
3554 * in the interval clock
3555 */
3556
3557 uint64_t sample_interval = end - begin + 1;
3558
3559 *pMaxDeviation = sample_interval + max_clock_period;
3560
3561 return VK_SUCCESS;
3562 }
3563
3564 /* vk_icd.h does not declare this function, so we declare it here to
3565 * suppress Wmissing-prototypes.
3566 */
3567 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
3568 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
3569
3570 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
3571 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
3572 {
3573 /* For the full details on loader interface versioning, see
3574 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
3575 * What follows is a condensed summary, to help you navigate the large and
3576 * confusing official doc.
3577 *
3578 * - Loader interface v0 is incompatible with later versions. We don't
3579 * support it.
3580 *
3581 * - In loader interface v1:
3582 * - The first ICD entrypoint called by the loader is
3583 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
3584 * entrypoint.
3585 * - The ICD must statically expose no other Vulkan symbol unless it is
3586 * linked with -Bsymbolic.
3587 * - Each dispatchable Vulkan handle created by the ICD must be
3588 * a pointer to a struct whose first member is VK_LOADER_DATA. The
3589 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
3590 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
3591 * vkDestroySurfaceKHR(). The ICD must be capable of working with
3592 * such loader-managed surfaces.
3593 *
3594 * - Loader interface v2 differs from v1 in:
3595 * - The first ICD entrypoint called by the loader is
3596 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
3597 * statically expose this entrypoint.
3598 *
3599 * - Loader interface v3 differs from v2 in:
3600 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
3601 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
3602 * because the loader no longer does so.
3603 */
3604 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
3605 return VK_SUCCESS;
3606 }