f670be5cc5ccafe24e88b5de5c6ca4e659859c67
[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 <unistd.h>
29 #include <fcntl.h>
30 #include "drm-uapi/drm_fourcc.h"
31 #include "drm-uapi/drm.h"
32 #include <xf86drm.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/os_misc.h"
41 #include "util/u_atomic.h"
42 #include "util/u_string.h"
43 #include "util/driconf.h"
44 #include "git_sha1.h"
45 #include "vk_util.h"
46 #include "common/gen_aux_map.h"
47 #include "common/gen_defines.h"
48 #include "compiler/glsl_types.h"
49
50 #include "genxml/gen7_pack.h"
51
52 static const char anv_dri_options_xml[] =
53 DRI_CONF_BEGIN
54 DRI_CONF_SECTION_PERFORMANCE
55 DRI_CONF_VK_X11_OVERRIDE_MIN_IMAGE_COUNT(0)
56 DRI_CONF_VK_X11_STRICT_IMAGE_COUNT("false")
57 DRI_CONF_SECTION_END
58
59 DRI_CONF_SECTION_DEBUG
60 DRI_CONF_ALWAYS_FLUSH_CACHE("false")
61 DRI_CONF_VK_WSI_FORCE_BGRA8_UNORM_FIRST("false")
62 DRI_CONF_SECTION_END
63 DRI_CONF_END;
64
65 /* This is probably far to big but it reflects the max size used for messages
66 * in OpenGLs KHR_debug.
67 */
68 #define MAX_DEBUG_MESSAGE_LENGTH 4096
69
70 /* Render engine timestamp register */
71 #define TIMESTAMP 0x2358
72
73 static void
74 compiler_debug_log(void *data, const char *fmt, ...)
75 {
76 char str[MAX_DEBUG_MESSAGE_LENGTH];
77 struct anv_device *device = (struct anv_device *)data;
78 struct anv_instance *instance = device->physical->instance;
79
80 if (list_is_empty(&instance->debug_report_callbacks.callbacks))
81 return;
82
83 va_list args;
84 va_start(args, fmt);
85 (void) vsnprintf(str, MAX_DEBUG_MESSAGE_LENGTH, fmt, args);
86 va_end(args);
87
88 vk_debug_report(&instance->debug_report_callbacks,
89 VK_DEBUG_REPORT_DEBUG_BIT_EXT,
90 VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT,
91 0, 0, 0, "anv", str);
92 }
93
94 static void
95 compiler_perf_log(void *data, const char *fmt, ...)
96 {
97 va_list args;
98 va_start(args, fmt);
99
100 if (unlikely(INTEL_DEBUG & DEBUG_PERF))
101 intel_logd_v(fmt, args);
102
103 va_end(args);
104 }
105
106 static uint64_t
107 anv_compute_heap_size(int fd, uint64_t gtt_size)
108 {
109 /* Query the total ram from the system */
110 uint64_t total_ram;
111 if (!os_get_total_physical_memory(&total_ram))
112 return 0;
113
114 /* We don't want to burn too much ram with the GPU. If the user has 4GiB
115 * or less, we use at most half. If they have more than 4GiB, we use 3/4.
116 */
117 uint64_t available_ram;
118 if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
119 available_ram = total_ram / 2;
120 else
121 available_ram = total_ram * 3 / 4;
122
123 /* We also want to leave some padding for things we allocate in the driver,
124 * so don't go over 3/4 of the GTT either.
125 */
126 uint64_t available_gtt = gtt_size * 3 / 4;
127
128 return MIN2(available_ram, available_gtt);
129 }
130
131 static VkResult
132 anv_physical_device_init_heaps(struct anv_physical_device *device, int fd)
133 {
134 if (anv_gem_get_context_param(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE,
135 &device->gtt_size) == -1) {
136 /* If, for whatever reason, we can't actually get the GTT size from the
137 * kernel (too old?) fall back to the aperture size.
138 */
139 anv_perf_warn(NULL, NULL,
140 "Failed to get I915_CONTEXT_PARAM_GTT_SIZE: %m");
141
142 if (gen_get_aperture_size(fd, &device->gtt_size) == -1) {
143 return vk_errorfi(device->instance, NULL,
144 VK_ERROR_INITIALIZATION_FAILED,
145 "failed to get aperture size: %m");
146 }
147 }
148
149 /* We only allow 48-bit addresses with softpin because knowing the actual
150 * address is required for the vertex cache flush workaround.
151 */
152 device->supports_48bit_addresses = (device->info.gen >= 8) &&
153 device->has_softpin &&
154 device->gtt_size > (4ULL << 30 /* GiB */);
155
156 uint64_t heap_size = anv_compute_heap_size(fd, device->gtt_size);
157
158 if (heap_size > (2ull << 30) && !device->supports_48bit_addresses) {
159 /* When running with an overridden PCI ID, we may get a GTT size from
160 * the kernel that is greater than 2 GiB but the execbuf check for 48bit
161 * address support can still fail. Just clamp the address space size to
162 * 2 GiB if we don't have 48-bit support.
163 */
164 intel_logw("%s:%d: The kernel reported a GTT size larger than 2 GiB but "
165 "not support for 48-bit addresses",
166 __FILE__, __LINE__);
167 heap_size = 2ull << 30;
168 }
169
170 device->memory.heap_count = 1;
171 device->memory.heaps[0] = (struct anv_memory_heap) {
172 .size = heap_size,
173 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
174 };
175
176 uint32_t type_count = 0;
177 for (uint32_t heap = 0; heap < device->memory.heap_count; heap++) {
178 if (device->info.has_llc) {
179 /* Big core GPUs share LLC with the CPU and thus one memory type can be
180 * both cached and coherent at the same time.
181 */
182 device->memory.types[type_count++] = (struct anv_memory_type) {
183 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
184 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
185 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
186 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
187 .heapIndex = heap,
188 };
189 } else {
190 /* The spec requires that we expose a host-visible, coherent memory
191 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
192 * to give the application a choice between cached, but not coherent and
193 * coherent but uncached (WC though).
194 */
195 device->memory.types[type_count++] = (struct anv_memory_type) {
196 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
197 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
198 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
199 .heapIndex = heap,
200 };
201 device->memory.types[type_count++] = (struct anv_memory_type) {
202 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
203 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
204 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
205 .heapIndex = heap,
206 };
207 }
208 }
209 device->memory.type_count = type_count;
210
211 return VK_SUCCESS;
212 }
213
214 static VkResult
215 anv_physical_device_init_uuids(struct anv_physical_device *device)
216 {
217 const struct build_id_note *note =
218 build_id_find_nhdr_for_addr(anv_physical_device_init_uuids);
219 if (!note) {
220 return vk_errorfi(device->instance, NULL,
221 VK_ERROR_INITIALIZATION_FAILED,
222 "Failed to find build-id");
223 }
224
225 unsigned build_id_len = build_id_length(note);
226 if (build_id_len < 20) {
227 return vk_errorfi(device->instance, NULL,
228 VK_ERROR_INITIALIZATION_FAILED,
229 "build-id too short. It needs to be a SHA");
230 }
231
232 memcpy(device->driver_build_sha1, build_id_data(note), 20);
233
234 struct mesa_sha1 sha1_ctx;
235 uint8_t sha1[20];
236 STATIC_ASSERT(VK_UUID_SIZE <= sizeof(sha1));
237
238 /* The pipeline cache UUID is used for determining when a pipeline cache is
239 * invalid. It needs both a driver build and the PCI ID of the device.
240 */
241 _mesa_sha1_init(&sha1_ctx);
242 _mesa_sha1_update(&sha1_ctx, build_id_data(note), build_id_len);
243 _mesa_sha1_update(&sha1_ctx, &device->info.chipset_id,
244 sizeof(device->info.chipset_id));
245 _mesa_sha1_update(&sha1_ctx, &device->always_use_bindless,
246 sizeof(device->always_use_bindless));
247 _mesa_sha1_update(&sha1_ctx, &device->has_a64_buffer_access,
248 sizeof(device->has_a64_buffer_access));
249 _mesa_sha1_update(&sha1_ctx, &device->has_bindless_images,
250 sizeof(device->has_bindless_images));
251 _mesa_sha1_update(&sha1_ctx, &device->has_bindless_samplers,
252 sizeof(device->has_bindless_samplers));
253 _mesa_sha1_final(&sha1_ctx, sha1);
254 memcpy(device->pipeline_cache_uuid, sha1, VK_UUID_SIZE);
255
256 /* The driver UUID is used for determining sharability of images and memory
257 * between two Vulkan instances in separate processes. People who want to
258 * share memory need to also check the device UUID (below) so all this
259 * needs to be is the build-id.
260 */
261 memcpy(device->driver_uuid, build_id_data(note), VK_UUID_SIZE);
262
263 /* The device UUID uniquely identifies the given device within the machine.
264 * Since we never have more than one device, this doesn't need to be a real
265 * UUID. However, on the off-chance that someone tries to use this to
266 * cache pre-tiled images or something of the like, we use the PCI ID and
267 * some bits of ISL info to ensure that this is safe.
268 */
269 _mesa_sha1_init(&sha1_ctx);
270 _mesa_sha1_update(&sha1_ctx, &device->info.chipset_id,
271 sizeof(device->info.chipset_id));
272 _mesa_sha1_update(&sha1_ctx, &device->isl_dev.has_bit6_swizzling,
273 sizeof(device->isl_dev.has_bit6_swizzling));
274 _mesa_sha1_final(&sha1_ctx, sha1);
275 memcpy(device->device_uuid, sha1, VK_UUID_SIZE);
276
277 return VK_SUCCESS;
278 }
279
280 static void
281 anv_physical_device_init_disk_cache(struct anv_physical_device *device)
282 {
283 #ifdef ENABLE_SHADER_CACHE
284 char renderer[10];
285 ASSERTED int len = snprintf(renderer, sizeof(renderer), "anv_%04x",
286 device->info.chipset_id);
287 assert(len == sizeof(renderer) - 2);
288
289 char timestamp[41];
290 _mesa_sha1_format(timestamp, device->driver_build_sha1);
291
292 const uint64_t driver_flags =
293 brw_get_compiler_config_value(device->compiler);
294 device->disk_cache = disk_cache_create(renderer, timestamp, driver_flags);
295 #else
296 device->disk_cache = NULL;
297 #endif
298 }
299
300 static void
301 anv_physical_device_free_disk_cache(struct anv_physical_device *device)
302 {
303 #ifdef ENABLE_SHADER_CACHE
304 if (device->disk_cache)
305 disk_cache_destroy(device->disk_cache);
306 #else
307 assert(device->disk_cache == NULL);
308 #endif
309 }
310
311 static uint64_t
312 get_available_system_memory()
313 {
314 char *meminfo = os_read_file("/proc/meminfo", NULL);
315 if (!meminfo)
316 return 0;
317
318 char *str = strstr(meminfo, "MemAvailable:");
319 if (!str) {
320 free(meminfo);
321 return 0;
322 }
323
324 uint64_t kb_mem_available;
325 if (sscanf(str, "MemAvailable: %" PRIx64, &kb_mem_available) == 1) {
326 free(meminfo);
327 return kb_mem_available << 10;
328 }
329
330 free(meminfo);
331 return 0;
332 }
333
334 static VkResult
335 anv_physical_device_try_create(struct anv_instance *instance,
336 drmDevicePtr drm_device,
337 struct anv_physical_device **device_out)
338 {
339 const char *primary_path = drm_device->nodes[DRM_NODE_PRIMARY];
340 const char *path = drm_device->nodes[DRM_NODE_RENDER];
341 VkResult result;
342 int fd;
343 int master_fd = -1;
344
345 brw_process_intel_debug_variable();
346
347 fd = open(path, O_RDWR | O_CLOEXEC);
348 if (fd < 0)
349 return vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
350
351 struct gen_device_info devinfo;
352 if (!gen_get_device_info_from_fd(fd, &devinfo)) {
353 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
354 goto fail_fd;
355 }
356
357 const char *device_name = gen_get_device_name(devinfo.chipset_id);
358
359 if (devinfo.is_haswell) {
360 intel_logw("Haswell Vulkan support is incomplete");
361 } else if (devinfo.gen == 7 && !devinfo.is_baytrail) {
362 intel_logw("Ivy Bridge Vulkan support is incomplete");
363 } else if (devinfo.gen == 7 && devinfo.is_baytrail) {
364 intel_logw("Bay Trail Vulkan support is incomplete");
365 } else if (devinfo.gen >= 8 && devinfo.gen <= 11) {
366 /* Gen8-11 fully supported */
367 } else if (devinfo.gen == 12) {
368 intel_logw("Vulkan is not yet fully supported on gen12");
369 } else {
370 result = vk_errorfi(instance, NULL, VK_ERROR_INCOMPATIBLE_DRIVER,
371 "Vulkan not yet supported on %s", device_name);
372 goto fail_fd;
373 }
374
375 struct anv_physical_device *device =
376 vk_alloc(&instance->alloc, sizeof(*device), 8,
377 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
378 if (device == NULL) {
379 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
380 goto fail_fd;
381 }
382
383 vk_object_base_init(NULL, &device->base, VK_OBJECT_TYPE_PHYSICAL_DEVICE);
384 device->instance = instance;
385
386 assert(strlen(path) < ARRAY_SIZE(device->path));
387 snprintf(device->path, ARRAY_SIZE(device->path), "%s", path);
388
389 device->info = devinfo;
390 device->name = device_name;
391
392 device->no_hw = device->info.no_hw;
393 if (getenv("INTEL_NO_HW") != NULL)
394 device->no_hw = true;
395
396 device->pci_info.domain = drm_device->businfo.pci->domain;
397 device->pci_info.bus = drm_device->businfo.pci->bus;
398 device->pci_info.device = drm_device->businfo.pci->dev;
399 device->pci_info.function = drm_device->businfo.pci->func;
400
401 device->cmd_parser_version = -1;
402 if (device->info.gen == 7) {
403 device->cmd_parser_version =
404 anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
405 if (device->cmd_parser_version == -1) {
406 result = vk_errorfi(device->instance, NULL,
407 VK_ERROR_INITIALIZATION_FAILED,
408 "failed to get command parser version");
409 goto fail_alloc;
410 }
411 }
412
413 if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
414 result = vk_errorfi(device->instance, NULL,
415 VK_ERROR_INITIALIZATION_FAILED,
416 "kernel missing gem wait");
417 goto fail_alloc;
418 }
419
420 if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
421 result = vk_errorfi(device->instance, NULL,
422 VK_ERROR_INITIALIZATION_FAILED,
423 "kernel missing execbuf2");
424 goto fail_alloc;
425 }
426
427 if (!device->info.has_llc &&
428 anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
429 result = vk_errorfi(device->instance, NULL,
430 VK_ERROR_INITIALIZATION_FAILED,
431 "kernel missing wc mmap");
432 goto fail_alloc;
433 }
434
435 device->has_softpin = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_SOFTPIN);
436 device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
437 device->has_exec_capture = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_CAPTURE);
438 device->has_exec_fence = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE);
439 device->has_syncobj = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_FENCE_ARRAY);
440 device->has_syncobj_wait = device->has_syncobj &&
441 anv_gem_supports_syncobj_wait(fd);
442 device->has_syncobj_wait_available =
443 anv_gem_get_drm_cap(fd, DRM_CAP_SYNCOBJ_TIMELINE) != 0;
444
445 device->has_context_priority = anv_gem_has_context_priority(fd);
446
447 result = anv_physical_device_init_heaps(device, fd);
448 if (result != VK_SUCCESS)
449 goto fail_alloc;
450
451 device->use_softpin = device->has_softpin &&
452 device->supports_48bit_addresses;
453
454 device->has_context_isolation =
455 anv_gem_get_param(fd, I915_PARAM_HAS_CONTEXT_ISOLATION);
456
457 device->has_exec_timeline =
458 anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_TIMELINE_FENCES);
459 if (env_var_as_boolean("ANV_QUEUE_THREAD_DISABLE", false))
460 device->has_exec_timeline = false;
461
462 device->has_thread_submit =
463 device->has_syncobj_wait_available && device->has_exec_timeline;
464
465 device->always_use_bindless =
466 env_var_as_boolean("ANV_ALWAYS_BINDLESS", false);
467
468 device->use_call_secondary =
469 device->use_softpin &&
470 !env_var_as_boolean("ANV_DISABLE_SECONDARY_CMD_BUFFER_CALLS", false);
471
472 /* We first got the A64 messages on broadwell and we can only use them if
473 * we can pass addresses directly into the shader which requires softpin.
474 */
475 device->has_a64_buffer_access = device->info.gen >= 8 &&
476 device->use_softpin;
477
478 /* We first get bindless image access on Skylake and we can only really do
479 * it if we don't have any relocations so we need softpin.
480 */
481 device->has_bindless_images = device->info.gen >= 9 &&
482 device->use_softpin;
483
484 /* We've had bindless samplers since Ivy Bridge (forever in Vulkan terms)
485 * because it's just a matter of setting the sampler address in the sample
486 * message header. However, we've not bothered to wire it up for vec4 so
487 * we leave it disabled on gen7.
488 */
489 device->has_bindless_samplers = device->info.gen >= 8;
490
491 device->has_implicit_ccs = device->info.has_aux_map;
492
493 /* Check if we can read the GPU timestamp register from the CPU */
494 uint64_t u64_ignore;
495 device->has_reg_timestamp = anv_gem_reg_read(fd, TIMESTAMP | I915_REG_READ_8B_WA,
496 &u64_ignore) == 0;
497
498 device->has_mem_available = get_available_system_memory() != 0;
499
500 device->always_flush_cache =
501 driQueryOptionb(&instance->dri_options, "always_flush_cache");
502
503 device->has_mmap_offset =
504 anv_gem_get_param(fd, I915_PARAM_MMAP_GTT_VERSION) >= 4;
505
506 /* GENs prior to 8 do not support EU/Subslice info */
507 if (device->info.gen >= 8) {
508 device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
509 device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
510
511 /* Without this information, we cannot get the right Braswell
512 * brandstrings, and we have to use conservative numbers for GPGPU on
513 * many platforms, but otherwise, things will just work.
514 */
515 if (device->subslice_total < 1 || device->eu_total < 1) {
516 intel_logw("Kernel 4.1 required to properly query GPU properties");
517 }
518 } else if (device->info.gen == 7) {
519 device->subslice_total = 1 << (device->info.gt - 1);
520 }
521
522 if (device->info.is_cherryview &&
523 device->subslice_total > 0 && device->eu_total > 0) {
524 /* Logical CS threads = EUs per subslice * num threads per EU */
525 uint32_t max_cs_threads =
526 device->eu_total / device->subslice_total * device->info.num_thread_per_eu;
527
528 /* Fuse configurations may give more threads than expected, never less. */
529 if (max_cs_threads > device->info.max_cs_threads)
530 device->info.max_cs_threads = max_cs_threads;
531 }
532
533 device->compiler = brw_compiler_create(NULL, &device->info);
534 if (device->compiler == NULL) {
535 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
536 goto fail_alloc;
537 }
538 device->compiler->shader_debug_log = compiler_debug_log;
539 device->compiler->shader_perf_log = compiler_perf_log;
540 device->compiler->supports_pull_constants = false;
541 device->compiler->constant_buffer_0_is_relative =
542 device->info.gen < 8 || !device->has_context_isolation;
543 device->compiler->supports_shader_constants = true;
544 device->compiler->compact_params = false;
545
546 /* Broadwell PRM says:
547 *
548 * "Before Gen8, there was a historical configuration control field to
549 * swizzle address bit[6] for in X/Y tiling modes. This was set in three
550 * different places: TILECTL[1:0], ARB_MODE[5:4], and
551 * DISP_ARB_CTL[14:13].
552 *
553 * For Gen8 and subsequent generations, the swizzle fields are all
554 * reserved, and the CPU's memory controller performs all address
555 * swizzling modifications."
556 */
557 bool swizzled =
558 device->info.gen < 8 && anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
559
560 isl_device_init(&device->isl_dev, &device->info, swizzled);
561
562 result = anv_physical_device_init_uuids(device);
563 if (result != VK_SUCCESS)
564 goto fail_compiler;
565
566 anv_physical_device_init_disk_cache(device);
567
568 if (instance->enabled_extensions.KHR_display) {
569 master_fd = open(primary_path, O_RDWR | O_CLOEXEC);
570 if (master_fd >= 0) {
571 /* prod the device with a GETPARAM call which will fail if
572 * we don't have permission to even render on this device
573 */
574 if (anv_gem_get_param(master_fd, I915_PARAM_CHIPSET_ID) == 0) {
575 close(master_fd);
576 master_fd = -1;
577 }
578 }
579 }
580 device->master_fd = master_fd;
581
582 result = anv_init_wsi(device);
583 if (result != VK_SUCCESS)
584 goto fail_disk_cache;
585
586 device->perf = anv_get_perf(&device->info, fd);
587
588 anv_physical_device_get_supported_extensions(device,
589 &device->supported_extensions);
590
591
592 device->local_fd = fd;
593
594 *device_out = device;
595
596 return VK_SUCCESS;
597
598 fail_disk_cache:
599 anv_physical_device_free_disk_cache(device);
600 fail_compiler:
601 ralloc_free(device->compiler);
602 fail_alloc:
603 vk_free(&instance->alloc, device);
604 fail_fd:
605 close(fd);
606 if (master_fd != -1)
607 close(master_fd);
608 return result;
609 }
610
611 static void
612 anv_physical_device_destroy(struct anv_physical_device *device)
613 {
614 anv_finish_wsi(device);
615 anv_physical_device_free_disk_cache(device);
616 ralloc_free(device->compiler);
617 ralloc_free(device->perf);
618 close(device->local_fd);
619 if (device->master_fd >= 0)
620 close(device->master_fd);
621 vk_object_base_finish(&device->base);
622 vk_free(&device->instance->alloc, device);
623 }
624
625 static void *
626 default_alloc_func(void *pUserData, size_t size, size_t align,
627 VkSystemAllocationScope allocationScope)
628 {
629 return malloc(size);
630 }
631
632 static void *
633 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
634 size_t align, VkSystemAllocationScope allocationScope)
635 {
636 return realloc(pOriginal, size);
637 }
638
639 static void
640 default_free_func(void *pUserData, void *pMemory)
641 {
642 free(pMemory);
643 }
644
645 static const VkAllocationCallbacks default_alloc = {
646 .pUserData = NULL,
647 .pfnAllocation = default_alloc_func,
648 .pfnReallocation = default_realloc_func,
649 .pfnFree = default_free_func,
650 };
651
652 VkResult anv_EnumerateInstanceExtensionProperties(
653 const char* pLayerName,
654 uint32_t* pPropertyCount,
655 VkExtensionProperties* pProperties)
656 {
657 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
658
659 for (int i = 0; i < ANV_INSTANCE_EXTENSION_COUNT; i++) {
660 if (anv_instance_extensions_supported.extensions[i]) {
661 vk_outarray_append(&out, prop) {
662 *prop = anv_instance_extensions[i];
663 }
664 }
665 }
666
667 return vk_outarray_status(&out);
668 }
669
670 VkResult anv_CreateInstance(
671 const VkInstanceCreateInfo* pCreateInfo,
672 const VkAllocationCallbacks* pAllocator,
673 VkInstance* pInstance)
674 {
675 struct anv_instance *instance;
676 VkResult result;
677
678 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
679
680 struct anv_instance_extension_table enabled_extensions = {};
681 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
682 int idx;
683 for (idx = 0; idx < ANV_INSTANCE_EXTENSION_COUNT; idx++) {
684 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
685 anv_instance_extensions[idx].extensionName) == 0)
686 break;
687 }
688
689 if (idx >= ANV_INSTANCE_EXTENSION_COUNT)
690 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
691
692 if (!anv_instance_extensions_supported.extensions[idx])
693 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
694
695 enabled_extensions.extensions[idx] = true;
696 }
697
698 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
699 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
700 if (!instance)
701 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
702
703 vk_object_base_init(NULL, &instance->base, VK_OBJECT_TYPE_INSTANCE);
704
705 if (pAllocator)
706 instance->alloc = *pAllocator;
707 else
708 instance->alloc = default_alloc;
709
710 instance->app_info = (struct anv_app_info) { .api_version = 0 };
711 if (pCreateInfo->pApplicationInfo) {
712 const VkApplicationInfo *app = pCreateInfo->pApplicationInfo;
713
714 instance->app_info.app_name =
715 vk_strdup(&instance->alloc, app->pApplicationName,
716 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
717 instance->app_info.app_version = app->applicationVersion;
718
719 instance->app_info.engine_name =
720 vk_strdup(&instance->alloc, app->pEngineName,
721 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
722 instance->app_info.engine_version = app->engineVersion;
723
724 instance->app_info.api_version = app->apiVersion;
725 }
726
727 if (instance->app_info.api_version == 0)
728 instance->app_info.api_version = VK_API_VERSION_1_0;
729
730 instance->enabled_extensions = enabled_extensions;
731
732 for (unsigned i = 0; i < ARRAY_SIZE(instance->dispatch.entrypoints); i++) {
733 /* Vulkan requires that entrypoints for extensions which have not been
734 * enabled must not be advertised.
735 */
736 if (!anv_instance_entrypoint_is_enabled(i, instance->app_info.api_version,
737 &instance->enabled_extensions)) {
738 instance->dispatch.entrypoints[i] = NULL;
739 } else {
740 instance->dispatch.entrypoints[i] =
741 anv_instance_dispatch_table.entrypoints[i];
742 }
743 }
744
745 for (unsigned i = 0; i < ARRAY_SIZE(instance->physical_device_dispatch.entrypoints); i++) {
746 /* Vulkan requires that entrypoints for extensions which have not been
747 * enabled must not be advertised.
748 */
749 if (!anv_physical_device_entrypoint_is_enabled(i, instance->app_info.api_version,
750 &instance->enabled_extensions)) {
751 instance->physical_device_dispatch.entrypoints[i] = NULL;
752 } else {
753 instance->physical_device_dispatch.entrypoints[i] =
754 anv_physical_device_dispatch_table.entrypoints[i];
755 }
756 }
757
758 for (unsigned i = 0; i < ARRAY_SIZE(instance->device_dispatch.entrypoints); i++) {
759 /* Vulkan requires that entrypoints for extensions which have not been
760 * enabled must not be advertised.
761 */
762 if (!anv_device_entrypoint_is_enabled(i, instance->app_info.api_version,
763 &instance->enabled_extensions, NULL)) {
764 instance->device_dispatch.entrypoints[i] = NULL;
765 } else {
766 instance->device_dispatch.entrypoints[i] =
767 anv_device_dispatch_table.entrypoints[i];
768 }
769 }
770
771 instance->physical_devices_enumerated = false;
772 list_inithead(&instance->physical_devices);
773
774 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
775 if (result != VK_SUCCESS) {
776 vk_free2(&default_alloc, pAllocator, instance);
777 return vk_error(result);
778 }
779
780 instance->pipeline_cache_enabled =
781 env_var_as_boolean("ANV_ENABLE_PIPELINE_CACHE", true);
782
783 glsl_type_singleton_init_or_ref();
784
785 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
786
787 driParseOptionInfo(&instance->available_dri_options, anv_dri_options_xml);
788 driParseConfigFiles(&instance->dri_options, &instance->available_dri_options,
789 0, "anv", NULL,
790 instance->app_info.app_name,
791 instance->app_info.app_version,
792 instance->app_info.engine_name,
793 instance->app_info.engine_version);
794
795 *pInstance = anv_instance_to_handle(instance);
796
797 return VK_SUCCESS;
798 }
799
800 void anv_DestroyInstance(
801 VkInstance _instance,
802 const VkAllocationCallbacks* pAllocator)
803 {
804 ANV_FROM_HANDLE(anv_instance, instance, _instance);
805
806 if (!instance)
807 return;
808
809 list_for_each_entry_safe(struct anv_physical_device, pdevice,
810 &instance->physical_devices, link)
811 anv_physical_device_destroy(pdevice);
812
813 vk_free(&instance->alloc, (char *)instance->app_info.app_name);
814 vk_free(&instance->alloc, (char *)instance->app_info.engine_name);
815
816 VG(VALGRIND_DESTROY_MEMPOOL(instance));
817
818 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
819
820 glsl_type_singleton_decref();
821
822 driDestroyOptionCache(&instance->dri_options);
823 driDestroyOptionInfo(&instance->available_dri_options);
824
825 vk_object_base_finish(&instance->base);
826 vk_free(&instance->alloc, instance);
827 }
828
829 static VkResult
830 anv_enumerate_physical_devices(struct anv_instance *instance)
831 {
832 if (instance->physical_devices_enumerated)
833 return VK_SUCCESS;
834
835 instance->physical_devices_enumerated = true;
836
837 /* TODO: Check for more devices ? */
838 drmDevicePtr devices[8];
839 int max_devices;
840
841 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
842 if (max_devices < 1)
843 return VK_SUCCESS;
844
845 VkResult result = VK_SUCCESS;
846 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
847 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
848 devices[i]->bustype == DRM_BUS_PCI &&
849 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
850
851 struct anv_physical_device *pdevice;
852 result = anv_physical_device_try_create(instance, devices[i],
853 &pdevice);
854 /* Incompatible DRM device, skip. */
855 if (result == VK_ERROR_INCOMPATIBLE_DRIVER) {
856 result = VK_SUCCESS;
857 continue;
858 }
859
860 /* Error creating the physical device, report the error. */
861 if (result != VK_SUCCESS)
862 break;
863
864 list_addtail(&pdevice->link, &instance->physical_devices);
865 }
866 }
867 drmFreeDevices(devices, max_devices);
868
869 /* If we successfully enumerated any devices, call it success */
870 return result;
871 }
872
873 VkResult anv_EnumeratePhysicalDevices(
874 VkInstance _instance,
875 uint32_t* pPhysicalDeviceCount,
876 VkPhysicalDevice* pPhysicalDevices)
877 {
878 ANV_FROM_HANDLE(anv_instance, instance, _instance);
879 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
880
881 VkResult result = anv_enumerate_physical_devices(instance);
882 if (result != VK_SUCCESS)
883 return result;
884
885 list_for_each_entry(struct anv_physical_device, pdevice,
886 &instance->physical_devices, link) {
887 vk_outarray_append(&out, i) {
888 *i = anv_physical_device_to_handle(pdevice);
889 }
890 }
891
892 return vk_outarray_status(&out);
893 }
894
895 VkResult anv_EnumeratePhysicalDeviceGroups(
896 VkInstance _instance,
897 uint32_t* pPhysicalDeviceGroupCount,
898 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
899 {
900 ANV_FROM_HANDLE(anv_instance, instance, _instance);
901 VK_OUTARRAY_MAKE(out, pPhysicalDeviceGroupProperties,
902 pPhysicalDeviceGroupCount);
903
904 VkResult result = anv_enumerate_physical_devices(instance);
905 if (result != VK_SUCCESS)
906 return result;
907
908 list_for_each_entry(struct anv_physical_device, pdevice,
909 &instance->physical_devices, link) {
910 vk_outarray_append(&out, p) {
911 p->physicalDeviceCount = 1;
912 memset(p->physicalDevices, 0, sizeof(p->physicalDevices));
913 p->physicalDevices[0] = anv_physical_device_to_handle(pdevice);
914 p->subsetAllocation = false;
915
916 vk_foreach_struct(ext, p->pNext)
917 anv_debug_ignored_stype(ext->sType);
918 }
919 }
920
921 return vk_outarray_status(&out);
922 }
923
924 void anv_GetPhysicalDeviceFeatures(
925 VkPhysicalDevice physicalDevice,
926 VkPhysicalDeviceFeatures* pFeatures)
927 {
928 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
929
930 *pFeatures = (VkPhysicalDeviceFeatures) {
931 .robustBufferAccess = true,
932 .fullDrawIndexUint32 = true,
933 .imageCubeArray = true,
934 .independentBlend = true,
935 .geometryShader = true,
936 .tessellationShader = true,
937 .sampleRateShading = true,
938 .dualSrcBlend = true,
939 .logicOp = true,
940 .multiDrawIndirect = true,
941 .drawIndirectFirstInstance = true,
942 .depthClamp = true,
943 .depthBiasClamp = true,
944 .fillModeNonSolid = true,
945 .depthBounds = pdevice->info.gen >= 12,
946 .wideLines = true,
947 .largePoints = true,
948 .alphaToOne = true,
949 .multiViewport = true,
950 .samplerAnisotropy = true,
951 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
952 pdevice->info.is_baytrail,
953 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
954 .textureCompressionBC = true,
955 .occlusionQueryPrecise = true,
956 .pipelineStatisticsQuery = true,
957 .fragmentStoresAndAtomics = true,
958 .shaderTessellationAndGeometryPointSize = true,
959 .shaderImageGatherExtended = true,
960 .shaderStorageImageExtendedFormats = true,
961 .shaderStorageImageMultisample = false,
962 .shaderStorageImageReadWithoutFormat = false,
963 .shaderStorageImageWriteWithoutFormat = true,
964 .shaderUniformBufferArrayDynamicIndexing = true,
965 .shaderSampledImageArrayDynamicIndexing = true,
966 .shaderStorageBufferArrayDynamicIndexing = true,
967 .shaderStorageImageArrayDynamicIndexing = true,
968 .shaderClipDistance = true,
969 .shaderCullDistance = true,
970 .shaderFloat64 = pdevice->info.gen >= 8 &&
971 pdevice->info.has_64bit_float,
972 .shaderInt64 = pdevice->info.gen >= 8 &&
973 pdevice->info.has_64bit_int,
974 .shaderInt16 = pdevice->info.gen >= 8,
975 .shaderResourceMinLod = pdevice->info.gen >= 9,
976 .variableMultisampleRate = true,
977 .inheritedQueries = true,
978 };
979
980 /* We can't do image stores in vec4 shaders */
981 pFeatures->vertexPipelineStoresAndAtomics =
982 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
983 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
984
985 struct anv_app_info *app_info = &pdevice->instance->app_info;
986
987 /* The new DOOM and Wolfenstein games require depthBounds without
988 * checking for it. They seem to run fine without it so just claim it's
989 * there and accept the consequences.
990 */
991 if (app_info->engine_name && strcmp(app_info->engine_name, "idTech") == 0)
992 pFeatures->depthBounds = true;
993 }
994
995 static void
996 anv_get_physical_device_features_1_1(struct anv_physical_device *pdevice,
997 VkPhysicalDeviceVulkan11Features *f)
998 {
999 assert(f->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES);
1000
1001 f->storageBuffer16BitAccess = pdevice->info.gen >= 8;
1002 f->uniformAndStorageBuffer16BitAccess = pdevice->info.gen >= 8;
1003 f->storagePushConstant16 = pdevice->info.gen >= 8;
1004 f->storageInputOutput16 = false;
1005 f->multiview = true;
1006 f->multiviewGeometryShader = true;
1007 f->multiviewTessellationShader = true;
1008 f->variablePointersStorageBuffer = true;
1009 f->variablePointers = true;
1010 f->protectedMemory = false;
1011 f->samplerYcbcrConversion = true;
1012 f->shaderDrawParameters = true;
1013 }
1014
1015 static void
1016 anv_get_physical_device_features_1_2(struct anv_physical_device *pdevice,
1017 VkPhysicalDeviceVulkan12Features *f)
1018 {
1019 assert(f->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES);
1020
1021 f->samplerMirrorClampToEdge = true;
1022 f->drawIndirectCount = true;
1023 f->storageBuffer8BitAccess = pdevice->info.gen >= 8;
1024 f->uniformAndStorageBuffer8BitAccess = pdevice->info.gen >= 8;
1025 f->storagePushConstant8 = pdevice->info.gen >= 8;
1026 f->shaderBufferInt64Atomics = pdevice->info.gen >= 9 &&
1027 pdevice->use_softpin;
1028 f->shaderSharedInt64Atomics = false;
1029 f->shaderFloat16 = pdevice->info.gen >= 8;
1030 f->shaderInt8 = pdevice->info.gen >= 8;
1031
1032 bool descIndexing = pdevice->has_a64_buffer_access &&
1033 pdevice->has_bindless_images;
1034 f->descriptorIndexing = descIndexing;
1035 f->shaderInputAttachmentArrayDynamicIndexing = false;
1036 f->shaderUniformTexelBufferArrayDynamicIndexing = descIndexing;
1037 f->shaderStorageTexelBufferArrayDynamicIndexing = descIndexing;
1038 f->shaderUniformBufferArrayNonUniformIndexing = false;
1039 f->shaderSampledImageArrayNonUniformIndexing = descIndexing;
1040 f->shaderStorageBufferArrayNonUniformIndexing = descIndexing;
1041 f->shaderStorageImageArrayNonUniformIndexing = descIndexing;
1042 f->shaderInputAttachmentArrayNonUniformIndexing = false;
1043 f->shaderUniformTexelBufferArrayNonUniformIndexing = descIndexing;
1044 f->shaderStorageTexelBufferArrayNonUniformIndexing = descIndexing;
1045 f->descriptorBindingUniformBufferUpdateAfterBind = false;
1046 f->descriptorBindingSampledImageUpdateAfterBind = descIndexing;
1047 f->descriptorBindingStorageImageUpdateAfterBind = descIndexing;
1048 f->descriptorBindingStorageBufferUpdateAfterBind = descIndexing;
1049 f->descriptorBindingUniformTexelBufferUpdateAfterBind = descIndexing;
1050 f->descriptorBindingStorageTexelBufferUpdateAfterBind = descIndexing;
1051 f->descriptorBindingUpdateUnusedWhilePending = descIndexing;
1052 f->descriptorBindingPartiallyBound = descIndexing;
1053 f->descriptorBindingVariableDescriptorCount = false;
1054 f->runtimeDescriptorArray = descIndexing;
1055
1056 f->samplerFilterMinmax = pdevice->info.gen >= 9;
1057 f->scalarBlockLayout = true;
1058 f->imagelessFramebuffer = true;
1059 f->uniformBufferStandardLayout = true;
1060 f->shaderSubgroupExtendedTypes = true;
1061 f->separateDepthStencilLayouts = true;
1062 f->hostQueryReset = true;
1063 f->timelineSemaphore = true;
1064 f->bufferDeviceAddress = pdevice->has_a64_buffer_access;
1065 f->bufferDeviceAddressCaptureReplay = pdevice->has_a64_buffer_access;
1066 f->bufferDeviceAddressMultiDevice = false;
1067 f->vulkanMemoryModel = true;
1068 f->vulkanMemoryModelDeviceScope = true;
1069 f->vulkanMemoryModelAvailabilityVisibilityChains = true;
1070 f->shaderOutputViewportIndex = true;
1071 f->shaderOutputLayer = true;
1072 f->subgroupBroadcastDynamicId = true;
1073 }
1074
1075 void anv_GetPhysicalDeviceFeatures2(
1076 VkPhysicalDevice physicalDevice,
1077 VkPhysicalDeviceFeatures2* pFeatures)
1078 {
1079 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1080 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
1081
1082 VkPhysicalDeviceVulkan11Features core_1_1 = {
1083 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES,
1084 };
1085 anv_get_physical_device_features_1_1(pdevice, &core_1_1);
1086
1087 VkPhysicalDeviceVulkan12Features core_1_2 = {
1088 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES,
1089 };
1090 anv_get_physical_device_features_1_2(pdevice, &core_1_2);
1091
1092 #define CORE_FEATURE(major, minor, feature) \
1093 features->feature = core_##major##_##minor.feature
1094
1095
1096 vk_foreach_struct(ext, pFeatures->pNext) {
1097 switch (ext->sType) {
1098 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_4444_FORMATS_FEATURES_EXT: {
1099 VkPhysicalDevice4444FormatsFeaturesEXT *features =
1100 (VkPhysicalDevice4444FormatsFeaturesEXT *)ext;
1101 features->formatA4R4G4B4 = true;
1102 features->formatA4B4G4R4 = false;
1103 break;
1104 }
1105
1106 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR: {
1107 VkPhysicalDevice8BitStorageFeaturesKHR *features =
1108 (VkPhysicalDevice8BitStorageFeaturesKHR *)ext;
1109 CORE_FEATURE(1, 2, storageBuffer8BitAccess);
1110 CORE_FEATURE(1, 2, uniformAndStorageBuffer8BitAccess);
1111 CORE_FEATURE(1, 2, storagePushConstant8);
1112 break;
1113 }
1114
1115 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
1116 VkPhysicalDevice16BitStorageFeatures *features =
1117 (VkPhysicalDevice16BitStorageFeatures *)ext;
1118 CORE_FEATURE(1, 1, storageBuffer16BitAccess);
1119 CORE_FEATURE(1, 1, uniformAndStorageBuffer16BitAccess);
1120 CORE_FEATURE(1, 1, storagePushConstant16);
1121 CORE_FEATURE(1, 1, storageInputOutput16);
1122 break;
1123 }
1124
1125 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT: {
1126 VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *features = (void *)ext;
1127 features->bufferDeviceAddress = pdevice->has_a64_buffer_access;
1128 features->bufferDeviceAddressCaptureReplay = false;
1129 features->bufferDeviceAddressMultiDevice = false;
1130 break;
1131 }
1132
1133 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_KHR: {
1134 VkPhysicalDeviceBufferDeviceAddressFeaturesKHR *features = (void *)ext;
1135 CORE_FEATURE(1, 2, bufferDeviceAddress);
1136 CORE_FEATURE(1, 2, bufferDeviceAddressCaptureReplay);
1137 CORE_FEATURE(1, 2, bufferDeviceAddressMultiDevice);
1138 break;
1139 }
1140
1141 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV: {
1142 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *features =
1143 (VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *)ext;
1144 features->computeDerivativeGroupQuads = true;
1145 features->computeDerivativeGroupLinear = true;
1146 break;
1147 }
1148
1149 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
1150 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
1151 (VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
1152 features->conditionalRendering = pdevice->info.gen >= 8 ||
1153 pdevice->info.is_haswell;
1154 features->inheritedConditionalRendering = pdevice->info.gen >= 8 ||
1155 pdevice->info.is_haswell;
1156 break;
1157 }
1158
1159 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_FEATURES_EXT: {
1160 VkPhysicalDeviceCustomBorderColorFeaturesEXT *features =
1161 (VkPhysicalDeviceCustomBorderColorFeaturesEXT *)ext;
1162 features->customBorderColors = pdevice->info.gen >= 8;
1163 features->customBorderColorWithoutFormat = pdevice->info.gen >= 8;
1164 break;
1165 }
1166
1167 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT: {
1168 VkPhysicalDeviceDepthClipEnableFeaturesEXT *features =
1169 (VkPhysicalDeviceDepthClipEnableFeaturesEXT *)ext;
1170 features->depthClipEnable = true;
1171 break;
1172 }
1173
1174 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR: {
1175 VkPhysicalDeviceFloat16Int8FeaturesKHR *features = (void *)ext;
1176 CORE_FEATURE(1, 2, shaderFloat16);
1177 CORE_FEATURE(1, 2, shaderInt8);
1178 break;
1179 }
1180
1181 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT: {
1182 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT *features =
1183 (VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT *)ext;
1184 features->fragmentShaderSampleInterlock = pdevice->info.gen >= 9;
1185 features->fragmentShaderPixelInterlock = pdevice->info.gen >= 9;
1186 features->fragmentShaderShadingRateInterlock = false;
1187 break;
1188 }
1189
1190 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT: {
1191 VkPhysicalDeviceHostQueryResetFeaturesEXT *features =
1192 (VkPhysicalDeviceHostQueryResetFeaturesEXT *)ext;
1193 CORE_FEATURE(1, 2, hostQueryReset);
1194 break;
1195 }
1196
1197 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
1198 VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
1199 (VkPhysicalDeviceDescriptorIndexingFeaturesEXT *)ext;
1200 CORE_FEATURE(1, 2, shaderInputAttachmentArrayDynamicIndexing);
1201 CORE_FEATURE(1, 2, shaderUniformTexelBufferArrayDynamicIndexing);
1202 CORE_FEATURE(1, 2, shaderStorageTexelBufferArrayDynamicIndexing);
1203 CORE_FEATURE(1, 2, shaderUniformBufferArrayNonUniformIndexing);
1204 CORE_FEATURE(1, 2, shaderSampledImageArrayNonUniformIndexing);
1205 CORE_FEATURE(1, 2, shaderStorageBufferArrayNonUniformIndexing);
1206 CORE_FEATURE(1, 2, shaderStorageImageArrayNonUniformIndexing);
1207 CORE_FEATURE(1, 2, shaderInputAttachmentArrayNonUniformIndexing);
1208 CORE_FEATURE(1, 2, shaderUniformTexelBufferArrayNonUniformIndexing);
1209 CORE_FEATURE(1, 2, shaderStorageTexelBufferArrayNonUniformIndexing);
1210 CORE_FEATURE(1, 2, descriptorBindingUniformBufferUpdateAfterBind);
1211 CORE_FEATURE(1, 2, descriptorBindingSampledImageUpdateAfterBind);
1212 CORE_FEATURE(1, 2, descriptorBindingStorageImageUpdateAfterBind);
1213 CORE_FEATURE(1, 2, descriptorBindingStorageBufferUpdateAfterBind);
1214 CORE_FEATURE(1, 2, descriptorBindingUniformTexelBufferUpdateAfterBind);
1215 CORE_FEATURE(1, 2, descriptorBindingStorageTexelBufferUpdateAfterBind);
1216 CORE_FEATURE(1, 2, descriptorBindingUpdateUnusedWhilePending);
1217 CORE_FEATURE(1, 2, descriptorBindingPartiallyBound);
1218 CORE_FEATURE(1, 2, descriptorBindingVariableDescriptorCount);
1219 CORE_FEATURE(1, 2, runtimeDescriptorArray);
1220 break;
1221 }
1222
1223 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_ROBUSTNESS_FEATURES_EXT: {
1224 VkPhysicalDeviceImageRobustnessFeaturesEXT *features =
1225 (VkPhysicalDeviceImageRobustnessFeaturesEXT *)ext;
1226 features->robustImageAccess = true;
1227 break;
1228 }
1229
1230 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT: {
1231 VkPhysicalDeviceIndexTypeUint8FeaturesEXT *features =
1232 (VkPhysicalDeviceIndexTypeUint8FeaturesEXT *)ext;
1233 features->indexTypeUint8 = true;
1234 break;
1235 }
1236
1237 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT: {
1238 VkPhysicalDeviceInlineUniformBlockFeaturesEXT *features =
1239 (VkPhysicalDeviceInlineUniformBlockFeaturesEXT *)ext;
1240 features->inlineUniformBlock = true;
1241 features->descriptorBindingInlineUniformBlockUpdateAfterBind = true;
1242 break;
1243 }
1244
1245 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_FEATURES_EXT: {
1246 VkPhysicalDeviceLineRasterizationFeaturesEXT *features =
1247 (VkPhysicalDeviceLineRasterizationFeaturesEXT *)ext;
1248 features->rectangularLines = true;
1249 features->bresenhamLines = true;
1250 /* Support for Smooth lines with MSAA was removed on gen11. From the
1251 * BSpec section "Multisample ModesState" table for "AA Line Support
1252 * Requirements":
1253 *
1254 * GEN10:BUG:######## NUM_MULTISAMPLES == 1
1255 *
1256 * Fortunately, this isn't a case most people care about.
1257 */
1258 features->smoothLines = pdevice->info.gen < 10;
1259 features->stippledRectangularLines = false;
1260 features->stippledBresenhamLines = true;
1261 features->stippledSmoothLines = false;
1262 break;
1263 }
1264
1265 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
1266 VkPhysicalDeviceMultiviewFeatures *features =
1267 (VkPhysicalDeviceMultiviewFeatures *)ext;
1268 CORE_FEATURE(1, 1, multiview);
1269 CORE_FEATURE(1, 1, multiviewGeometryShader);
1270 CORE_FEATURE(1, 1, multiviewTessellationShader);
1271 break;
1272 }
1273
1274 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES_KHR: {
1275 VkPhysicalDeviceImagelessFramebufferFeaturesKHR *features =
1276 (VkPhysicalDeviceImagelessFramebufferFeaturesKHR *)ext;
1277 CORE_FEATURE(1, 2, imagelessFramebuffer);
1278 break;
1279 }
1280
1281 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PERFORMANCE_QUERY_FEATURES_KHR: {
1282 VkPhysicalDevicePerformanceQueryFeaturesKHR *feature =
1283 (VkPhysicalDevicePerformanceQueryFeaturesKHR *)ext;
1284 feature->performanceCounterQueryPools = true;
1285 /* HW only supports a single configuration at a time. */
1286 feature->performanceCounterMultipleQueryPools = false;
1287 break;
1288 }
1289
1290 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_CREATION_CACHE_CONTROL_FEATURES_EXT: {
1291 VkPhysicalDevicePipelineCreationCacheControlFeaturesEXT *features =
1292 (VkPhysicalDevicePipelineCreationCacheControlFeaturesEXT *)ext;
1293 features->pipelineCreationCacheControl = true;
1294 break;
1295 }
1296
1297 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR: {
1298 VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *features =
1299 (VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *)ext;
1300 features->pipelineExecutableInfo = true;
1301 break;
1302 }
1303
1304 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRIVATE_DATA_FEATURES_EXT: {
1305 VkPhysicalDevicePrivateDataFeaturesEXT *features = (void *)ext;
1306 features->privateData = true;
1307 break;
1308 }
1309
1310 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
1311 VkPhysicalDeviceProtectedMemoryFeatures *features = (void *)ext;
1312 CORE_FEATURE(1, 1, protectedMemory);
1313 break;
1314 }
1315
1316 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT: {
1317 VkPhysicalDeviceRobustness2FeaturesEXT *features = (void *)ext;
1318 features->robustBufferAccess2 = true;
1319 features->robustImageAccess2 = true;
1320 features->nullDescriptor = true;
1321 break;
1322 }
1323
1324 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
1325 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
1326 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
1327 CORE_FEATURE(1, 1, samplerYcbcrConversion);
1328 break;
1329 }
1330
1331 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
1332 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
1333 (VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
1334 CORE_FEATURE(1, 2, scalarBlockLayout);
1335 break;
1336 }
1337
1338 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SEPARATE_DEPTH_STENCIL_LAYOUTS_FEATURES_KHR: {
1339 VkPhysicalDeviceSeparateDepthStencilLayoutsFeaturesKHR *features =
1340 (VkPhysicalDeviceSeparateDepthStencilLayoutsFeaturesKHR *)ext;
1341 CORE_FEATURE(1, 2, separateDepthStencilLayouts);
1342 break;
1343 }
1344
1345 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_FLOAT_FEATURES_EXT: {
1346 VkPhysicalDeviceShaderAtomicFloatFeaturesEXT *features = (void *)ext;
1347 features->shaderBufferFloat32Atomics = true;
1348 features->shaderBufferFloat32AtomicAdd = false;
1349 features->shaderBufferFloat64Atomics = false;
1350 features->shaderBufferFloat64AtomicAdd = false;
1351 features->shaderSharedFloat32Atomics = true;
1352 features->shaderSharedFloat32AtomicAdd = false;
1353 features->shaderSharedFloat64Atomics = false;
1354 features->shaderSharedFloat64AtomicAdd = false;
1355 features->shaderImageFloat32Atomics = true;
1356 features->shaderImageFloat32AtomicAdd = false;
1357 features->sparseImageFloat32Atomics = false;
1358 features->sparseImageFloat32AtomicAdd = false;
1359 break;
1360 }
1361
1362 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR: {
1363 VkPhysicalDeviceShaderAtomicInt64FeaturesKHR *features = (void *)ext;
1364 CORE_FEATURE(1, 2, shaderBufferInt64Atomics);
1365 CORE_FEATURE(1, 2, shaderSharedInt64Atomics);
1366 break;
1367 }
1368
1369 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DEMOTE_TO_HELPER_INVOCATION_FEATURES_EXT: {
1370 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT *features = (void *)ext;
1371 features->shaderDemoteToHelperInvocation = true;
1372 break;
1373 }
1374
1375 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CLOCK_FEATURES_KHR: {
1376 VkPhysicalDeviceShaderClockFeaturesKHR *features =
1377 (VkPhysicalDeviceShaderClockFeaturesKHR *)ext;
1378 features->shaderSubgroupClock = true;
1379 features->shaderDeviceClock = false;
1380 break;
1381 }
1382
1383 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
1384 VkPhysicalDeviceShaderDrawParametersFeatures *features = (void *)ext;
1385 CORE_FEATURE(1, 1, shaderDrawParameters);
1386 break;
1387 }
1388
1389 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_INTEGER_FUNCTIONS_2_FEATURES_INTEL: {
1390 VkPhysicalDeviceShaderIntegerFunctions2FeaturesINTEL *features =
1391 (VkPhysicalDeviceShaderIntegerFunctions2FeaturesINTEL *)ext;
1392 features->shaderIntegerFunctions2 = true;
1393 break;
1394 }
1395
1396 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_SUBGROUP_EXTENDED_TYPES_FEATURES_KHR: {
1397 VkPhysicalDeviceShaderSubgroupExtendedTypesFeaturesKHR *features =
1398 (VkPhysicalDeviceShaderSubgroupExtendedTypesFeaturesKHR *)ext;
1399 CORE_FEATURE(1, 2, shaderSubgroupExtendedTypes);
1400 break;
1401 }
1402
1403 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT: {
1404 VkPhysicalDeviceSubgroupSizeControlFeaturesEXT *features =
1405 (VkPhysicalDeviceSubgroupSizeControlFeaturesEXT *)ext;
1406 features->subgroupSizeControl = true;
1407 features->computeFullSubgroups = true;
1408 break;
1409 }
1410
1411 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_FEATURES_EXT: {
1412 VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *features =
1413 (VkPhysicalDeviceTexelBufferAlignmentFeaturesEXT *)ext;
1414 features->texelBufferAlignment = true;
1415 break;
1416 }
1417
1418 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR: {
1419 VkPhysicalDeviceTimelineSemaphoreFeaturesKHR *features =
1420 (VkPhysicalDeviceTimelineSemaphoreFeaturesKHR *) ext;
1421 CORE_FEATURE(1, 2, timelineSemaphore);
1422 break;
1423 }
1424
1425 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
1426 VkPhysicalDeviceVariablePointersFeatures *features = (void *)ext;
1427 CORE_FEATURE(1, 1, variablePointersStorageBuffer);
1428 CORE_FEATURE(1, 1, variablePointers);
1429 break;
1430 }
1431
1432 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
1433 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
1434 (VkPhysicalDeviceTransformFeedbackFeaturesEXT *)ext;
1435 features->transformFeedback = true;
1436 features->geometryStreams = true;
1437 break;
1438 }
1439
1440 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR: {
1441 VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *features =
1442 (VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *)ext;
1443 CORE_FEATURE(1, 2, uniformBufferStandardLayout);
1444 break;
1445 }
1446
1447 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
1448 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
1449 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
1450 features->vertexAttributeInstanceRateDivisor = true;
1451 features->vertexAttributeInstanceRateZeroDivisor = true;
1452 break;
1453 }
1454
1455 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES:
1456 anv_get_physical_device_features_1_1(pdevice, (void *)ext);
1457 break;
1458
1459 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES:
1460 anv_get_physical_device_features_1_2(pdevice, (void *)ext);
1461 break;
1462
1463 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES_KHR: {
1464 VkPhysicalDeviceVulkanMemoryModelFeaturesKHR *features = (void *)ext;
1465 CORE_FEATURE(1, 2, vulkanMemoryModel);
1466 CORE_FEATURE(1, 2, vulkanMemoryModelDeviceScope);
1467 CORE_FEATURE(1, 2, vulkanMemoryModelAvailabilityVisibilityChains);
1468 break;
1469 }
1470
1471 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT: {
1472 VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *features =
1473 (VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *)ext;
1474 features->ycbcrImageArrays = true;
1475 break;
1476 }
1477
1478 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT: {
1479 VkPhysicalDeviceExtendedDynamicStateFeaturesEXT *features =
1480 (VkPhysicalDeviceExtendedDynamicStateFeaturesEXT *)ext;
1481 features->extendedDynamicState = true;
1482 break;
1483 }
1484
1485 default:
1486 anv_debug_ignored_stype(ext->sType);
1487 break;
1488 }
1489 }
1490
1491 #undef CORE_FEATURE
1492 }
1493
1494 #define MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS 64
1495
1496 #define MAX_PER_STAGE_DESCRIPTOR_INPUT_ATTACHMENTS 64
1497 #define MAX_DESCRIPTOR_SET_INPUT_ATTACHMENTS 256
1498
1499 #define MAX_CUSTOM_BORDER_COLORS 4096
1500
1501 void anv_GetPhysicalDeviceProperties(
1502 VkPhysicalDevice physicalDevice,
1503 VkPhysicalDeviceProperties* pProperties)
1504 {
1505 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1506 const struct gen_device_info *devinfo = &pdevice->info;
1507
1508 /* See assertions made when programming the buffer surface state. */
1509 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
1510 (1ul << 30) : (1ul << 27);
1511
1512 const uint32_t max_ssbos = pdevice->has_a64_buffer_access ? UINT16_MAX : 64;
1513 const uint32_t max_textures =
1514 pdevice->has_bindless_images ? UINT16_MAX : 128;
1515 const uint32_t max_samplers =
1516 pdevice->has_bindless_samplers ? UINT16_MAX :
1517 (devinfo->gen >= 8 || devinfo->is_haswell) ? 128 : 16;
1518 const uint32_t max_images =
1519 pdevice->has_bindless_images ? UINT16_MAX : MAX_IMAGES;
1520
1521 /* If we can use bindless for everything, claim a high per-stage limit,
1522 * otherwise use the binding table size, minus the slots reserved for
1523 * render targets and one slot for the descriptor buffer. */
1524 const uint32_t max_per_stage =
1525 pdevice->has_bindless_images && pdevice->has_a64_buffer_access
1526 ? UINT32_MAX : MAX_BINDING_TABLE_SIZE - MAX_RTS - 1;
1527
1528 /* Limit max_threads to 64 for the GPGPU_WALKER command */
1529 const uint32_t max_workgroup_size = 32 * MIN2(64, devinfo->max_cs_threads);
1530
1531 VkSampleCountFlags sample_counts =
1532 isl_device_get_sample_counts(&pdevice->isl_dev);
1533
1534
1535 VkPhysicalDeviceLimits limits = {
1536 .maxImageDimension1D = (1 << 14),
1537 .maxImageDimension2D = (1 << 14),
1538 .maxImageDimension3D = (1 << 11),
1539 .maxImageDimensionCube = (1 << 14),
1540 .maxImageArrayLayers = (1 << 11),
1541 .maxTexelBufferElements = 128 * 1024 * 1024,
1542 .maxUniformBufferRange = (1ul << 27),
1543 .maxStorageBufferRange = max_raw_buffer_sz,
1544 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
1545 .maxMemoryAllocationCount = UINT32_MAX,
1546 .maxSamplerAllocationCount = 64 * 1024,
1547 .bufferImageGranularity = 64, /* A cache line */
1548 .sparseAddressSpaceSize = 0,
1549 .maxBoundDescriptorSets = MAX_SETS,
1550 .maxPerStageDescriptorSamplers = max_samplers,
1551 .maxPerStageDescriptorUniformBuffers = MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS,
1552 .maxPerStageDescriptorStorageBuffers = max_ssbos,
1553 .maxPerStageDescriptorSampledImages = max_textures,
1554 .maxPerStageDescriptorStorageImages = max_images,
1555 .maxPerStageDescriptorInputAttachments = MAX_PER_STAGE_DESCRIPTOR_INPUT_ATTACHMENTS,
1556 .maxPerStageResources = max_per_stage,
1557 .maxDescriptorSetSamplers = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
1558 .maxDescriptorSetUniformBuffers = 6 * MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS, /* number of stages * maxPerStageDescriptorUniformBuffers */
1559 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
1560 .maxDescriptorSetStorageBuffers = 6 * max_ssbos, /* number of stages * maxPerStageDescriptorStorageBuffers */
1561 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
1562 .maxDescriptorSetSampledImages = 6 * max_textures, /* number of stages * maxPerStageDescriptorSampledImages */
1563 .maxDescriptorSetStorageImages = 6 * max_images, /* number of stages * maxPerStageDescriptorStorageImages */
1564 .maxDescriptorSetInputAttachments = MAX_DESCRIPTOR_SET_INPUT_ATTACHMENTS,
1565 .maxVertexInputAttributes = MAX_VBS,
1566 .maxVertexInputBindings = MAX_VBS,
1567 .maxVertexInputAttributeOffset = 2047,
1568 .maxVertexInputBindingStride = 2048,
1569 .maxVertexOutputComponents = 128,
1570 .maxTessellationGenerationLevel = 64,
1571 .maxTessellationPatchSize = 32,
1572 .maxTessellationControlPerVertexInputComponents = 128,
1573 .maxTessellationControlPerVertexOutputComponents = 128,
1574 .maxTessellationControlPerPatchOutputComponents = 128,
1575 .maxTessellationControlTotalOutputComponents = 2048,
1576 .maxTessellationEvaluationInputComponents = 128,
1577 .maxTessellationEvaluationOutputComponents = 128,
1578 .maxGeometryShaderInvocations = 32,
1579 .maxGeometryInputComponents = 64,
1580 .maxGeometryOutputComponents = 128,
1581 .maxGeometryOutputVertices = 256,
1582 .maxGeometryTotalOutputComponents = 1024,
1583 .maxFragmentInputComponents = 116, /* 128 components - (PSIZ, CLIP_DIST0, CLIP_DIST1) */
1584 .maxFragmentOutputAttachments = 8,
1585 .maxFragmentDualSrcAttachments = 1,
1586 .maxFragmentCombinedOutputResources = 8,
1587 .maxComputeSharedMemorySize = 64 * 1024,
1588 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
1589 .maxComputeWorkGroupInvocations = max_workgroup_size,
1590 .maxComputeWorkGroupSize = {
1591 max_workgroup_size,
1592 max_workgroup_size,
1593 max_workgroup_size,
1594 },
1595 .subPixelPrecisionBits = 8,
1596 .subTexelPrecisionBits = 8,
1597 .mipmapPrecisionBits = 8,
1598 .maxDrawIndexedIndexValue = UINT32_MAX,
1599 .maxDrawIndirectCount = UINT32_MAX,
1600 .maxSamplerLodBias = 16,
1601 .maxSamplerAnisotropy = 16,
1602 .maxViewports = MAX_VIEWPORTS,
1603 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1604 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1605 .viewportSubPixelBits = 13, /* We take a float? */
1606 .minMemoryMapAlignment = 4096, /* A page */
1607 /* The dataport requires texel alignment so we need to assume a worst
1608 * case of R32G32B32A32 which is 16 bytes.
1609 */
1610 .minTexelBufferOffsetAlignment = 16,
1611 .minUniformBufferOffsetAlignment = ANV_UBO_ALIGNMENT,
1612 .minStorageBufferOffsetAlignment = 4,
1613 .minTexelOffset = -8,
1614 .maxTexelOffset = 7,
1615 .minTexelGatherOffset = -32,
1616 .maxTexelGatherOffset = 31,
1617 .minInterpolationOffset = -0.5,
1618 .maxInterpolationOffset = 0.4375,
1619 .subPixelInterpolationOffsetBits = 4,
1620 .maxFramebufferWidth = (1 << 14),
1621 .maxFramebufferHeight = (1 << 14),
1622 .maxFramebufferLayers = (1 << 11),
1623 .framebufferColorSampleCounts = sample_counts,
1624 .framebufferDepthSampleCounts = sample_counts,
1625 .framebufferStencilSampleCounts = sample_counts,
1626 .framebufferNoAttachmentsSampleCounts = sample_counts,
1627 .maxColorAttachments = MAX_RTS,
1628 .sampledImageColorSampleCounts = sample_counts,
1629 .sampledImageIntegerSampleCounts = sample_counts,
1630 .sampledImageDepthSampleCounts = sample_counts,
1631 .sampledImageStencilSampleCounts = sample_counts,
1632 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1633 .maxSampleMaskWords = 1,
1634 .timestampComputeAndGraphics = true,
1635 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
1636 .maxClipDistances = 8,
1637 .maxCullDistances = 8,
1638 .maxCombinedClipAndCullDistances = 8,
1639 .discreteQueuePriorities = 2,
1640 .pointSizeRange = { 0.125, 255.875 },
1641 .lineWidthRange = {
1642 0.0,
1643 (devinfo->gen >= 9 || devinfo->is_cherryview) ?
1644 2047.9921875 : 7.9921875,
1645 },
1646 .pointSizeGranularity = (1.0 / 8.0),
1647 .lineWidthGranularity = (1.0 / 128.0),
1648 .strictLines = false,
1649 .standardSampleLocations = true,
1650 .optimalBufferCopyOffsetAlignment = 128,
1651 .optimalBufferCopyRowPitchAlignment = 128,
1652 .nonCoherentAtomSize = 64,
1653 };
1654
1655 *pProperties = (VkPhysicalDeviceProperties) {
1656 .apiVersion = anv_physical_device_api_version(pdevice),
1657 .driverVersion = vk_get_driver_version(),
1658 .vendorID = 0x8086,
1659 .deviceID = pdevice->info.chipset_id,
1660 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1661 .limits = limits,
1662 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
1663 };
1664
1665 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
1666 "%s", pdevice->name);
1667 memcpy(pProperties->pipelineCacheUUID,
1668 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
1669 }
1670
1671 static void
1672 anv_get_physical_device_properties_1_1(struct anv_physical_device *pdevice,
1673 VkPhysicalDeviceVulkan11Properties *p)
1674 {
1675 assert(p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES);
1676
1677 memcpy(p->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1678 memcpy(p->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1679 memset(p->deviceLUID, 0, VK_LUID_SIZE);
1680 p->deviceNodeMask = 0;
1681 p->deviceLUIDValid = false;
1682
1683 p->subgroupSize = BRW_SUBGROUP_SIZE;
1684 VkShaderStageFlags scalar_stages = 0;
1685 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1686 if (pdevice->compiler->scalar_stage[stage])
1687 scalar_stages |= mesa_to_vk_shader_stage(stage);
1688 }
1689 p->subgroupSupportedStages = scalar_stages;
1690 p->subgroupSupportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1691 VK_SUBGROUP_FEATURE_VOTE_BIT |
1692 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1693 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1694 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
1695 VK_SUBGROUP_FEATURE_QUAD_BIT;
1696 if (pdevice->info.gen >= 8) {
1697 /* TODO: There's no technical reason why these can't be made to
1698 * work on gen7 but they don't at the moment so it's best to leave
1699 * the feature disabled than enabled and broken.
1700 */
1701 p->subgroupSupportedOperations |= VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1702 VK_SUBGROUP_FEATURE_CLUSTERED_BIT;
1703 }
1704 p->subgroupQuadOperationsInAllStages = pdevice->info.gen >= 8;
1705
1706 p->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_USER_CLIP_PLANES_ONLY;
1707 p->maxMultiviewViewCount = 16;
1708 p->maxMultiviewInstanceIndex = UINT32_MAX / 16;
1709 p->protectedNoFault = false;
1710 /* This value doesn't matter for us today as our per-stage descriptors are
1711 * the real limit.
1712 */
1713 p->maxPerSetDescriptors = 1024;
1714 p->maxMemoryAllocationSize = MAX_MEMORY_ALLOCATION_SIZE;
1715 }
1716
1717 static void
1718 anv_get_physical_device_properties_1_2(struct anv_physical_device *pdevice,
1719 VkPhysicalDeviceVulkan12Properties *p)
1720 {
1721 assert(p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES);
1722
1723 p->driverID = VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA_KHR;
1724 memset(p->driverName, 0, sizeof(p->driverName));
1725 snprintf(p->driverName, VK_MAX_DRIVER_NAME_SIZE_KHR,
1726 "Intel open-source Mesa driver");
1727 memset(p->driverInfo, 0, sizeof(p->driverInfo));
1728 snprintf(p->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1729 "Mesa " PACKAGE_VERSION MESA_GIT_SHA1);
1730 p->conformanceVersion = (VkConformanceVersionKHR) {
1731 .major = 1,
1732 .minor = 2,
1733 .subminor = 0,
1734 .patch = 0,
1735 };
1736
1737 p->denormBehaviorIndependence =
1738 VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL_KHR;
1739 p->roundingModeIndependence =
1740 VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE_KHR;
1741
1742 /* Broadwell does not support HF denorms and there are restrictions
1743 * other gens. According to Kabylake's PRM:
1744 *
1745 * "math - Extended Math Function
1746 * [...]
1747 * Restriction : Half-float denorms are always retained."
1748 */
1749 p->shaderDenormFlushToZeroFloat16 = false;
1750 p->shaderDenormPreserveFloat16 = pdevice->info.gen > 8;
1751 p->shaderRoundingModeRTEFloat16 = true;
1752 p->shaderRoundingModeRTZFloat16 = true;
1753 p->shaderSignedZeroInfNanPreserveFloat16 = true;
1754
1755 p->shaderDenormFlushToZeroFloat32 = true;
1756 p->shaderDenormPreserveFloat32 = true;
1757 p->shaderRoundingModeRTEFloat32 = true;
1758 p->shaderRoundingModeRTZFloat32 = true;
1759 p->shaderSignedZeroInfNanPreserveFloat32 = true;
1760
1761 p->shaderDenormFlushToZeroFloat64 = true;
1762 p->shaderDenormPreserveFloat64 = true;
1763 p->shaderRoundingModeRTEFloat64 = true;
1764 p->shaderRoundingModeRTZFloat64 = true;
1765 p->shaderSignedZeroInfNanPreserveFloat64 = true;
1766
1767 /* It's a bit hard to exactly map our implementation to the limits
1768 * described here. The bindless surface handle in the extended
1769 * message descriptors is 20 bits and it's an index into the table of
1770 * RENDER_SURFACE_STATE structs that starts at bindless surface base
1771 * address. Given that most things consume two surface states per
1772 * view (general/sampled for textures and write-only/read-write for
1773 * images), we claim 2^19 things.
1774 *
1775 * For SSBOs, we just use A64 messages so there is no real limit
1776 * there beyond the limit on the total size of a descriptor set.
1777 */
1778 const unsigned max_bindless_views = 1 << 19;
1779 p->maxUpdateAfterBindDescriptorsInAllPools = max_bindless_views;
1780 p->shaderUniformBufferArrayNonUniformIndexingNative = false;
1781 p->shaderSampledImageArrayNonUniformIndexingNative = false;
1782 p->shaderStorageBufferArrayNonUniformIndexingNative = true;
1783 p->shaderStorageImageArrayNonUniformIndexingNative = false;
1784 p->shaderInputAttachmentArrayNonUniformIndexingNative = false;
1785 p->robustBufferAccessUpdateAfterBind = true;
1786 p->quadDivergentImplicitLod = false;
1787 p->maxPerStageDescriptorUpdateAfterBindSamplers = max_bindless_views;
1788 p->maxPerStageDescriptorUpdateAfterBindUniformBuffers = MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS;
1789 p->maxPerStageDescriptorUpdateAfterBindStorageBuffers = UINT32_MAX;
1790 p->maxPerStageDescriptorUpdateAfterBindSampledImages = max_bindless_views;
1791 p->maxPerStageDescriptorUpdateAfterBindStorageImages = max_bindless_views;
1792 p->maxPerStageDescriptorUpdateAfterBindInputAttachments = MAX_PER_STAGE_DESCRIPTOR_INPUT_ATTACHMENTS;
1793 p->maxPerStageUpdateAfterBindResources = UINT32_MAX;
1794 p->maxDescriptorSetUpdateAfterBindSamplers = max_bindless_views;
1795 p->maxDescriptorSetUpdateAfterBindUniformBuffers = 6 * MAX_PER_STAGE_DESCRIPTOR_UNIFORM_BUFFERS;
1796 p->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2;
1797 p->maxDescriptorSetUpdateAfterBindStorageBuffers = UINT32_MAX;
1798 p->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2;
1799 p->maxDescriptorSetUpdateAfterBindSampledImages = max_bindless_views;
1800 p->maxDescriptorSetUpdateAfterBindStorageImages = max_bindless_views;
1801 p->maxDescriptorSetUpdateAfterBindInputAttachments = MAX_DESCRIPTOR_SET_INPUT_ATTACHMENTS;
1802
1803 /* We support all of the depth resolve modes */
1804 p->supportedDepthResolveModes = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1805 VK_RESOLVE_MODE_AVERAGE_BIT_KHR |
1806 VK_RESOLVE_MODE_MIN_BIT_KHR |
1807 VK_RESOLVE_MODE_MAX_BIT_KHR;
1808 /* Average doesn't make sense for stencil so we don't support that */
1809 p->supportedStencilResolveModes = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR;
1810 if (pdevice->info.gen >= 8) {
1811 /* The advanced stencil resolve modes currently require stencil
1812 * sampling be supported by the hardware.
1813 */
1814 p->supportedStencilResolveModes |= VK_RESOLVE_MODE_MIN_BIT_KHR |
1815 VK_RESOLVE_MODE_MAX_BIT_KHR;
1816 }
1817 p->independentResolveNone = true;
1818 p->independentResolve = true;
1819
1820 p->filterMinmaxSingleComponentFormats = pdevice->info.gen >= 9;
1821 p->filterMinmaxImageComponentMapping = pdevice->info.gen >= 9;
1822
1823 p->maxTimelineSemaphoreValueDifference = UINT64_MAX;
1824
1825 p->framebufferIntegerColorSampleCounts =
1826 isl_device_get_sample_counts(&pdevice->isl_dev);
1827 }
1828
1829 void anv_GetPhysicalDeviceProperties2(
1830 VkPhysicalDevice physicalDevice,
1831 VkPhysicalDeviceProperties2* pProperties)
1832 {
1833 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1834
1835 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1836
1837 VkPhysicalDeviceVulkan11Properties core_1_1 = {
1838 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES,
1839 };
1840 anv_get_physical_device_properties_1_1(pdevice, &core_1_1);
1841
1842 VkPhysicalDeviceVulkan12Properties core_1_2 = {
1843 .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES,
1844 };
1845 anv_get_physical_device_properties_1_2(pdevice, &core_1_2);
1846
1847 #define CORE_RENAMED_PROPERTY(major, minor, ext_property, core_property) \
1848 memcpy(&properties->ext_property, &core_##major##_##minor.core_property, \
1849 sizeof(core_##major##_##minor.core_property))
1850
1851 #define CORE_PROPERTY(major, minor, property) \
1852 CORE_RENAMED_PROPERTY(major, minor, property, property)
1853
1854 vk_foreach_struct(ext, pProperties->pNext) {
1855 switch (ext->sType) {
1856 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CUSTOM_BORDER_COLOR_PROPERTIES_EXT: {
1857 VkPhysicalDeviceCustomBorderColorPropertiesEXT *properties =
1858 (VkPhysicalDeviceCustomBorderColorPropertiesEXT *)ext;
1859 properties->maxCustomBorderColorSamplers = MAX_CUSTOM_BORDER_COLORS;
1860 break;
1861 }
1862
1863 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR: {
1864 VkPhysicalDeviceDepthStencilResolvePropertiesKHR *properties =
1865 (VkPhysicalDeviceDepthStencilResolvePropertiesKHR *)ext;
1866 CORE_PROPERTY(1, 2, supportedDepthResolveModes);
1867 CORE_PROPERTY(1, 2, supportedStencilResolveModes);
1868 CORE_PROPERTY(1, 2, independentResolveNone);
1869 CORE_PROPERTY(1, 2, independentResolve);
1870 break;
1871 }
1872
1873 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT: {
1874 VkPhysicalDeviceDescriptorIndexingPropertiesEXT *properties =
1875 (VkPhysicalDeviceDescriptorIndexingPropertiesEXT *)ext;
1876 CORE_PROPERTY(1, 2, maxUpdateAfterBindDescriptorsInAllPools);
1877 CORE_PROPERTY(1, 2, shaderUniformBufferArrayNonUniformIndexingNative);
1878 CORE_PROPERTY(1, 2, shaderSampledImageArrayNonUniformIndexingNative);
1879 CORE_PROPERTY(1, 2, shaderStorageBufferArrayNonUniformIndexingNative);
1880 CORE_PROPERTY(1, 2, shaderStorageImageArrayNonUniformIndexingNative);
1881 CORE_PROPERTY(1, 2, shaderInputAttachmentArrayNonUniformIndexingNative);
1882 CORE_PROPERTY(1, 2, robustBufferAccessUpdateAfterBind);
1883 CORE_PROPERTY(1, 2, quadDivergentImplicitLod);
1884 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindSamplers);
1885 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindUniformBuffers);
1886 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindStorageBuffers);
1887 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindSampledImages);
1888 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindStorageImages);
1889 CORE_PROPERTY(1, 2, maxPerStageDescriptorUpdateAfterBindInputAttachments);
1890 CORE_PROPERTY(1, 2, maxPerStageUpdateAfterBindResources);
1891 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindSamplers);
1892 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindUniformBuffers);
1893 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindUniformBuffersDynamic);
1894 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageBuffers);
1895 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageBuffersDynamic);
1896 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindSampledImages);
1897 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindStorageImages);
1898 CORE_PROPERTY(1, 2, maxDescriptorSetUpdateAfterBindInputAttachments);
1899 break;
1900 }
1901
1902 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
1903 VkPhysicalDeviceDriverPropertiesKHR *properties =
1904 (VkPhysicalDeviceDriverPropertiesKHR *) ext;
1905 CORE_PROPERTY(1, 2, driverID);
1906 CORE_PROPERTY(1, 2, driverName);
1907 CORE_PROPERTY(1, 2, driverInfo);
1908 CORE_PROPERTY(1, 2, conformanceVersion);
1909 break;
1910 }
1911
1912 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1913 VkPhysicalDeviceExternalMemoryHostPropertiesEXT *props =
1914 (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1915 /* Userptr needs page aligned memory. */
1916 props->minImportedHostPointerAlignment = 4096;
1917 break;
1918 }
1919
1920 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1921 VkPhysicalDeviceIDProperties *properties =
1922 (VkPhysicalDeviceIDProperties *)ext;
1923 CORE_PROPERTY(1, 1, deviceUUID);
1924 CORE_PROPERTY(1, 1, driverUUID);
1925 CORE_PROPERTY(1, 1, deviceLUID);
1926 CORE_PROPERTY(1, 1, deviceLUIDValid);
1927 break;
1928 }
1929
1930 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT: {
1931 VkPhysicalDeviceInlineUniformBlockPropertiesEXT *props =
1932 (VkPhysicalDeviceInlineUniformBlockPropertiesEXT *)ext;
1933 props->maxInlineUniformBlockSize = MAX_INLINE_UNIFORM_BLOCK_SIZE;
1934 props->maxPerStageDescriptorInlineUniformBlocks =
1935 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1936 props->maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks =
1937 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1938 props->maxDescriptorSetInlineUniformBlocks =
1939 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1940 props->maxDescriptorSetUpdateAfterBindInlineUniformBlocks =
1941 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1942 break;
1943 }
1944
1945 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_LINE_RASTERIZATION_PROPERTIES_EXT: {
1946 VkPhysicalDeviceLineRasterizationPropertiesEXT *props =
1947 (VkPhysicalDeviceLineRasterizationPropertiesEXT *)ext;
1948 /* In the Skylake PRM Vol. 7, subsection titled "GIQ (Diamond)
1949 * Sampling Rules - Legacy Mode", it says the following:
1950 *
1951 * "Note that the device divides a pixel into a 16x16 array of
1952 * subpixels, referenced by their upper left corners."
1953 *
1954 * This is the only known reference in the PRMs to the subpixel
1955 * precision of line rasterization and a "16x16 array of subpixels"
1956 * implies 4 subpixel precision bits. Empirical testing has shown
1957 * that 4 subpixel precision bits applies to all line rasterization
1958 * types.
1959 */
1960 props->lineSubPixelPrecisionBits = 4;
1961 break;
1962 }
1963
1964 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1965 VkPhysicalDeviceMaintenance3Properties *properties =
1966 (VkPhysicalDeviceMaintenance3Properties *)ext;
1967 /* This value doesn't matter for us today as our per-stage
1968 * descriptors are the real limit.
1969 */
1970 CORE_PROPERTY(1, 1, maxPerSetDescriptors);
1971 CORE_PROPERTY(1, 1, maxMemoryAllocationSize);
1972 break;
1973 }
1974
1975 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1976 VkPhysicalDeviceMultiviewProperties *properties =
1977 (VkPhysicalDeviceMultiviewProperties *)ext;
1978 CORE_PROPERTY(1, 1, maxMultiviewViewCount);
1979 CORE_PROPERTY(1, 1, maxMultiviewInstanceIndex);
1980 break;
1981 }
1982
1983 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1984 VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1985 (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1986 properties->pciDomain = pdevice->pci_info.domain;
1987 properties->pciBus = pdevice->pci_info.bus;
1988 properties->pciDevice = pdevice->pci_info.device;
1989 properties->pciFunction = pdevice->pci_info.function;
1990 break;
1991 }
1992
1993 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PERFORMANCE_QUERY_PROPERTIES_KHR: {
1994 VkPhysicalDevicePerformanceQueryPropertiesKHR *properties =
1995 (VkPhysicalDevicePerformanceQueryPropertiesKHR *)ext;
1996 /* We could support this by spawning a shader to do the equation
1997 * normalization.
1998 */
1999 properties->allowCommandBufferQueryCopies = false;
2000 break;
2001 }
2002
2003 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
2004 VkPhysicalDevicePointClippingProperties *properties =
2005 (VkPhysicalDevicePointClippingProperties *) ext;
2006 CORE_PROPERTY(1, 1, pointClippingBehavior);
2007 break;
2008 }
2009
2010 #pragma GCC diagnostic push
2011 #pragma GCC diagnostic ignored "-Wswitch"
2012 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PRESENTATION_PROPERTIES_ANDROID: {
2013 VkPhysicalDevicePresentationPropertiesANDROID *props =
2014 (VkPhysicalDevicePresentationPropertiesANDROID *)ext;
2015 props->sharedImage = VK_FALSE;
2016 break;
2017 }
2018 #pragma GCC diagnostic pop
2019
2020 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
2021 VkPhysicalDeviceProtectedMemoryProperties *properties =
2022 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
2023 CORE_PROPERTY(1, 1, protectedNoFault);
2024 break;
2025 }
2026
2027 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
2028 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
2029 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
2030 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
2031 break;
2032 }
2033
2034 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_PROPERTIES_EXT: {
2035 VkPhysicalDeviceRobustness2PropertiesEXT *properties = (void *)ext;
2036 properties->robustStorageBufferAccessSizeAlignment =
2037 ANV_SSBO_BOUNDS_CHECK_ALIGNMENT;
2038 properties->robustUniformBufferAccessSizeAlignment =
2039 ANV_UBO_ALIGNMENT;
2040 break;
2041 }
2042
2043 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
2044 VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
2045 (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
2046 CORE_PROPERTY(1, 2, filterMinmaxImageComponentMapping);
2047 CORE_PROPERTY(1, 2, filterMinmaxSingleComponentFormats);
2048 break;
2049 }
2050
2051 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
2052 VkPhysicalDeviceSubgroupProperties *properties = (void *)ext;
2053 CORE_PROPERTY(1, 1, subgroupSize);
2054 CORE_RENAMED_PROPERTY(1, 1, supportedStages,
2055 subgroupSupportedStages);
2056 CORE_RENAMED_PROPERTY(1, 1, supportedOperations,
2057 subgroupSupportedOperations);
2058 CORE_RENAMED_PROPERTY(1, 1, quadOperationsInAllStages,
2059 subgroupQuadOperationsInAllStages);
2060 break;
2061 }
2062
2063 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_PROPERTIES_EXT: {
2064 VkPhysicalDeviceSubgroupSizeControlPropertiesEXT *props =
2065 (VkPhysicalDeviceSubgroupSizeControlPropertiesEXT *)ext;
2066 STATIC_ASSERT(8 <= BRW_SUBGROUP_SIZE && BRW_SUBGROUP_SIZE <= 32);
2067 props->minSubgroupSize = 8;
2068 props->maxSubgroupSize = 32;
2069 props->maxComputeWorkgroupSubgroups = pdevice->info.max_cs_threads;
2070 props->requiredSubgroupSizeStages = VK_SHADER_STAGE_COMPUTE_BIT;
2071 break;
2072 }
2073 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT_CONTROLS_PROPERTIES_KHR : {
2074 VkPhysicalDeviceFloatControlsPropertiesKHR *properties = (void *)ext;
2075 CORE_PROPERTY(1, 2, denormBehaviorIndependence);
2076 CORE_PROPERTY(1, 2, roundingModeIndependence);
2077 CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat16);
2078 CORE_PROPERTY(1, 2, shaderDenormPreserveFloat16);
2079 CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat16);
2080 CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat16);
2081 CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat16);
2082 CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat32);
2083 CORE_PROPERTY(1, 2, shaderDenormPreserveFloat32);
2084 CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat32);
2085 CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat32);
2086 CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat32);
2087 CORE_PROPERTY(1, 2, shaderDenormFlushToZeroFloat64);
2088 CORE_PROPERTY(1, 2, shaderDenormPreserveFloat64);
2089 CORE_PROPERTY(1, 2, shaderRoundingModeRTEFloat64);
2090 CORE_PROPERTY(1, 2, shaderRoundingModeRTZFloat64);
2091 CORE_PROPERTY(1, 2, shaderSignedZeroInfNanPreserveFloat64);
2092 break;
2093 }
2094
2095 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXEL_BUFFER_ALIGNMENT_PROPERTIES_EXT: {
2096 VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *props =
2097 (VkPhysicalDeviceTexelBufferAlignmentPropertiesEXT *)ext;
2098
2099 /* From the SKL PRM Vol. 2d, docs for RENDER_SURFACE_STATE::Surface
2100 * Base Address:
2101 *
2102 * "For SURFTYPE_BUFFER non-rendertarget surfaces, this field
2103 * specifies the base address of the first element of the surface,
2104 * computed in software by adding the surface base address to the
2105 * byte offset of the element in the buffer. The base address must
2106 * be aligned to element size."
2107 *
2108 * The typed dataport messages require that things be texel aligned.
2109 * Otherwise, we may just load/store the wrong data or, in the worst
2110 * case, there may be hangs.
2111 */
2112 props->storageTexelBufferOffsetAlignmentBytes = 16;
2113 props->storageTexelBufferOffsetSingleTexelAlignment = true;
2114
2115 /* The sampler, however, is much more forgiving and it can handle
2116 * arbitrary byte alignment for linear and buffer surfaces. It's
2117 * hard to find a good PRM citation for this but years of empirical
2118 * experience demonstrate that this is true.
2119 */
2120 props->uniformTexelBufferOffsetAlignmentBytes = 1;
2121 props->uniformTexelBufferOffsetSingleTexelAlignment = false;
2122 break;
2123 }
2124
2125 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_PROPERTIES_KHR: {
2126 VkPhysicalDeviceTimelineSemaphorePropertiesKHR *properties =
2127 (VkPhysicalDeviceTimelineSemaphorePropertiesKHR *) ext;
2128 CORE_PROPERTY(1, 2, maxTimelineSemaphoreValueDifference);
2129 break;
2130 }
2131
2132 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
2133 VkPhysicalDeviceTransformFeedbackPropertiesEXT *props =
2134 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
2135
2136 props->maxTransformFeedbackStreams = MAX_XFB_STREAMS;
2137 props->maxTransformFeedbackBuffers = MAX_XFB_BUFFERS;
2138 props->maxTransformFeedbackBufferSize = (1ull << 32);
2139 props->maxTransformFeedbackStreamDataSize = 128 * 4;
2140 props->maxTransformFeedbackBufferDataSize = 128 * 4;
2141 props->maxTransformFeedbackBufferDataStride = 2048;
2142 props->transformFeedbackQueries = true;
2143 props->transformFeedbackStreamsLinesTriangles = false;
2144 props->transformFeedbackRasterizationStreamSelect = false;
2145 props->transformFeedbackDraw = true;
2146 break;
2147 }
2148
2149 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
2150 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *props =
2151 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
2152 /* We have to restrict this a bit for multiview */
2153 props->maxVertexAttribDivisor = UINT32_MAX / 16;
2154 break;
2155 }
2156
2157 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_PROPERTIES:
2158 anv_get_physical_device_properties_1_1(pdevice, (void *)ext);
2159 break;
2160
2161 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_PROPERTIES:
2162 anv_get_physical_device_properties_1_2(pdevice, (void *)ext);
2163 break;
2164
2165 default:
2166 anv_debug_ignored_stype(ext->sType);
2167 break;
2168 }
2169 }
2170
2171 #undef CORE_RENAMED_PROPERTY
2172 #undef CORE_PROPERTY
2173 }
2174
2175 /* We support exactly one queue family. */
2176 static const VkQueueFamilyProperties
2177 anv_queue_family_properties = {
2178 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
2179 VK_QUEUE_COMPUTE_BIT |
2180 VK_QUEUE_TRANSFER_BIT,
2181 .queueCount = 1,
2182 .timestampValidBits = 36, /* XXX: Real value here */
2183 .minImageTransferGranularity = { 1, 1, 1 },
2184 };
2185
2186 void anv_GetPhysicalDeviceQueueFamilyProperties(
2187 VkPhysicalDevice physicalDevice,
2188 uint32_t* pCount,
2189 VkQueueFamilyProperties* pQueueFamilyProperties)
2190 {
2191 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
2192
2193 vk_outarray_append(&out, p) {
2194 *p = anv_queue_family_properties;
2195 }
2196 }
2197
2198 void anv_GetPhysicalDeviceQueueFamilyProperties2(
2199 VkPhysicalDevice physicalDevice,
2200 uint32_t* pQueueFamilyPropertyCount,
2201 VkQueueFamilyProperties2* pQueueFamilyProperties)
2202 {
2203
2204 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
2205
2206 vk_outarray_append(&out, p) {
2207 p->queueFamilyProperties = anv_queue_family_properties;
2208
2209 vk_foreach_struct(s, p->pNext) {
2210 anv_debug_ignored_stype(s->sType);
2211 }
2212 }
2213 }
2214
2215 void anv_GetPhysicalDeviceMemoryProperties(
2216 VkPhysicalDevice physicalDevice,
2217 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
2218 {
2219 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
2220
2221 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
2222 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
2223 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
2224 .propertyFlags = physical_device->memory.types[i].propertyFlags,
2225 .heapIndex = physical_device->memory.types[i].heapIndex,
2226 };
2227 }
2228
2229 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
2230 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
2231 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
2232 .size = physical_device->memory.heaps[i].size,
2233 .flags = physical_device->memory.heaps[i].flags,
2234 };
2235 }
2236 }
2237
2238 static void
2239 anv_get_memory_budget(VkPhysicalDevice physicalDevice,
2240 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memoryBudget)
2241 {
2242 ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
2243 uint64_t sys_available = get_available_system_memory();
2244 assert(sys_available > 0);
2245
2246 VkDeviceSize total_heaps_size = 0;
2247 for (size_t i = 0; i < device->memory.heap_count; i++)
2248 total_heaps_size += device->memory.heaps[i].size;
2249
2250 for (size_t i = 0; i < device->memory.heap_count; i++) {
2251 VkDeviceSize heap_size = device->memory.heaps[i].size;
2252 VkDeviceSize heap_used = device->memory.heaps[i].used;
2253 VkDeviceSize heap_budget;
2254
2255 double heap_proportion = (double) heap_size / total_heaps_size;
2256 VkDeviceSize sys_available_prop = sys_available * heap_proportion;
2257
2258 /*
2259 * Let's not incite the app to starve the system: report at most 90% of
2260 * available system memory.
2261 */
2262 uint64_t heap_available = sys_available_prop * 9 / 10;
2263 heap_budget = MIN2(heap_size, heap_used + heap_available);
2264
2265 /*
2266 * Round down to the nearest MB
2267 */
2268 heap_budget &= ~((1ull << 20) - 1);
2269
2270 /*
2271 * The heapBudget value must be non-zero for array elements less than
2272 * VkPhysicalDeviceMemoryProperties::memoryHeapCount. The heapBudget
2273 * value must be less than or equal to VkMemoryHeap::size for each heap.
2274 */
2275 assert(0 < heap_budget && heap_budget <= heap_size);
2276
2277 memoryBudget->heapUsage[i] = heap_used;
2278 memoryBudget->heapBudget[i] = heap_budget;
2279 }
2280
2281 /* The heapBudget and heapUsage values must be zero for array elements
2282 * greater than or equal to VkPhysicalDeviceMemoryProperties::memoryHeapCount
2283 */
2284 for (uint32_t i = device->memory.heap_count; i < VK_MAX_MEMORY_HEAPS; i++) {
2285 memoryBudget->heapBudget[i] = 0;
2286 memoryBudget->heapUsage[i] = 0;
2287 }
2288 }
2289
2290 void anv_GetPhysicalDeviceMemoryProperties2(
2291 VkPhysicalDevice physicalDevice,
2292 VkPhysicalDeviceMemoryProperties2* pMemoryProperties)
2293 {
2294 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
2295 &pMemoryProperties->memoryProperties);
2296
2297 vk_foreach_struct(ext, pMemoryProperties->pNext) {
2298 switch (ext->sType) {
2299 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT:
2300 anv_get_memory_budget(physicalDevice, (void*)ext);
2301 break;
2302 default:
2303 anv_debug_ignored_stype(ext->sType);
2304 break;
2305 }
2306 }
2307 }
2308
2309 void
2310 anv_GetDeviceGroupPeerMemoryFeatures(
2311 VkDevice device,
2312 uint32_t heapIndex,
2313 uint32_t localDeviceIndex,
2314 uint32_t remoteDeviceIndex,
2315 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
2316 {
2317 assert(localDeviceIndex == 0 && remoteDeviceIndex == 0);
2318 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
2319 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
2320 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
2321 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
2322 }
2323
2324 PFN_vkVoidFunction anv_GetInstanceProcAddr(
2325 VkInstance _instance,
2326 const char* pName)
2327 {
2328 ANV_FROM_HANDLE(anv_instance, instance, _instance);
2329
2330 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
2331 * when we have to return valid function pointers, NULL, or it's left
2332 * undefined. See the table for exact details.
2333 */
2334 if (pName == NULL)
2335 return NULL;
2336
2337 #define LOOKUP_ANV_ENTRYPOINT(entrypoint) \
2338 if (strcmp(pName, "vk" #entrypoint) == 0) \
2339 return (PFN_vkVoidFunction)anv_##entrypoint
2340
2341 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
2342 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceLayerProperties);
2343 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceVersion);
2344 LOOKUP_ANV_ENTRYPOINT(CreateInstance);
2345
2346 /* GetInstanceProcAddr() can also be called with a NULL instance.
2347 * See https://gitlab.khronos.org/vulkan/vulkan/issues/2057
2348 */
2349 LOOKUP_ANV_ENTRYPOINT(GetInstanceProcAddr);
2350
2351 #undef LOOKUP_ANV_ENTRYPOINT
2352
2353 if (instance == NULL)
2354 return NULL;
2355
2356 int idx = anv_get_instance_entrypoint_index(pName);
2357 if (idx >= 0)
2358 return instance->dispatch.entrypoints[idx];
2359
2360 idx = anv_get_physical_device_entrypoint_index(pName);
2361 if (idx >= 0)
2362 return instance->physical_device_dispatch.entrypoints[idx];
2363
2364 idx = anv_get_device_entrypoint_index(pName);
2365 if (idx >= 0)
2366 return instance->device_dispatch.entrypoints[idx];
2367
2368 return NULL;
2369 }
2370
2371 /* With version 1+ of the loader interface the ICD should expose
2372 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
2373 */
2374 PUBLIC
2375 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
2376 VkInstance instance,
2377 const char* pName);
2378
2379 PUBLIC
2380 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
2381 VkInstance instance,
2382 const char* pName)
2383 {
2384 return anv_GetInstanceProcAddr(instance, pName);
2385 }
2386
2387 PFN_vkVoidFunction anv_GetDeviceProcAddr(
2388 VkDevice _device,
2389 const char* pName)
2390 {
2391 ANV_FROM_HANDLE(anv_device, device, _device);
2392
2393 if (!device || !pName)
2394 return NULL;
2395
2396 int idx = anv_get_device_entrypoint_index(pName);
2397 if (idx < 0)
2398 return NULL;
2399
2400 return device->dispatch.entrypoints[idx];
2401 }
2402
2403 /* With version 4+ of the loader interface the ICD should expose
2404 * vk_icdGetPhysicalDeviceProcAddr()
2405 */
2406 PUBLIC
2407 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
2408 VkInstance _instance,
2409 const char* pName);
2410
2411 PFN_vkVoidFunction vk_icdGetPhysicalDeviceProcAddr(
2412 VkInstance _instance,
2413 const char* pName)
2414 {
2415 ANV_FROM_HANDLE(anv_instance, instance, _instance);
2416
2417 if (!pName || !instance)
2418 return NULL;
2419
2420 int idx = anv_get_physical_device_entrypoint_index(pName);
2421 if (idx < 0)
2422 return NULL;
2423
2424 return instance->physical_device_dispatch.entrypoints[idx];
2425 }
2426
2427
2428 VkResult
2429 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
2430 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
2431 const VkAllocationCallbacks* pAllocator,
2432 VkDebugReportCallbackEXT* pCallback)
2433 {
2434 ANV_FROM_HANDLE(anv_instance, instance, _instance);
2435 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
2436 pCreateInfo, pAllocator, &instance->alloc,
2437 pCallback);
2438 }
2439
2440 void
2441 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
2442 VkDebugReportCallbackEXT _callback,
2443 const VkAllocationCallbacks* pAllocator)
2444 {
2445 ANV_FROM_HANDLE(anv_instance, instance, _instance);
2446 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
2447 _callback, pAllocator, &instance->alloc);
2448 }
2449
2450 void
2451 anv_DebugReportMessageEXT(VkInstance _instance,
2452 VkDebugReportFlagsEXT flags,
2453 VkDebugReportObjectTypeEXT objectType,
2454 uint64_t object,
2455 size_t location,
2456 int32_t messageCode,
2457 const char* pLayerPrefix,
2458 const char* pMessage)
2459 {
2460 ANV_FROM_HANDLE(anv_instance, instance, _instance);
2461 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
2462 object, location, messageCode, pLayerPrefix, pMessage);
2463 }
2464
2465 static struct anv_state
2466 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
2467 {
2468 struct anv_state state;
2469
2470 state = anv_state_pool_alloc(pool, size, align);
2471 memcpy(state.map, p, size);
2472
2473 return state;
2474 }
2475
2476 static void
2477 anv_device_init_border_colors(struct anv_device *device)
2478 {
2479 if (device->info.is_haswell) {
2480 static const struct hsw_border_color border_colors[] = {
2481 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
2482 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
2483 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
2484 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
2485 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
2486 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
2487 };
2488
2489 device->border_colors =
2490 anv_state_pool_emit_data(&device->dynamic_state_pool,
2491 sizeof(border_colors), 512, border_colors);
2492 } else {
2493 static const struct gen8_border_color border_colors[] = {
2494 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
2495 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
2496 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
2497 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
2498 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
2499 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
2500 };
2501
2502 device->border_colors =
2503 anv_state_pool_emit_data(&device->dynamic_state_pool,
2504 sizeof(border_colors), 64, border_colors);
2505 }
2506 }
2507
2508 static VkResult
2509 anv_device_init_trivial_batch(struct anv_device *device)
2510 {
2511 VkResult result = anv_device_alloc_bo(device, 4096,
2512 ANV_BO_ALLOC_MAPPED,
2513 0 /* explicit_address */,
2514 &device->trivial_batch_bo);
2515 if (result != VK_SUCCESS)
2516 return result;
2517
2518 struct anv_batch batch = {
2519 .start = device->trivial_batch_bo->map,
2520 .next = device->trivial_batch_bo->map,
2521 .end = device->trivial_batch_bo->map + 4096,
2522 };
2523
2524 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
2525 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
2526
2527 if (!device->info.has_llc)
2528 gen_clflush_range(batch.start, batch.next - batch.start);
2529
2530 return VK_SUCCESS;
2531 }
2532
2533 VkResult anv_EnumerateDeviceExtensionProperties(
2534 VkPhysicalDevice physicalDevice,
2535 const char* pLayerName,
2536 uint32_t* pPropertyCount,
2537 VkExtensionProperties* pProperties)
2538 {
2539 ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
2540 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
2541
2542 for (int i = 0; i < ANV_DEVICE_EXTENSION_COUNT; i++) {
2543 if (device->supported_extensions.extensions[i]) {
2544 vk_outarray_append(&out, prop) {
2545 *prop = anv_device_extensions[i];
2546 }
2547 }
2548 }
2549
2550 return vk_outarray_status(&out);
2551 }
2552
2553 static int
2554 vk_priority_to_gen(int priority)
2555 {
2556 switch (priority) {
2557 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
2558 return GEN_CONTEXT_LOW_PRIORITY;
2559 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
2560 return GEN_CONTEXT_MEDIUM_PRIORITY;
2561 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
2562 return GEN_CONTEXT_HIGH_PRIORITY;
2563 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
2564 return GEN_CONTEXT_REALTIME_PRIORITY;
2565 default:
2566 unreachable("Invalid priority");
2567 }
2568 }
2569
2570 static VkResult
2571 anv_device_init_hiz_clear_value_bo(struct anv_device *device)
2572 {
2573 VkResult result = anv_device_alloc_bo(device, 4096,
2574 ANV_BO_ALLOC_MAPPED,
2575 0 /* explicit_address */,
2576 &device->hiz_clear_bo);
2577 if (result != VK_SUCCESS)
2578 return result;
2579
2580 union isl_color_value hiz_clear = { .u32 = { 0, } };
2581 hiz_clear.f32[0] = ANV_HZ_FC_VAL;
2582
2583 memcpy(device->hiz_clear_bo->map, hiz_clear.u32, sizeof(hiz_clear.u32));
2584
2585 if (!device->info.has_llc)
2586 gen_clflush_range(device->hiz_clear_bo->map, sizeof(hiz_clear.u32));
2587
2588 return VK_SUCCESS;
2589 }
2590
2591 static bool
2592 get_bo_from_pool(struct gen_batch_decode_bo *ret,
2593 struct anv_block_pool *pool,
2594 uint64_t address)
2595 {
2596 anv_block_pool_foreach_bo(bo, pool) {
2597 uint64_t bo_address = gen_48b_address(bo->offset);
2598 if (address >= bo_address && address < (bo_address + bo->size)) {
2599 *ret = (struct gen_batch_decode_bo) {
2600 .addr = bo_address,
2601 .size = bo->size,
2602 .map = bo->map,
2603 };
2604 return true;
2605 }
2606 }
2607 return false;
2608 }
2609
2610 /* Finding a buffer for batch decoding */
2611 static struct gen_batch_decode_bo
2612 decode_get_bo(void *v_batch, bool ppgtt, uint64_t address)
2613 {
2614 struct anv_device *device = v_batch;
2615 struct gen_batch_decode_bo ret_bo = {};
2616
2617 assert(ppgtt);
2618
2619 if (get_bo_from_pool(&ret_bo, &device->dynamic_state_pool.block_pool, address))
2620 return ret_bo;
2621 if (get_bo_from_pool(&ret_bo, &device->instruction_state_pool.block_pool, address))
2622 return ret_bo;
2623 if (get_bo_from_pool(&ret_bo, &device->binding_table_pool.block_pool, address))
2624 return ret_bo;
2625 if (get_bo_from_pool(&ret_bo, &device->surface_state_pool.block_pool, address))
2626 return ret_bo;
2627
2628 if (!device->cmd_buffer_being_decoded)
2629 return (struct gen_batch_decode_bo) { };
2630
2631 struct anv_batch_bo **bo;
2632
2633 u_vector_foreach(bo, &device->cmd_buffer_being_decoded->seen_bbos) {
2634 /* The decoder zeroes out the top 16 bits, so we need to as well */
2635 uint64_t bo_address = (*bo)->bo->offset & (~0ull >> 16);
2636
2637 if (address >= bo_address && address < bo_address + (*bo)->bo->size) {
2638 return (struct gen_batch_decode_bo) {
2639 .addr = bo_address,
2640 .size = (*bo)->bo->size,
2641 .map = (*bo)->bo->map,
2642 };
2643 }
2644 }
2645
2646 return (struct gen_batch_decode_bo) { };
2647 }
2648
2649 struct gen_aux_map_buffer {
2650 struct gen_buffer base;
2651 struct anv_state state;
2652 };
2653
2654 static struct gen_buffer *
2655 gen_aux_map_buffer_alloc(void *driver_ctx, uint32_t size)
2656 {
2657 struct gen_aux_map_buffer *buf = malloc(sizeof(struct gen_aux_map_buffer));
2658 if (!buf)
2659 return NULL;
2660
2661 struct anv_device *device = (struct anv_device*)driver_ctx;
2662 assert(device->physical->supports_48bit_addresses &&
2663 device->physical->use_softpin);
2664
2665 struct anv_state_pool *pool = &device->dynamic_state_pool;
2666 buf->state = anv_state_pool_alloc(pool, size, size);
2667
2668 buf->base.gpu = pool->block_pool.bo->offset + buf->state.offset;
2669 buf->base.gpu_end = buf->base.gpu + buf->state.alloc_size;
2670 buf->base.map = buf->state.map;
2671 buf->base.driver_bo = &buf->state;
2672 return &buf->base;
2673 }
2674
2675 static void
2676 gen_aux_map_buffer_free(void *driver_ctx, struct gen_buffer *buffer)
2677 {
2678 struct gen_aux_map_buffer *buf = (struct gen_aux_map_buffer*)buffer;
2679 struct anv_device *device = (struct anv_device*)driver_ctx;
2680 struct anv_state_pool *pool = &device->dynamic_state_pool;
2681 anv_state_pool_free(pool, buf->state);
2682 free(buf);
2683 }
2684
2685 static struct gen_mapped_pinned_buffer_alloc aux_map_allocator = {
2686 .alloc = gen_aux_map_buffer_alloc,
2687 .free = gen_aux_map_buffer_free,
2688 };
2689
2690 static VkResult
2691 check_physical_device_features(VkPhysicalDevice physicalDevice,
2692 const VkPhysicalDeviceFeatures *features)
2693 {
2694 VkPhysicalDeviceFeatures supported_features;
2695 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
2696 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
2697 VkBool32 *enabled_feature = (VkBool32 *)features;
2698 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
2699 for (uint32_t i = 0; i < num_features; i++) {
2700 if (enabled_feature[i] && !supported_feature[i])
2701 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2702 }
2703
2704 return VK_SUCCESS;
2705 }
2706
2707 VkResult anv_CreateDevice(
2708 VkPhysicalDevice physicalDevice,
2709 const VkDeviceCreateInfo* pCreateInfo,
2710 const VkAllocationCallbacks* pAllocator,
2711 VkDevice* pDevice)
2712 {
2713 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
2714 VkResult result;
2715 struct anv_device *device;
2716
2717 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
2718
2719 struct anv_device_extension_table enabled_extensions = { };
2720 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
2721 int idx;
2722 for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
2723 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
2724 anv_device_extensions[idx].extensionName) == 0)
2725 break;
2726 }
2727
2728 if (idx >= ANV_DEVICE_EXTENSION_COUNT)
2729 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
2730
2731 if (!physical_device->supported_extensions.extensions[idx])
2732 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
2733
2734 enabled_extensions.extensions[idx] = true;
2735 }
2736
2737 /* Check enabled features */
2738 bool robust_buffer_access = false;
2739 if (pCreateInfo->pEnabledFeatures) {
2740 result = check_physical_device_features(physicalDevice,
2741 pCreateInfo->pEnabledFeatures);
2742 if (result != VK_SUCCESS)
2743 return result;
2744
2745 if (pCreateInfo->pEnabledFeatures->robustBufferAccess)
2746 robust_buffer_access = true;
2747 }
2748
2749 vk_foreach_struct_const(ext, pCreateInfo->pNext) {
2750 switch (ext->sType) {
2751 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: {
2752 const VkPhysicalDeviceFeatures2 *features = (const void *)ext;
2753 result = check_physical_device_features(physicalDevice,
2754 &features->features);
2755 if (result != VK_SUCCESS)
2756 return result;
2757
2758 if (features->features.robustBufferAccess)
2759 robust_buffer_access = true;
2760 break;
2761 }
2762
2763 default:
2764 /* Don't warn */
2765 break;
2766 }
2767 }
2768
2769 /* Check requested queues and fail if we are requested to create any
2770 * queues with flags we don't support.
2771 */
2772 assert(pCreateInfo->queueCreateInfoCount > 0);
2773 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
2774 if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
2775 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
2776 }
2777
2778 /* Check if client specified queue priority. */
2779 const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
2780 vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
2781 DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
2782
2783 VkQueueGlobalPriorityEXT priority =
2784 queue_priority ? queue_priority->globalPriority :
2785 VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
2786
2787 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
2788 sizeof(*device), 8,
2789 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2790 if (!device)
2791 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2792
2793 vk_device_init(&device->vk, pCreateInfo,
2794 &physical_device->instance->alloc, pAllocator);
2795
2796 if (INTEL_DEBUG & DEBUG_BATCH) {
2797 const unsigned decode_flags =
2798 GEN_BATCH_DECODE_FULL |
2799 ((INTEL_DEBUG & DEBUG_COLOR) ? GEN_BATCH_DECODE_IN_COLOR : 0) |
2800 GEN_BATCH_DECODE_OFFSETS |
2801 GEN_BATCH_DECODE_FLOATS;
2802
2803 gen_batch_decode_ctx_init(&device->decoder_ctx,
2804 &physical_device->info,
2805 stderr, decode_flags, NULL,
2806 decode_get_bo, NULL, device);
2807 }
2808
2809 device->physical = physical_device;
2810 device->no_hw = physical_device->no_hw;
2811 device->_lost = false;
2812
2813 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
2814 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
2815 if (device->fd == -1) {
2816 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2817 goto fail_device;
2818 }
2819
2820 device->context_id = anv_gem_create_context(device);
2821 if (device->context_id == -1) {
2822 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2823 goto fail_fd;
2824 }
2825
2826 device->has_thread_submit = physical_device->has_thread_submit;
2827
2828 result = anv_queue_init(device, &device->queue);
2829 if (result != VK_SUCCESS)
2830 goto fail_context_id;
2831
2832 if (physical_device->use_softpin) {
2833 if (pthread_mutex_init(&device->vma_mutex, NULL) != 0) {
2834 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2835 goto fail_queue;
2836 }
2837
2838 /* keep the page with address zero out of the allocator */
2839 util_vma_heap_init(&device->vma_lo,
2840 LOW_HEAP_MIN_ADDRESS, LOW_HEAP_SIZE);
2841
2842 util_vma_heap_init(&device->vma_cva, CLIENT_VISIBLE_HEAP_MIN_ADDRESS,
2843 CLIENT_VISIBLE_HEAP_SIZE);
2844
2845 /* Leave the last 4GiB out of the high vma range, so that no state
2846 * base address + size can overflow 48 bits. For more information see
2847 * the comment about Wa32bitGeneralStateOffset in anv_allocator.c
2848 */
2849 util_vma_heap_init(&device->vma_hi, HIGH_HEAP_MIN_ADDRESS,
2850 physical_device->gtt_size - (1ull << 32) -
2851 HIGH_HEAP_MIN_ADDRESS);
2852 }
2853
2854 list_inithead(&device->memory_objects);
2855
2856 /* As per spec, the driver implementation may deny requests to acquire
2857 * a priority above the default priority (MEDIUM) if the caller does not
2858 * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
2859 * is returned.
2860 */
2861 if (physical_device->has_context_priority) {
2862 int err = anv_gem_set_context_param(device->fd, device->context_id,
2863 I915_CONTEXT_PARAM_PRIORITY,
2864 vk_priority_to_gen(priority));
2865 if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
2866 result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
2867 goto fail_vmas;
2868 }
2869 }
2870
2871 device->info = physical_device->info;
2872 device->isl_dev = physical_device->isl_dev;
2873
2874 /* On Broadwell and later, we can use batch chaining to more efficiently
2875 * implement growing command buffers. Prior to Haswell, the kernel
2876 * command parser gets in the way and we have to fall back to growing
2877 * the batch.
2878 */
2879 device->can_chain_batches = device->info.gen >= 8;
2880
2881 device->robust_buffer_access = robust_buffer_access;
2882 device->enabled_extensions = enabled_extensions;
2883
2884 const struct anv_instance *instance = physical_device->instance;
2885 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
2886 /* Vulkan requires that entrypoints for extensions which have not been
2887 * enabled must not be advertised.
2888 */
2889 if (!anv_device_entrypoint_is_enabled(i, instance->app_info.api_version,
2890 &instance->enabled_extensions,
2891 &device->enabled_extensions)) {
2892 device->dispatch.entrypoints[i] = NULL;
2893 } else {
2894 device->dispatch.entrypoints[i] =
2895 anv_resolve_device_entrypoint(&device->info, i);
2896 }
2897 }
2898
2899 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
2900 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2901 goto fail_queue;
2902 }
2903
2904 pthread_condattr_t condattr;
2905 if (pthread_condattr_init(&condattr) != 0) {
2906 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2907 goto fail_mutex;
2908 }
2909 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
2910 pthread_condattr_destroy(&condattr);
2911 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2912 goto fail_mutex;
2913 }
2914 if (pthread_cond_init(&device->queue_submit, &condattr) != 0) {
2915 pthread_condattr_destroy(&condattr);
2916 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2917 goto fail_mutex;
2918 }
2919 pthread_condattr_destroy(&condattr);
2920
2921 result = anv_bo_cache_init(&device->bo_cache);
2922 if (result != VK_SUCCESS)
2923 goto fail_queue_cond;
2924
2925 anv_bo_pool_init(&device->batch_bo_pool, device);
2926
2927 result = anv_state_pool_init(&device->dynamic_state_pool, device,
2928 DYNAMIC_STATE_POOL_MIN_ADDRESS, 0, 16384);
2929 if (result != VK_SUCCESS)
2930 goto fail_batch_bo_pool;
2931
2932 if (device->info.gen >= 8) {
2933 /* The border color pointer is limited to 24 bits, so we need to make
2934 * sure that any such color used at any point in the program doesn't
2935 * exceed that limit.
2936 * We achieve that by reserving all the custom border colors we support
2937 * right off the bat, so they are close to the base address.
2938 */
2939 anv_state_reserved_pool_init(&device->custom_border_colors,
2940 &device->dynamic_state_pool,
2941 MAX_CUSTOM_BORDER_COLORS,
2942 sizeof(struct gen8_border_color), 64);
2943 }
2944
2945 result = anv_state_pool_init(&device->instruction_state_pool, device,
2946 INSTRUCTION_STATE_POOL_MIN_ADDRESS, 0, 16384);
2947 if (result != VK_SUCCESS)
2948 goto fail_dynamic_state_pool;
2949
2950 result = anv_state_pool_init(&device->surface_state_pool, device,
2951 SURFACE_STATE_POOL_MIN_ADDRESS, 0, 4096);
2952 if (result != VK_SUCCESS)
2953 goto fail_instruction_state_pool;
2954
2955 if (physical_device->use_softpin) {
2956 int64_t bt_pool_offset = (int64_t)BINDING_TABLE_POOL_MIN_ADDRESS -
2957 (int64_t)SURFACE_STATE_POOL_MIN_ADDRESS;
2958 assert(INT32_MIN < bt_pool_offset && bt_pool_offset < 0);
2959 result = anv_state_pool_init(&device->binding_table_pool, device,
2960 SURFACE_STATE_POOL_MIN_ADDRESS,
2961 bt_pool_offset, 4096);
2962 if (result != VK_SUCCESS)
2963 goto fail_surface_state_pool;
2964 }
2965
2966 if (device->info.has_aux_map) {
2967 device->aux_map_ctx = gen_aux_map_init(device, &aux_map_allocator,
2968 &physical_device->info);
2969 if (!device->aux_map_ctx)
2970 goto fail_binding_table_pool;
2971 }
2972
2973 result = anv_device_alloc_bo(device, 4096,
2974 ANV_BO_ALLOC_CAPTURE | ANV_BO_ALLOC_MAPPED /* flags */,
2975 0 /* explicit_address */,
2976 &device->workaround_bo);
2977 if (result != VK_SUCCESS)
2978 goto fail_surface_aux_map_pool;
2979
2980 device->workaround_address = (struct anv_address) {
2981 .bo = device->workaround_bo,
2982 .offset = align_u32(
2983 intel_debug_write_identifiers(device->workaround_bo->map,
2984 device->workaround_bo->size,
2985 "Anv") + 8, 8),
2986 };
2987
2988 device->debug_frame_desc =
2989 intel_debug_get_identifier_block(device->workaround_bo->map,
2990 device->workaround_bo->size,
2991 GEN_DEBUG_BLOCK_TYPE_FRAME);
2992
2993 result = anv_device_init_trivial_batch(device);
2994 if (result != VK_SUCCESS)
2995 goto fail_workaround_bo;
2996
2997 /* Allocate a null surface state at surface state offset 0. This makes
2998 * NULL descriptor handling trivial because we can just memset structures
2999 * to zero and they have a valid descriptor.
3000 */
3001 device->null_surface_state =
3002 anv_state_pool_alloc(&device->surface_state_pool,
3003 device->isl_dev.ss.size,
3004 device->isl_dev.ss.align);
3005 isl_null_fill_state(&device->isl_dev, device->null_surface_state.map,
3006 isl_extent3d(1, 1, 1) /* This shouldn't matter */);
3007 assert(device->null_surface_state.offset == 0);
3008
3009 if (device->info.gen >= 10) {
3010 result = anv_device_init_hiz_clear_value_bo(device);
3011 if (result != VK_SUCCESS)
3012 goto fail_trivial_batch_bo;
3013 }
3014
3015 anv_scratch_pool_init(device, &device->scratch_pool);
3016
3017 switch (device->info.gen) {
3018 case 7:
3019 if (!device->info.is_haswell)
3020 result = gen7_init_device_state(device);
3021 else
3022 result = gen75_init_device_state(device);
3023 break;
3024 case 8:
3025 result = gen8_init_device_state(device);
3026 break;
3027 case 9:
3028 result = gen9_init_device_state(device);
3029 break;
3030 case 10:
3031 result = gen10_init_device_state(device);
3032 break;
3033 case 11:
3034 result = gen11_init_device_state(device);
3035 break;
3036 case 12:
3037 result = gen12_init_device_state(device);
3038 break;
3039 default:
3040 /* Shouldn't get here as we don't create physical devices for any other
3041 * gens. */
3042 unreachable("unhandled gen");
3043 }
3044 if (result != VK_SUCCESS)
3045 goto fail_clear_value_bo;
3046
3047 anv_pipeline_cache_init(&device->default_pipeline_cache, device,
3048 true /* cache_enabled */, false /* external_sync */);
3049
3050 anv_device_init_blorp(device);
3051
3052 anv_device_init_border_colors(device);
3053
3054 anv_device_perf_init(device);
3055
3056 *pDevice = anv_device_to_handle(device);
3057
3058 return VK_SUCCESS;
3059
3060 fail_clear_value_bo:
3061 if (device->info.gen >= 10)
3062 anv_device_release_bo(device, device->hiz_clear_bo);
3063 anv_scratch_pool_finish(device, &device->scratch_pool);
3064 fail_trivial_batch_bo:
3065 anv_device_release_bo(device, device->trivial_batch_bo);
3066 fail_workaround_bo:
3067 anv_device_release_bo(device, device->workaround_bo);
3068 fail_surface_aux_map_pool:
3069 if (device->info.has_aux_map) {
3070 gen_aux_map_finish(device->aux_map_ctx);
3071 device->aux_map_ctx = NULL;
3072 }
3073 fail_binding_table_pool:
3074 if (physical_device->use_softpin)
3075 anv_state_pool_finish(&device->binding_table_pool);
3076 fail_surface_state_pool:
3077 anv_state_pool_finish(&device->surface_state_pool);
3078 fail_instruction_state_pool:
3079 anv_state_pool_finish(&device->instruction_state_pool);
3080 fail_dynamic_state_pool:
3081 if (device->info.gen >= 8)
3082 anv_state_reserved_pool_finish(&device->custom_border_colors);
3083 anv_state_pool_finish(&device->dynamic_state_pool);
3084 fail_batch_bo_pool:
3085 anv_bo_pool_finish(&device->batch_bo_pool);
3086 anv_bo_cache_finish(&device->bo_cache);
3087 fail_queue_cond:
3088 pthread_cond_destroy(&device->queue_submit);
3089 fail_mutex:
3090 pthread_mutex_destroy(&device->mutex);
3091 fail_vmas:
3092 if (physical_device->use_softpin) {
3093 util_vma_heap_finish(&device->vma_hi);
3094 util_vma_heap_finish(&device->vma_cva);
3095 util_vma_heap_finish(&device->vma_lo);
3096 }
3097 fail_queue:
3098 anv_queue_finish(&device->queue);
3099 fail_context_id:
3100 anv_gem_destroy_context(device, device->context_id);
3101 fail_fd:
3102 close(device->fd);
3103 fail_device:
3104 vk_free(&device->vk.alloc, device);
3105
3106 return result;
3107 }
3108
3109 void anv_DestroyDevice(
3110 VkDevice _device,
3111 const VkAllocationCallbacks* pAllocator)
3112 {
3113 ANV_FROM_HANDLE(anv_device, device, _device);
3114
3115 if (!device)
3116 return;
3117
3118 anv_queue_finish(&device->queue);
3119
3120 anv_device_finish_blorp(device);
3121
3122 anv_pipeline_cache_finish(&device->default_pipeline_cache);
3123
3124 #ifdef HAVE_VALGRIND
3125 /* We only need to free these to prevent valgrind errors. The backing
3126 * BO will go away in a couple of lines so we don't actually leak.
3127 */
3128 if (device->info.gen >= 8)
3129 anv_state_reserved_pool_finish(&device->custom_border_colors);
3130 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
3131 anv_state_pool_free(&device->dynamic_state_pool, device->slice_hash);
3132 #endif
3133
3134 anv_scratch_pool_finish(device, &device->scratch_pool);
3135
3136 anv_device_release_bo(device, device->workaround_bo);
3137 anv_device_release_bo(device, device->trivial_batch_bo);
3138 if (device->info.gen >= 10)
3139 anv_device_release_bo(device, device->hiz_clear_bo);
3140
3141 if (device->info.has_aux_map) {
3142 gen_aux_map_finish(device->aux_map_ctx);
3143 device->aux_map_ctx = NULL;
3144 }
3145
3146 if (device->physical->use_softpin)
3147 anv_state_pool_finish(&device->binding_table_pool);
3148 anv_state_pool_finish(&device->surface_state_pool);
3149 anv_state_pool_finish(&device->instruction_state_pool);
3150 anv_state_pool_finish(&device->dynamic_state_pool);
3151
3152 anv_bo_pool_finish(&device->batch_bo_pool);
3153
3154 anv_bo_cache_finish(&device->bo_cache);
3155
3156 if (device->physical->use_softpin) {
3157 util_vma_heap_finish(&device->vma_hi);
3158 util_vma_heap_finish(&device->vma_cva);
3159 util_vma_heap_finish(&device->vma_lo);
3160 }
3161
3162 pthread_cond_destroy(&device->queue_submit);
3163 pthread_mutex_destroy(&device->mutex);
3164
3165 anv_gem_destroy_context(device, device->context_id);
3166
3167 if (INTEL_DEBUG & DEBUG_BATCH)
3168 gen_batch_decode_ctx_finish(&device->decoder_ctx);
3169
3170 close(device->fd);
3171
3172 vk_device_finish(&device->vk);
3173 vk_free(&device->vk.alloc, device);
3174 }
3175
3176 VkResult anv_EnumerateInstanceLayerProperties(
3177 uint32_t* pPropertyCount,
3178 VkLayerProperties* pProperties)
3179 {
3180 if (pProperties == NULL) {
3181 *pPropertyCount = 0;
3182 return VK_SUCCESS;
3183 }
3184
3185 /* None supported at this time */
3186 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
3187 }
3188
3189 VkResult anv_EnumerateDeviceLayerProperties(
3190 VkPhysicalDevice physicalDevice,
3191 uint32_t* pPropertyCount,
3192 VkLayerProperties* pProperties)
3193 {
3194 if (pProperties == NULL) {
3195 *pPropertyCount = 0;
3196 return VK_SUCCESS;
3197 }
3198
3199 /* None supported at this time */
3200 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
3201 }
3202
3203 void anv_GetDeviceQueue(
3204 VkDevice _device,
3205 uint32_t queueNodeIndex,
3206 uint32_t queueIndex,
3207 VkQueue* pQueue)
3208 {
3209 const VkDeviceQueueInfo2 info = {
3210 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
3211 .pNext = NULL,
3212 .flags = 0,
3213 .queueFamilyIndex = queueNodeIndex,
3214 .queueIndex = queueIndex,
3215 };
3216
3217 anv_GetDeviceQueue2(_device, &info, pQueue);
3218 }
3219
3220 void anv_GetDeviceQueue2(
3221 VkDevice _device,
3222 const VkDeviceQueueInfo2* pQueueInfo,
3223 VkQueue* pQueue)
3224 {
3225 ANV_FROM_HANDLE(anv_device, device, _device);
3226
3227 assert(pQueueInfo->queueIndex == 0);
3228
3229 if (pQueueInfo->flags == device->queue.flags)
3230 *pQueue = anv_queue_to_handle(&device->queue);
3231 else
3232 *pQueue = NULL;
3233 }
3234
3235 void
3236 _anv_device_report_lost(struct anv_device *device)
3237 {
3238 assert(p_atomic_read(&device->_lost) > 0);
3239
3240 device->lost_reported = true;
3241
3242 struct anv_queue *queue = &device->queue;
3243
3244 __vk_errorf(device->physical->instance, device,
3245 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
3246 VK_ERROR_DEVICE_LOST,
3247 queue->error_file, queue->error_line,
3248 "%s", queue->error_msg);
3249 }
3250
3251 VkResult
3252 _anv_device_set_lost(struct anv_device *device,
3253 const char *file, int line,
3254 const char *msg, ...)
3255 {
3256 VkResult err;
3257 va_list ap;
3258
3259 if (p_atomic_read(&device->_lost) > 0)
3260 return VK_ERROR_DEVICE_LOST;
3261
3262 p_atomic_inc(&device->_lost);
3263 device->lost_reported = true;
3264
3265 va_start(ap, msg);
3266 err = __vk_errorv(device->physical->instance, device,
3267 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
3268 VK_ERROR_DEVICE_LOST, file, line, msg, ap);
3269 va_end(ap);
3270
3271 if (env_var_as_boolean("ANV_ABORT_ON_DEVICE_LOSS", false))
3272 abort();
3273
3274 return err;
3275 }
3276
3277 VkResult
3278 _anv_queue_set_lost(struct anv_queue *queue,
3279 const char *file, int line,
3280 const char *msg, ...)
3281 {
3282 va_list ap;
3283
3284 if (queue->lost)
3285 return VK_ERROR_DEVICE_LOST;
3286
3287 queue->lost = true;
3288
3289 queue->error_file = file;
3290 queue->error_line = line;
3291 va_start(ap, msg);
3292 vsnprintf(queue->error_msg, sizeof(queue->error_msg),
3293 msg, ap);
3294 va_end(ap);
3295
3296 p_atomic_inc(&queue->device->_lost);
3297
3298 if (env_var_as_boolean("ANV_ABORT_ON_DEVICE_LOSS", false))
3299 abort();
3300
3301 return VK_ERROR_DEVICE_LOST;
3302 }
3303
3304 VkResult
3305 anv_device_query_status(struct anv_device *device)
3306 {
3307 /* This isn't likely as most of the callers of this function already check
3308 * for it. However, it doesn't hurt to check and it potentially lets us
3309 * avoid an ioctl.
3310 */
3311 if (anv_device_is_lost(device))
3312 return VK_ERROR_DEVICE_LOST;
3313
3314 uint32_t active, pending;
3315 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
3316 if (ret == -1) {
3317 /* We don't know the real error. */
3318 return anv_device_set_lost(device, "get_reset_stats failed: %m");
3319 }
3320
3321 if (active) {
3322 return anv_device_set_lost(device, "GPU hung on one of our command buffers");
3323 } else if (pending) {
3324 return anv_device_set_lost(device, "GPU hung with commands in-flight");
3325 }
3326
3327 return VK_SUCCESS;
3328 }
3329
3330 VkResult
3331 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
3332 {
3333 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
3334 * Other usages of the BO (such as on different hardware) will not be
3335 * flagged as "busy" by this ioctl. Use with care.
3336 */
3337 int ret = anv_gem_busy(device, bo->gem_handle);
3338 if (ret == 1) {
3339 return VK_NOT_READY;
3340 } else if (ret == -1) {
3341 /* We don't know the real error. */
3342 return anv_device_set_lost(device, "gem wait failed: %m");
3343 }
3344
3345 /* Query for device status after the busy call. If the BO we're checking
3346 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
3347 * client because it clearly doesn't have valid data. Yes, this most
3348 * likely means an ioctl, but we just did an ioctl to query the busy status
3349 * so it's no great loss.
3350 */
3351 return anv_device_query_status(device);
3352 }
3353
3354 VkResult
3355 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
3356 int64_t timeout)
3357 {
3358 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
3359 if (ret == -1 && errno == ETIME) {
3360 return VK_TIMEOUT;
3361 } else if (ret == -1) {
3362 /* We don't know the real error. */
3363 return anv_device_set_lost(device, "gem wait failed: %m");
3364 }
3365
3366 /* Query for device status after the wait. If the BO we're waiting on got
3367 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
3368 * because it clearly doesn't have valid data. Yes, this most likely means
3369 * an ioctl, but we just did an ioctl to wait so it's no great loss.
3370 */
3371 return anv_device_query_status(device);
3372 }
3373
3374 VkResult anv_DeviceWaitIdle(
3375 VkDevice _device)
3376 {
3377 ANV_FROM_HANDLE(anv_device, device, _device);
3378
3379 if (anv_device_is_lost(device))
3380 return VK_ERROR_DEVICE_LOST;
3381
3382 return anv_queue_submit_simple_batch(&device->queue, NULL);
3383 }
3384
3385 uint64_t
3386 anv_vma_alloc(struct anv_device *device,
3387 uint64_t size, uint64_t align,
3388 enum anv_bo_alloc_flags alloc_flags,
3389 uint64_t client_address)
3390 {
3391 pthread_mutex_lock(&device->vma_mutex);
3392
3393 uint64_t addr = 0;
3394
3395 if (alloc_flags & ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS) {
3396 if (client_address) {
3397 if (util_vma_heap_alloc_addr(&device->vma_cva,
3398 client_address, size)) {
3399 addr = client_address;
3400 }
3401 } else {
3402 addr = util_vma_heap_alloc(&device->vma_cva, size, align);
3403 }
3404 /* We don't want to fall back to other heaps */
3405 goto done;
3406 }
3407
3408 assert(client_address == 0);
3409
3410 if (!(alloc_flags & ANV_BO_ALLOC_32BIT_ADDRESS))
3411 addr = util_vma_heap_alloc(&device->vma_hi, size, align);
3412
3413 if (addr == 0)
3414 addr = util_vma_heap_alloc(&device->vma_lo, size, align);
3415
3416 done:
3417 pthread_mutex_unlock(&device->vma_mutex);
3418
3419 assert(addr == gen_48b_address(addr));
3420 return gen_canonical_address(addr);
3421 }
3422
3423 void
3424 anv_vma_free(struct anv_device *device,
3425 uint64_t address, uint64_t size)
3426 {
3427 const uint64_t addr_48b = gen_48b_address(address);
3428
3429 pthread_mutex_lock(&device->vma_mutex);
3430
3431 if (addr_48b >= LOW_HEAP_MIN_ADDRESS &&
3432 addr_48b <= LOW_HEAP_MAX_ADDRESS) {
3433 util_vma_heap_free(&device->vma_lo, addr_48b, size);
3434 } else if (addr_48b >= CLIENT_VISIBLE_HEAP_MIN_ADDRESS &&
3435 addr_48b <= CLIENT_VISIBLE_HEAP_MAX_ADDRESS) {
3436 util_vma_heap_free(&device->vma_cva, addr_48b, size);
3437 } else {
3438 assert(addr_48b >= HIGH_HEAP_MIN_ADDRESS);
3439 util_vma_heap_free(&device->vma_hi, addr_48b, size);
3440 }
3441
3442 pthread_mutex_unlock(&device->vma_mutex);
3443 }
3444
3445 VkResult anv_AllocateMemory(
3446 VkDevice _device,
3447 const VkMemoryAllocateInfo* pAllocateInfo,
3448 const VkAllocationCallbacks* pAllocator,
3449 VkDeviceMemory* pMem)
3450 {
3451 ANV_FROM_HANDLE(anv_device, device, _device);
3452 struct anv_physical_device *pdevice = device->physical;
3453 struct anv_device_memory *mem;
3454 VkResult result = VK_SUCCESS;
3455
3456 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
3457
3458 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
3459 assert(pAllocateInfo->allocationSize > 0);
3460
3461 VkDeviceSize aligned_alloc_size =
3462 align_u64(pAllocateInfo->allocationSize, 4096);
3463
3464 if (aligned_alloc_size > MAX_MEMORY_ALLOCATION_SIZE)
3465 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
3466
3467 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
3468 struct anv_memory_type *mem_type =
3469 &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
3470 assert(mem_type->heapIndex < pdevice->memory.heap_count);
3471 struct anv_memory_heap *mem_heap =
3472 &pdevice->memory.heaps[mem_type->heapIndex];
3473
3474 uint64_t mem_heap_used = p_atomic_read(&mem_heap->used);
3475 if (mem_heap_used + aligned_alloc_size > mem_heap->size)
3476 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
3477
3478 mem = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*mem), 8,
3479 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3480 if (mem == NULL)
3481 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3482
3483 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
3484 vk_object_base_init(&device->vk, &mem->base, VK_OBJECT_TYPE_DEVICE_MEMORY);
3485 mem->type = mem_type;
3486 mem->map = NULL;
3487 mem->map_size = 0;
3488 mem->ahw = NULL;
3489 mem->host_ptr = NULL;
3490
3491 enum anv_bo_alloc_flags alloc_flags = 0;
3492
3493 const VkExportMemoryAllocateInfo *export_info = NULL;
3494 const VkImportAndroidHardwareBufferInfoANDROID *ahw_import_info = NULL;
3495 const VkImportMemoryFdInfoKHR *fd_info = NULL;
3496 const VkImportMemoryHostPointerInfoEXT *host_ptr_info = NULL;
3497 const VkMemoryDedicatedAllocateInfo *dedicated_info = NULL;
3498 VkMemoryAllocateFlags vk_flags = 0;
3499 uint64_t client_address = 0;
3500
3501 vk_foreach_struct_const(ext, pAllocateInfo->pNext) {
3502 switch (ext->sType) {
3503 case VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO:
3504 export_info = (void *)ext;
3505 break;
3506
3507 case VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID:
3508 ahw_import_info = (void *)ext;
3509 break;
3510
3511 case VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR:
3512 fd_info = (void *)ext;
3513 break;
3514
3515 case VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT:
3516 host_ptr_info = (void *)ext;
3517 break;
3518
3519 case VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO: {
3520 const VkMemoryAllocateFlagsInfo *flags_info = (void *)ext;
3521 vk_flags = flags_info->flags;
3522 break;
3523 }
3524
3525 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO:
3526 dedicated_info = (void *)ext;
3527 break;
3528
3529 case VK_STRUCTURE_TYPE_MEMORY_OPAQUE_CAPTURE_ADDRESS_ALLOCATE_INFO_KHR: {
3530 const VkMemoryOpaqueCaptureAddressAllocateInfoKHR *addr_info =
3531 (const VkMemoryOpaqueCaptureAddressAllocateInfoKHR *)ext;
3532 client_address = addr_info->opaqueCaptureAddress;
3533 break;
3534 }
3535
3536 default:
3537 anv_debug_ignored_stype(ext->sType);
3538 break;
3539 }
3540 }
3541
3542 /* By default, we want all VkDeviceMemory objects to support CCS */
3543 if (device->physical->has_implicit_ccs)
3544 alloc_flags |= ANV_BO_ALLOC_IMPLICIT_CCS;
3545
3546 if (vk_flags & VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR)
3547 alloc_flags |= ANV_BO_ALLOC_CLIENT_VISIBLE_ADDRESS;
3548
3549 if ((export_info && export_info->handleTypes) ||
3550 (fd_info && fd_info->handleType) ||
3551 (host_ptr_info && host_ptr_info->handleType)) {
3552 /* Anything imported or exported is EXTERNAL */
3553 alloc_flags |= ANV_BO_ALLOC_EXTERNAL;
3554
3555 /* We can't have implicit CCS on external memory with an AUX-table.
3556 * Doing so would require us to sync the aux tables across processes
3557 * which is impractical.
3558 */
3559 if (device->info.has_aux_map)
3560 alloc_flags &= ~ANV_BO_ALLOC_IMPLICIT_CCS;
3561 }
3562
3563 /* Check if we need to support Android HW buffer export. If so,
3564 * create AHardwareBuffer and import memory from it.
3565 */
3566 bool android_export = false;
3567 if (export_info && export_info->handleTypes &
3568 VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)
3569 android_export = true;
3570
3571 if (ahw_import_info) {
3572 result = anv_import_ahw_memory(_device, mem, ahw_import_info);
3573 if (result != VK_SUCCESS)
3574 goto fail;
3575
3576 goto success;
3577 } else if (android_export) {
3578 result = anv_create_ahw_memory(_device, mem, pAllocateInfo);
3579 if (result != VK_SUCCESS)
3580 goto fail;
3581
3582 const VkImportAndroidHardwareBufferInfoANDROID import_info = {
3583 .buffer = mem->ahw,
3584 };
3585 result = anv_import_ahw_memory(_device, mem, &import_info);
3586 if (result != VK_SUCCESS)
3587 goto fail;
3588
3589 goto success;
3590 }
3591
3592 /* The Vulkan spec permits handleType to be 0, in which case the struct is
3593 * ignored.
3594 */
3595 if (fd_info && fd_info->handleType) {
3596 /* At the moment, we support only the below handle types. */
3597 assert(fd_info->handleType ==
3598 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
3599 fd_info->handleType ==
3600 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
3601
3602 result = anv_device_import_bo(device, fd_info->fd, alloc_flags,
3603 client_address, &mem->bo);
3604 if (result != VK_SUCCESS)
3605 goto fail;
3606
3607 /* For security purposes, we reject importing the bo if it's smaller
3608 * than the requested allocation size. This prevents a malicious client
3609 * from passing a buffer to a trusted client, lying about the size, and
3610 * telling the trusted client to try and texture from an image that goes
3611 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
3612 * in the trusted client. The trusted client can protect itself against
3613 * this sort of attack but only if it can trust the buffer size.
3614 */
3615 if (mem->bo->size < aligned_alloc_size) {
3616 result = vk_errorf(device, device, VK_ERROR_INVALID_EXTERNAL_HANDLE,
3617 "aligned allocationSize too large for "
3618 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT: "
3619 "%"PRIu64"B > %"PRIu64"B",
3620 aligned_alloc_size, mem->bo->size);
3621 anv_device_release_bo(device, mem->bo);
3622 goto fail;
3623 }
3624
3625 /* From the Vulkan spec:
3626 *
3627 * "Importing memory from a file descriptor transfers ownership of
3628 * the file descriptor from the application to the Vulkan
3629 * implementation. The application must not perform any operations on
3630 * the file descriptor after a successful import."
3631 *
3632 * If the import fails, we leave the file descriptor open.
3633 */
3634 close(fd_info->fd);
3635 goto success;
3636 }
3637
3638 if (host_ptr_info && host_ptr_info->handleType) {
3639 if (host_ptr_info->handleType ==
3640 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT) {
3641 result = vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
3642 goto fail;
3643 }
3644
3645 assert(host_ptr_info->handleType ==
3646 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
3647
3648 result = anv_device_import_bo_from_host_ptr(device,
3649 host_ptr_info->pHostPointer,
3650 pAllocateInfo->allocationSize,
3651 alloc_flags,
3652 client_address,
3653 &mem->bo);
3654 if (result != VK_SUCCESS)
3655 goto fail;
3656
3657 mem->host_ptr = host_ptr_info->pHostPointer;
3658 goto success;
3659 }
3660
3661 /* Regular allocate (not importing memory). */
3662
3663 result = anv_device_alloc_bo(device, pAllocateInfo->allocationSize,
3664 alloc_flags, client_address, &mem->bo);
3665 if (result != VK_SUCCESS)
3666 goto fail;
3667
3668 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
3669 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
3670
3671 /* Some legacy (non-modifiers) consumers need the tiling to be set on
3672 * the BO. In this case, we have a dedicated allocation.
3673 */
3674 if (image->needs_set_tiling) {
3675 const uint32_t i915_tiling =
3676 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
3677 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
3678 image->planes[0].surface.isl.row_pitch_B,
3679 i915_tiling);
3680 if (ret) {
3681 anv_device_release_bo(device, mem->bo);
3682 result = vk_errorf(device, device, VK_ERROR_OUT_OF_DEVICE_MEMORY,
3683 "failed to set BO tiling: %m");
3684 goto fail;
3685 }
3686 }
3687 }
3688
3689 success:
3690 mem_heap_used = p_atomic_add_return(&mem_heap->used, mem->bo->size);
3691 if (mem_heap_used > mem_heap->size) {
3692 p_atomic_add(&mem_heap->used, -mem->bo->size);
3693 anv_device_release_bo(device, mem->bo);
3694 result = vk_errorf(device, device, VK_ERROR_OUT_OF_DEVICE_MEMORY,
3695 "Out of heap memory");
3696 goto fail;
3697 }
3698
3699 pthread_mutex_lock(&device->mutex);
3700 list_addtail(&mem->link, &device->memory_objects);
3701 pthread_mutex_unlock(&device->mutex);
3702
3703 *pMem = anv_device_memory_to_handle(mem);
3704
3705 return VK_SUCCESS;
3706
3707 fail:
3708 vk_free2(&device->vk.alloc, pAllocator, mem);
3709
3710 return result;
3711 }
3712
3713 VkResult anv_GetMemoryFdKHR(
3714 VkDevice device_h,
3715 const VkMemoryGetFdInfoKHR* pGetFdInfo,
3716 int* pFd)
3717 {
3718 ANV_FROM_HANDLE(anv_device, dev, device_h);
3719 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
3720
3721 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
3722
3723 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
3724 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
3725
3726 return anv_device_export_bo(dev, mem->bo, pFd);
3727 }
3728
3729 VkResult anv_GetMemoryFdPropertiesKHR(
3730 VkDevice _device,
3731 VkExternalMemoryHandleTypeFlagBits handleType,
3732 int fd,
3733 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
3734 {
3735 ANV_FROM_HANDLE(anv_device, device, _device);
3736
3737 switch (handleType) {
3738 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
3739 /* dma-buf can be imported as any memory type */
3740 pMemoryFdProperties->memoryTypeBits =
3741 (1 << device->physical->memory.type_count) - 1;
3742 return VK_SUCCESS;
3743
3744 default:
3745 /* The valid usage section for this function says:
3746 *
3747 * "handleType must not be one of the handle types defined as
3748 * opaque."
3749 *
3750 * So opaque handle types fall into the default "unsupported" case.
3751 */
3752 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
3753 }
3754 }
3755
3756 VkResult anv_GetMemoryHostPointerPropertiesEXT(
3757 VkDevice _device,
3758 VkExternalMemoryHandleTypeFlagBits handleType,
3759 const void* pHostPointer,
3760 VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties)
3761 {
3762 ANV_FROM_HANDLE(anv_device, device, _device);
3763
3764 assert(pMemoryHostPointerProperties->sType ==
3765 VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT);
3766
3767 switch (handleType) {
3768 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT:
3769 /* Host memory can be imported as any memory type. */
3770 pMemoryHostPointerProperties->memoryTypeBits =
3771 (1ull << device->physical->memory.type_count) - 1;
3772
3773 return VK_SUCCESS;
3774
3775 default:
3776 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
3777 }
3778 }
3779
3780 void anv_FreeMemory(
3781 VkDevice _device,
3782 VkDeviceMemory _mem,
3783 const VkAllocationCallbacks* pAllocator)
3784 {
3785 ANV_FROM_HANDLE(anv_device, device, _device);
3786 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
3787
3788 if (mem == NULL)
3789 return;
3790
3791 pthread_mutex_lock(&device->mutex);
3792 list_del(&mem->link);
3793 pthread_mutex_unlock(&device->mutex);
3794
3795 if (mem->map)
3796 anv_UnmapMemory(_device, _mem);
3797
3798 p_atomic_add(&device->physical->memory.heaps[mem->type->heapIndex].used,
3799 -mem->bo->size);
3800
3801 anv_device_release_bo(device, mem->bo);
3802
3803 #if defined(ANDROID) && ANDROID_API_LEVEL >= 26
3804 if (mem->ahw)
3805 AHardwareBuffer_release(mem->ahw);
3806 #endif
3807
3808 vk_object_base_finish(&mem->base);
3809 vk_free2(&device->vk.alloc, pAllocator, mem);
3810 }
3811
3812 VkResult anv_MapMemory(
3813 VkDevice _device,
3814 VkDeviceMemory _memory,
3815 VkDeviceSize offset,
3816 VkDeviceSize size,
3817 VkMemoryMapFlags flags,
3818 void** ppData)
3819 {
3820 ANV_FROM_HANDLE(anv_device, device, _device);
3821 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
3822
3823 if (mem == NULL) {
3824 *ppData = NULL;
3825 return VK_SUCCESS;
3826 }
3827
3828 if (mem->host_ptr) {
3829 *ppData = mem->host_ptr + offset;
3830 return VK_SUCCESS;
3831 }
3832
3833 if (size == VK_WHOLE_SIZE)
3834 size = mem->bo->size - offset;
3835
3836 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
3837 *
3838 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
3839 * assert(size != 0);
3840 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
3841 * equal to the size of the memory minus offset
3842 */
3843 assert(size > 0);
3844 assert(offset + size <= mem->bo->size);
3845
3846 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
3847 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
3848 * at a time is valid. We could just mmap up front and return an offset
3849 * pointer here, but that may exhaust virtual memory on 32 bit
3850 * userspace. */
3851
3852 uint32_t gem_flags = 0;
3853
3854 if (!device->info.has_llc &&
3855 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
3856 gem_flags |= I915_MMAP_WC;
3857
3858 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
3859 uint64_t map_offset;
3860 if (!device->physical->has_mmap_offset)
3861 map_offset = offset & ~4095ull;
3862 else
3863 map_offset = 0;
3864 assert(offset >= map_offset);
3865 uint64_t map_size = (offset + size) - map_offset;
3866
3867 /* Let's map whole pages */
3868 map_size = align_u64(map_size, 4096);
3869
3870 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
3871 map_offset, map_size, gem_flags);
3872 if (map == MAP_FAILED)
3873 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
3874
3875 mem->map = map;
3876 mem->map_size = map_size;
3877
3878 *ppData = mem->map + (offset - map_offset);
3879
3880 return VK_SUCCESS;
3881 }
3882
3883 void anv_UnmapMemory(
3884 VkDevice _device,
3885 VkDeviceMemory _memory)
3886 {
3887 ANV_FROM_HANDLE(anv_device, device, _device);
3888 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
3889
3890 if (mem == NULL || mem->host_ptr)
3891 return;
3892
3893 anv_gem_munmap(device, mem->map, mem->map_size);
3894
3895 mem->map = NULL;
3896 mem->map_size = 0;
3897 }
3898
3899 static void
3900 clflush_mapped_ranges(struct anv_device *device,
3901 uint32_t count,
3902 const VkMappedMemoryRange *ranges)
3903 {
3904 for (uint32_t i = 0; i < count; i++) {
3905 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
3906 if (ranges[i].offset >= mem->map_size)
3907 continue;
3908
3909 gen_clflush_range(mem->map + ranges[i].offset,
3910 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
3911 }
3912 }
3913
3914 VkResult anv_FlushMappedMemoryRanges(
3915 VkDevice _device,
3916 uint32_t memoryRangeCount,
3917 const VkMappedMemoryRange* pMemoryRanges)
3918 {
3919 ANV_FROM_HANDLE(anv_device, device, _device);
3920
3921 if (device->info.has_llc)
3922 return VK_SUCCESS;
3923
3924 /* Make sure the writes we're flushing have landed. */
3925 __builtin_ia32_mfence();
3926
3927 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
3928
3929 return VK_SUCCESS;
3930 }
3931
3932 VkResult anv_InvalidateMappedMemoryRanges(
3933 VkDevice _device,
3934 uint32_t memoryRangeCount,
3935 const VkMappedMemoryRange* pMemoryRanges)
3936 {
3937 ANV_FROM_HANDLE(anv_device, device, _device);
3938
3939 if (device->info.has_llc)
3940 return VK_SUCCESS;
3941
3942 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
3943
3944 /* Make sure no reads get moved up above the invalidate. */
3945 __builtin_ia32_mfence();
3946
3947 return VK_SUCCESS;
3948 }
3949
3950 void anv_GetBufferMemoryRequirements(
3951 VkDevice _device,
3952 VkBuffer _buffer,
3953 VkMemoryRequirements* pMemoryRequirements)
3954 {
3955 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3956 ANV_FROM_HANDLE(anv_device, device, _device);
3957
3958 /* The Vulkan spec (git aaed022) says:
3959 *
3960 * memoryTypeBits is a bitfield and contains one bit set for every
3961 * supported memory type for the resource. The bit `1<<i` is set if and
3962 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
3963 * structure for the physical device is supported.
3964 */
3965 uint32_t memory_types = (1ull << device->physical->memory.type_count) - 1;
3966
3967 /* Base alignment requirement of a cache line */
3968 uint32_t alignment = 16;
3969
3970 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
3971 alignment = MAX2(alignment, ANV_UBO_ALIGNMENT);
3972
3973 pMemoryRequirements->size = buffer->size;
3974 pMemoryRequirements->alignment = alignment;
3975
3976 /* Storage and Uniform buffers should have their size aligned to
3977 * 32-bits to avoid boundary checks when last DWord is not complete.
3978 * This would ensure that not internal padding would be needed for
3979 * 16-bit types.
3980 */
3981 if (device->robust_buffer_access &&
3982 (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
3983 buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
3984 pMemoryRequirements->size = align_u64(buffer->size, 4);
3985
3986 pMemoryRequirements->memoryTypeBits = memory_types;
3987 }
3988
3989 void anv_GetBufferMemoryRequirements2(
3990 VkDevice _device,
3991 const VkBufferMemoryRequirementsInfo2* pInfo,
3992 VkMemoryRequirements2* pMemoryRequirements)
3993 {
3994 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
3995 &pMemoryRequirements->memoryRequirements);
3996
3997 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3998 switch (ext->sType) {
3999 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
4000 VkMemoryDedicatedRequirements *requirements = (void *)ext;
4001 requirements->prefersDedicatedAllocation = false;
4002 requirements->requiresDedicatedAllocation = false;
4003 break;
4004 }
4005
4006 default:
4007 anv_debug_ignored_stype(ext->sType);
4008 break;
4009 }
4010 }
4011 }
4012
4013 void anv_GetImageMemoryRequirements(
4014 VkDevice _device,
4015 VkImage _image,
4016 VkMemoryRequirements* pMemoryRequirements)
4017 {
4018 ANV_FROM_HANDLE(anv_image, image, _image);
4019 ANV_FROM_HANDLE(anv_device, device, _device);
4020
4021 /* The Vulkan spec (git aaed022) says:
4022 *
4023 * memoryTypeBits is a bitfield and contains one bit set for every
4024 * supported memory type for the resource. The bit `1<<i` is set if and
4025 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
4026 * structure for the physical device is supported.
4027 *
4028 * All types are currently supported for images.
4029 */
4030 uint32_t memory_types = (1ull << device->physical->memory.type_count) - 1;
4031
4032 pMemoryRequirements->size = image->size;
4033 pMemoryRequirements->alignment = image->alignment;
4034 pMemoryRequirements->memoryTypeBits = memory_types;
4035 }
4036
4037 void anv_GetImageMemoryRequirements2(
4038 VkDevice _device,
4039 const VkImageMemoryRequirementsInfo2* pInfo,
4040 VkMemoryRequirements2* pMemoryRequirements)
4041 {
4042 ANV_FROM_HANDLE(anv_device, device, _device);
4043 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
4044
4045 anv_GetImageMemoryRequirements(_device, pInfo->image,
4046 &pMemoryRequirements->memoryRequirements);
4047
4048 vk_foreach_struct_const(ext, pInfo->pNext) {
4049 switch (ext->sType) {
4050 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
4051 const VkImagePlaneMemoryRequirementsInfo *plane_reqs =
4052 (const VkImagePlaneMemoryRequirementsInfo *) ext;
4053 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
4054 plane_reqs->planeAspect);
4055
4056 assert(image->planes[plane].offset == 0);
4057
4058 /* The Vulkan spec (git aaed022) says:
4059 *
4060 * memoryTypeBits is a bitfield and contains one bit set for every
4061 * supported memory type for the resource. The bit `1<<i` is set
4062 * if and only if the memory type `i` in the
4063 * VkPhysicalDeviceMemoryProperties structure for the physical
4064 * device is supported.
4065 *
4066 * All types are currently supported for images.
4067 */
4068 pMemoryRequirements->memoryRequirements.memoryTypeBits =
4069 (1ull << device->physical->memory.type_count) - 1;
4070
4071 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
4072 pMemoryRequirements->memoryRequirements.alignment =
4073 image->planes[plane].alignment;
4074 break;
4075 }
4076
4077 default:
4078 anv_debug_ignored_stype(ext->sType);
4079 break;
4080 }
4081 }
4082
4083 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
4084 switch (ext->sType) {
4085 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
4086 VkMemoryDedicatedRequirements *requirements = (void *)ext;
4087 if (image->needs_set_tiling || image->external_format) {
4088 /* If we need to set the tiling for external consumers, we need a
4089 * dedicated allocation.
4090 *
4091 * See also anv_AllocateMemory.
4092 */
4093 requirements->prefersDedicatedAllocation = true;
4094 requirements->requiresDedicatedAllocation = true;
4095 } else {
4096 requirements->prefersDedicatedAllocation = false;
4097 requirements->requiresDedicatedAllocation = false;
4098 }
4099 break;
4100 }
4101
4102 default:
4103 anv_debug_ignored_stype(ext->sType);
4104 break;
4105 }
4106 }
4107 }
4108
4109 void anv_GetImageSparseMemoryRequirements(
4110 VkDevice device,
4111 VkImage image,
4112 uint32_t* pSparseMemoryRequirementCount,
4113 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
4114 {
4115 *pSparseMemoryRequirementCount = 0;
4116 }
4117
4118 void anv_GetImageSparseMemoryRequirements2(
4119 VkDevice device,
4120 const VkImageSparseMemoryRequirementsInfo2* pInfo,
4121 uint32_t* pSparseMemoryRequirementCount,
4122 VkSparseImageMemoryRequirements2* pSparseMemoryRequirements)
4123 {
4124 *pSparseMemoryRequirementCount = 0;
4125 }
4126
4127 void anv_GetDeviceMemoryCommitment(
4128 VkDevice device,
4129 VkDeviceMemory memory,
4130 VkDeviceSize* pCommittedMemoryInBytes)
4131 {
4132 *pCommittedMemoryInBytes = 0;
4133 }
4134
4135 static void
4136 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
4137 {
4138 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
4139 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
4140
4141 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
4142
4143 if (mem) {
4144 buffer->address = (struct anv_address) {
4145 .bo = mem->bo,
4146 .offset = pBindInfo->memoryOffset,
4147 };
4148 } else {
4149 buffer->address = ANV_NULL_ADDRESS;
4150 }
4151 }
4152
4153 VkResult anv_BindBufferMemory(
4154 VkDevice device,
4155 VkBuffer buffer,
4156 VkDeviceMemory memory,
4157 VkDeviceSize memoryOffset)
4158 {
4159 anv_bind_buffer_memory(
4160 &(VkBindBufferMemoryInfo) {
4161 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
4162 .buffer = buffer,
4163 .memory = memory,
4164 .memoryOffset = memoryOffset,
4165 });
4166
4167 return VK_SUCCESS;
4168 }
4169
4170 VkResult anv_BindBufferMemory2(
4171 VkDevice device,
4172 uint32_t bindInfoCount,
4173 const VkBindBufferMemoryInfo* pBindInfos)
4174 {
4175 for (uint32_t i = 0; i < bindInfoCount; i++)
4176 anv_bind_buffer_memory(&pBindInfos[i]);
4177
4178 return VK_SUCCESS;
4179 }
4180
4181 VkResult anv_QueueBindSparse(
4182 VkQueue _queue,
4183 uint32_t bindInfoCount,
4184 const VkBindSparseInfo* pBindInfo,
4185 VkFence fence)
4186 {
4187 ANV_FROM_HANDLE(anv_queue, queue, _queue);
4188 if (anv_device_is_lost(queue->device))
4189 return VK_ERROR_DEVICE_LOST;
4190
4191 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
4192 }
4193
4194 // Event functions
4195
4196 VkResult anv_CreateEvent(
4197 VkDevice _device,
4198 const VkEventCreateInfo* pCreateInfo,
4199 const VkAllocationCallbacks* pAllocator,
4200 VkEvent* pEvent)
4201 {
4202 ANV_FROM_HANDLE(anv_device, device, _device);
4203 struct anv_event *event;
4204
4205 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
4206
4207 event = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*event), 8,
4208 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4209 if (event == NULL)
4210 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4211
4212 vk_object_base_init(&device->vk, &event->base, VK_OBJECT_TYPE_EVENT);
4213 event->state = anv_state_pool_alloc(&device->dynamic_state_pool,
4214 sizeof(uint64_t), 8);
4215 *(uint64_t *)event->state.map = VK_EVENT_RESET;
4216
4217 *pEvent = anv_event_to_handle(event);
4218
4219 return VK_SUCCESS;
4220 }
4221
4222 void anv_DestroyEvent(
4223 VkDevice _device,
4224 VkEvent _event,
4225 const VkAllocationCallbacks* pAllocator)
4226 {
4227 ANV_FROM_HANDLE(anv_device, device, _device);
4228 ANV_FROM_HANDLE(anv_event, event, _event);
4229
4230 if (!event)
4231 return;
4232
4233 anv_state_pool_free(&device->dynamic_state_pool, event->state);
4234
4235 vk_object_base_finish(&event->base);
4236 vk_free2(&device->vk.alloc, pAllocator, event);
4237 }
4238
4239 VkResult anv_GetEventStatus(
4240 VkDevice _device,
4241 VkEvent _event)
4242 {
4243 ANV_FROM_HANDLE(anv_device, device, _device);
4244 ANV_FROM_HANDLE(anv_event, event, _event);
4245
4246 if (anv_device_is_lost(device))
4247 return VK_ERROR_DEVICE_LOST;
4248
4249 return *(uint64_t *)event->state.map;
4250 }
4251
4252 VkResult anv_SetEvent(
4253 VkDevice _device,
4254 VkEvent _event)
4255 {
4256 ANV_FROM_HANDLE(anv_event, event, _event);
4257
4258 *(uint64_t *)event->state.map = VK_EVENT_SET;
4259
4260 return VK_SUCCESS;
4261 }
4262
4263 VkResult anv_ResetEvent(
4264 VkDevice _device,
4265 VkEvent _event)
4266 {
4267 ANV_FROM_HANDLE(anv_event, event, _event);
4268
4269 *(uint64_t *)event->state.map = VK_EVENT_RESET;
4270
4271 return VK_SUCCESS;
4272 }
4273
4274 // Buffer functions
4275
4276 VkResult anv_CreateBuffer(
4277 VkDevice _device,
4278 const VkBufferCreateInfo* pCreateInfo,
4279 const VkAllocationCallbacks* pAllocator,
4280 VkBuffer* pBuffer)
4281 {
4282 ANV_FROM_HANDLE(anv_device, device, _device);
4283 struct anv_buffer *buffer;
4284
4285 /* Don't allow creating buffers bigger than our address space. The real
4286 * issue here is that we may align up the buffer size and we don't want
4287 * doing so to cause roll-over. However, no one has any business
4288 * allocating a buffer larger than our GTT size.
4289 */
4290 if (pCreateInfo->size > device->physical->gtt_size)
4291 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
4292
4293 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
4294
4295 buffer = vk_alloc2(&device->vk.alloc, pAllocator, sizeof(*buffer), 8,
4296 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4297 if (buffer == NULL)
4298 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4299
4300 vk_object_base_init(&device->vk, &buffer->base, VK_OBJECT_TYPE_BUFFER);
4301 buffer->size = pCreateInfo->size;
4302 buffer->usage = pCreateInfo->usage;
4303 buffer->address = ANV_NULL_ADDRESS;
4304
4305 *pBuffer = anv_buffer_to_handle(buffer);
4306
4307 return VK_SUCCESS;
4308 }
4309
4310 void anv_DestroyBuffer(
4311 VkDevice _device,
4312 VkBuffer _buffer,
4313 const VkAllocationCallbacks* pAllocator)
4314 {
4315 ANV_FROM_HANDLE(anv_device, device, _device);
4316 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
4317
4318 if (!buffer)
4319 return;
4320
4321 vk_object_base_finish(&buffer->base);
4322 vk_free2(&device->vk.alloc, pAllocator, buffer);
4323 }
4324
4325 VkDeviceAddress anv_GetBufferDeviceAddress(
4326 VkDevice device,
4327 const VkBufferDeviceAddressInfoKHR* pInfo)
4328 {
4329 ANV_FROM_HANDLE(anv_buffer, buffer, pInfo->buffer);
4330
4331 assert(!anv_address_is_null(buffer->address));
4332 assert(buffer->address.bo->flags & EXEC_OBJECT_PINNED);
4333
4334 return anv_address_physical(buffer->address);
4335 }
4336
4337 uint64_t anv_GetBufferOpaqueCaptureAddress(
4338 VkDevice device,
4339 const VkBufferDeviceAddressInfoKHR* pInfo)
4340 {
4341 return 0;
4342 }
4343
4344 uint64_t anv_GetDeviceMemoryOpaqueCaptureAddress(
4345 VkDevice device,
4346 const VkDeviceMemoryOpaqueCaptureAddressInfoKHR* pInfo)
4347 {
4348 ANV_FROM_HANDLE(anv_device_memory, memory, pInfo->memory);
4349
4350 assert(memory->bo->flags & EXEC_OBJECT_PINNED);
4351 assert(memory->bo->has_client_visible_address);
4352
4353 return gen_48b_address(memory->bo->offset);
4354 }
4355
4356 void
4357 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
4358 enum isl_format format,
4359 struct anv_address address,
4360 uint32_t range, uint32_t stride)
4361 {
4362 isl_buffer_fill_state(&device->isl_dev, state.map,
4363 .address = anv_address_physical(address),
4364 .mocs = device->isl_dev.mocs.internal,
4365 .size_B = range,
4366 .format = format,
4367 .swizzle = ISL_SWIZZLE_IDENTITY,
4368 .stride_B = stride);
4369 }
4370
4371 void anv_DestroySampler(
4372 VkDevice _device,
4373 VkSampler _sampler,
4374 const VkAllocationCallbacks* pAllocator)
4375 {
4376 ANV_FROM_HANDLE(anv_device, device, _device);
4377 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
4378
4379 if (!sampler)
4380 return;
4381
4382 if (sampler->bindless_state.map) {
4383 anv_state_pool_free(&device->dynamic_state_pool,
4384 sampler->bindless_state);
4385 }
4386
4387 if (sampler->custom_border_color.map) {
4388 anv_state_reserved_pool_free(&device->custom_border_colors,
4389 sampler->custom_border_color);
4390 }
4391
4392 vk_object_base_finish(&sampler->base);
4393 vk_free2(&device->vk.alloc, pAllocator, sampler);
4394 }
4395
4396 VkResult anv_CreateFramebuffer(
4397 VkDevice _device,
4398 const VkFramebufferCreateInfo* pCreateInfo,
4399 const VkAllocationCallbacks* pAllocator,
4400 VkFramebuffer* pFramebuffer)
4401 {
4402 ANV_FROM_HANDLE(anv_device, device, _device);
4403 struct anv_framebuffer *framebuffer;
4404
4405 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
4406
4407 size_t size = sizeof(*framebuffer);
4408
4409 /* VK_KHR_imageless_framebuffer extension says:
4410 *
4411 * If flags includes VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR,
4412 * parameter pAttachments is ignored.
4413 */
4414 if (!(pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT_KHR)) {
4415 size += sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
4416 framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
4417 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4418 if (framebuffer == NULL)
4419 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4420
4421 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
4422 ANV_FROM_HANDLE(anv_image_view, iview, pCreateInfo->pAttachments[i]);
4423 framebuffer->attachments[i] = iview;
4424 }
4425 framebuffer->attachment_count = pCreateInfo->attachmentCount;
4426 } else {
4427 framebuffer = vk_alloc2(&device->vk.alloc, pAllocator, size, 8,
4428 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4429 if (framebuffer == NULL)
4430 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
4431
4432 framebuffer->attachment_count = 0;
4433 }
4434
4435 vk_object_base_init(&device->vk, &framebuffer->base,
4436 VK_OBJECT_TYPE_FRAMEBUFFER);
4437
4438 framebuffer->width = pCreateInfo->width;
4439 framebuffer->height = pCreateInfo->height;
4440 framebuffer->layers = pCreateInfo->layers;
4441
4442 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
4443
4444 return VK_SUCCESS;
4445 }
4446
4447 void anv_DestroyFramebuffer(
4448 VkDevice _device,
4449 VkFramebuffer _fb,
4450 const VkAllocationCallbacks* pAllocator)
4451 {
4452 ANV_FROM_HANDLE(anv_device, device, _device);
4453 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
4454
4455 if (!fb)
4456 return;
4457
4458 vk_object_base_finish(&fb->base);
4459 vk_free2(&device->vk.alloc, pAllocator, fb);
4460 }
4461
4462 static const VkTimeDomainEXT anv_time_domains[] = {
4463 VK_TIME_DOMAIN_DEVICE_EXT,
4464 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
4465 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
4466 };
4467
4468 VkResult anv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
4469 VkPhysicalDevice physicalDevice,
4470 uint32_t *pTimeDomainCount,
4471 VkTimeDomainEXT *pTimeDomains)
4472 {
4473 int d;
4474 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
4475
4476 for (d = 0; d < ARRAY_SIZE(anv_time_domains); d++) {
4477 vk_outarray_append(&out, i) {
4478 *i = anv_time_domains[d];
4479 }
4480 }
4481
4482 return vk_outarray_status(&out);
4483 }
4484
4485 static uint64_t
4486 anv_clock_gettime(clockid_t clock_id)
4487 {
4488 struct timespec current;
4489 int ret;
4490
4491 ret = clock_gettime(clock_id, &current);
4492 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
4493 ret = clock_gettime(CLOCK_MONOTONIC, &current);
4494 if (ret < 0)
4495 return 0;
4496
4497 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
4498 }
4499
4500 VkResult anv_GetCalibratedTimestampsEXT(
4501 VkDevice _device,
4502 uint32_t timestampCount,
4503 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
4504 uint64_t *pTimestamps,
4505 uint64_t *pMaxDeviation)
4506 {
4507 ANV_FROM_HANDLE(anv_device, device, _device);
4508 uint64_t timestamp_frequency = device->info.timestamp_frequency;
4509 int ret;
4510 int d;
4511 uint64_t begin, end;
4512 uint64_t max_clock_period = 0;
4513
4514 begin = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
4515
4516 for (d = 0; d < timestampCount; d++) {
4517 switch (pTimestampInfos[d].timeDomain) {
4518 case VK_TIME_DOMAIN_DEVICE_EXT:
4519 ret = anv_gem_reg_read(device->fd, TIMESTAMP | I915_REG_READ_8B_WA,
4520 &pTimestamps[d]);
4521
4522 if (ret != 0) {
4523 return anv_device_set_lost(device, "Failed to read the TIMESTAMP "
4524 "register: %m");
4525 }
4526 uint64_t device_period = DIV_ROUND_UP(1000000000, timestamp_frequency);
4527 max_clock_period = MAX2(max_clock_period, device_period);
4528 break;
4529 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
4530 pTimestamps[d] = anv_clock_gettime(CLOCK_MONOTONIC);
4531 max_clock_period = MAX2(max_clock_period, 1);
4532 break;
4533
4534 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
4535 pTimestamps[d] = begin;
4536 break;
4537 default:
4538 pTimestamps[d] = 0;
4539 break;
4540 }
4541 }
4542
4543 end = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
4544
4545 /*
4546 * The maximum deviation is the sum of the interval over which we
4547 * perform the sampling and the maximum period of any sampled
4548 * clock. That's because the maximum skew between any two sampled
4549 * clock edges is when the sampled clock with the largest period is
4550 * sampled at the end of that period but right at the beginning of the
4551 * sampling interval and some other clock is sampled right at the
4552 * begining of its sampling period and right at the end of the
4553 * sampling interval. Let's assume the GPU has the longest clock
4554 * period and that the application is sampling GPU and monotonic:
4555 *
4556 * s e
4557 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
4558 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
4559 *
4560 * g
4561 * 0 1 2 3
4562 * GPU -----_____-----_____-----_____-----_____
4563 *
4564 * m
4565 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
4566 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
4567 *
4568 * Interval <----------------->
4569 * Deviation <-------------------------->
4570 *
4571 * s = read(raw) 2
4572 * g = read(GPU) 1
4573 * m = read(monotonic) 2
4574 * e = read(raw) b
4575 *
4576 * We round the sample interval up by one tick to cover sampling error
4577 * in the interval clock
4578 */
4579
4580 uint64_t sample_interval = end - begin + 1;
4581
4582 *pMaxDeviation = sample_interval + max_clock_period;
4583
4584 return VK_SUCCESS;
4585 }
4586
4587 /* vk_icd.h does not declare this function, so we declare it here to
4588 * suppress Wmissing-prototypes.
4589 */
4590 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
4591 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
4592
4593 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
4594 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
4595 {
4596 /* For the full details on loader interface versioning, see
4597 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
4598 * What follows is a condensed summary, to help you navigate the large and
4599 * confusing official doc.
4600 *
4601 * - Loader interface v0 is incompatible with later versions. We don't
4602 * support it.
4603 *
4604 * - In loader interface v1:
4605 * - The first ICD entrypoint called by the loader is
4606 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
4607 * entrypoint.
4608 * - The ICD must statically expose no other Vulkan symbol unless it is
4609 * linked with -Bsymbolic.
4610 * - Each dispatchable Vulkan handle created by the ICD must be
4611 * a pointer to a struct whose first member is VK_LOADER_DATA. The
4612 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
4613 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
4614 * vkDestroySurfaceKHR(). The ICD must be capable of working with
4615 * such loader-managed surfaces.
4616 *
4617 * - Loader interface v2 differs from v1 in:
4618 * - The first ICD entrypoint called by the loader is
4619 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
4620 * statically expose this entrypoint.
4621 *
4622 * - Loader interface v3 differs from v2 in:
4623 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
4624 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
4625 * because the loader no longer does so.
4626 *
4627 * - Loader interface v4 differs from v3 in:
4628 * - The ICD must implement vk_icdGetPhysicalDeviceProcAddr().
4629 */
4630 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
4631 return VK_SUCCESS;
4632 }
4633
4634 VkResult anv_CreatePrivateDataSlotEXT(
4635 VkDevice _device,
4636 const VkPrivateDataSlotCreateInfoEXT* pCreateInfo,
4637 const VkAllocationCallbacks* pAllocator,
4638 VkPrivateDataSlotEXT* pPrivateDataSlot)
4639 {
4640 ANV_FROM_HANDLE(anv_device, device, _device);
4641 return vk_private_data_slot_create(&device->vk, pCreateInfo, pAllocator,
4642 pPrivateDataSlot);
4643 }
4644
4645 void anv_DestroyPrivateDataSlotEXT(
4646 VkDevice _device,
4647 VkPrivateDataSlotEXT privateDataSlot,
4648 const VkAllocationCallbacks* pAllocator)
4649 {
4650 ANV_FROM_HANDLE(anv_device, device, _device);
4651 vk_private_data_slot_destroy(&device->vk, privateDataSlot, pAllocator);
4652 }
4653
4654 VkResult anv_SetPrivateDataEXT(
4655 VkDevice _device,
4656 VkObjectType objectType,
4657 uint64_t objectHandle,
4658 VkPrivateDataSlotEXT privateDataSlot,
4659 uint64_t data)
4660 {
4661 ANV_FROM_HANDLE(anv_device, device, _device);
4662 return vk_object_base_set_private_data(&device->vk,
4663 objectType, objectHandle,
4664 privateDataSlot, data);
4665 }
4666
4667 void anv_GetPrivateDataEXT(
4668 VkDevice _device,
4669 VkObjectType objectType,
4670 uint64_t objectHandle,
4671 VkPrivateDataSlotEXT privateDataSlot,
4672 uint64_t* pData)
4673 {
4674 ANV_FROM_HANDLE(anv_device, device, _device);
4675 vk_object_base_get_private_data(&device->vk,
4676 objectType, objectHandle,
4677 privateDataSlot, pData);
4678 }