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