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