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