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