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