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