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