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