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