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