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