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