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