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