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