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