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