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