anv: Implement VK_EXT_descriptor_indexing
[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_DESCRIPTOR_INDEXING_FEATURES_EXT: {
1035 VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
1036 (VkPhysicalDeviceDescriptorIndexingFeaturesEXT *)ext;
1037 features->shaderInputAttachmentArrayDynamicIndexing = false;
1038 features->shaderUniformTexelBufferArrayDynamicIndexing = true;
1039 features->shaderStorageTexelBufferArrayDynamicIndexing = true;
1040 features->shaderUniformBufferArrayNonUniformIndexing = false;
1041 features->shaderSampledImageArrayNonUniformIndexing = true;
1042 features->shaderStorageBufferArrayNonUniformIndexing = true;
1043 features->shaderStorageImageArrayNonUniformIndexing = true;
1044 features->shaderInputAttachmentArrayNonUniformIndexing = false;
1045 features->shaderUniformTexelBufferArrayNonUniformIndexing = true;
1046 features->shaderStorageTexelBufferArrayNonUniformIndexing = true;
1047 features->descriptorBindingUniformBufferUpdateAfterBind = false;
1048 features->descriptorBindingSampledImageUpdateAfterBind = true;
1049 features->descriptorBindingStorageImageUpdateAfterBind = true;
1050 features->descriptorBindingStorageBufferUpdateAfterBind = true;
1051 features->descriptorBindingUniformTexelBufferUpdateAfterBind = true;
1052 features->descriptorBindingStorageTexelBufferUpdateAfterBind = true;
1053 features->descriptorBindingUpdateUnusedWhilePending = true;
1054 features->descriptorBindingPartiallyBound = true;
1055 features->descriptorBindingVariableDescriptorCount = false;
1056 features->runtimeDescriptorArray = true;
1057 break;
1058 }
1059
1060 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT: {
1061 VkPhysicalDeviceInlineUniformBlockFeaturesEXT *features =
1062 (VkPhysicalDeviceInlineUniformBlockFeaturesEXT *)ext;
1063 features->inlineUniformBlock = true;
1064 features->descriptorBindingInlineUniformBlockUpdateAfterBind = true;
1065 break;
1066 }
1067
1068 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
1069 VkPhysicalDeviceMultiviewFeatures *features =
1070 (VkPhysicalDeviceMultiviewFeatures *)ext;
1071 features->multiview = true;
1072 features->multiviewGeometryShader = true;
1073 features->multiviewTessellationShader = true;
1074 break;
1075 }
1076
1077 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
1078 VkPhysicalDeviceProtectedMemoryFeatures *features = (void *)ext;
1079 features->protectedMemory = false;
1080 break;
1081 }
1082
1083 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
1084 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
1085 (VkPhysicalDeviceSamplerYcbcrConversionFeatures *) ext;
1086 features->samplerYcbcrConversion = true;
1087 break;
1088 }
1089
1090 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
1091 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
1092 (VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
1093 features->scalarBlockLayout = true;
1094 break;
1095 }
1096
1097 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR: {
1098 VkPhysicalDeviceShaderAtomicInt64FeaturesKHR *features = (void *)ext;
1099 features->shaderBufferInt64Atomics =
1100 pdevice->info.gen >= 9 && pdevice->use_softpin;
1101 features->shaderSharedInt64Atomics = VK_FALSE;
1102 break;
1103 }
1104
1105 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
1106 VkPhysicalDeviceShaderDrawParametersFeatures *features = (void *)ext;
1107 features->shaderDrawParameters = true;
1108 break;
1109 }
1110
1111 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
1112 VkPhysicalDeviceVariablePointersFeatures *features = (void *)ext;
1113 features->variablePointersStorageBuffer = true;
1114 features->variablePointers = true;
1115 break;
1116 }
1117
1118 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
1119 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
1120 (VkPhysicalDeviceTransformFeedbackFeaturesEXT *)ext;
1121 features->transformFeedback = true;
1122 features->geometryStreams = true;
1123 break;
1124 }
1125
1126 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
1127 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
1128 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
1129 features->vertexAttributeInstanceRateDivisor = true;
1130 features->vertexAttributeInstanceRateZeroDivisor = true;
1131 break;
1132 }
1133
1134 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT: {
1135 VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *features =
1136 (VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *)ext;
1137 features->ycbcrImageArrays = true;
1138 break;
1139 }
1140
1141 default:
1142 anv_debug_ignored_stype(ext->sType);
1143 break;
1144 }
1145 }
1146 }
1147
1148 void anv_GetPhysicalDeviceProperties(
1149 VkPhysicalDevice physicalDevice,
1150 VkPhysicalDeviceProperties* pProperties)
1151 {
1152 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1153 const struct gen_device_info *devinfo = &pdevice->info;
1154
1155 /* See assertions made when programming the buffer surface state. */
1156 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
1157 (1ul << 30) : (1ul << 27);
1158
1159 const uint32_t max_ssbos = pdevice->has_a64_buffer_access ? UINT16_MAX : 64;
1160 const uint32_t max_textures =
1161 pdevice->has_bindless_images ? UINT16_MAX : 128;
1162 const uint32_t max_samplers =
1163 pdevice->has_bindless_samplers ? UINT16_MAX :
1164 (devinfo->gen >= 8 || devinfo->is_haswell) ? 128 : 16;
1165 const uint32_t max_images =
1166 pdevice->has_bindless_images ? UINT16_MAX : MAX_IMAGES;
1167
1168 /* The moment we have anything bindless, claim a high per-stage limit */
1169 const uint32_t max_per_stage =
1170 pdevice->has_a64_buffer_access ? UINT32_MAX :
1171 MAX_BINDING_TABLE_SIZE - MAX_RTS;
1172
1173 VkSampleCountFlags sample_counts =
1174 isl_device_get_sample_counts(&pdevice->isl_dev);
1175
1176
1177 VkPhysicalDeviceLimits limits = {
1178 .maxImageDimension1D = (1 << 14),
1179 .maxImageDimension2D = (1 << 14),
1180 .maxImageDimension3D = (1 << 11),
1181 .maxImageDimensionCube = (1 << 14),
1182 .maxImageArrayLayers = (1 << 11),
1183 .maxTexelBufferElements = 128 * 1024 * 1024,
1184 .maxUniformBufferRange = (1ul << 27),
1185 .maxStorageBufferRange = max_raw_buffer_sz,
1186 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
1187 .maxMemoryAllocationCount = UINT32_MAX,
1188 .maxSamplerAllocationCount = 64 * 1024,
1189 .bufferImageGranularity = 64, /* A cache line */
1190 .sparseAddressSpaceSize = 0,
1191 .maxBoundDescriptorSets = MAX_SETS,
1192 .maxPerStageDescriptorSamplers = max_samplers,
1193 .maxPerStageDescriptorUniformBuffers = 64,
1194 .maxPerStageDescriptorStorageBuffers = max_ssbos,
1195 .maxPerStageDescriptorSampledImages = max_textures,
1196 .maxPerStageDescriptorStorageImages = max_images,
1197 .maxPerStageDescriptorInputAttachments = 64,
1198 .maxPerStageResources = max_per_stage,
1199 .maxDescriptorSetSamplers = 6 * max_samplers, /* number of stages * maxPerStageDescriptorSamplers */
1200 .maxDescriptorSetUniformBuffers = 6 * 64, /* number of stages * maxPerStageDescriptorUniformBuffers */
1201 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
1202 .maxDescriptorSetStorageBuffers = 6 * max_ssbos, /* number of stages * maxPerStageDescriptorStorageBuffers */
1203 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
1204 .maxDescriptorSetSampledImages = 6 * max_textures, /* number of stages * maxPerStageDescriptorSampledImages */
1205 .maxDescriptorSetStorageImages = 6 * max_images, /* number of stages * maxPerStageDescriptorStorageImages */
1206 .maxDescriptorSetInputAttachments = 256,
1207 .maxVertexInputAttributes = MAX_VBS,
1208 .maxVertexInputBindings = MAX_VBS,
1209 .maxVertexInputAttributeOffset = 2047,
1210 .maxVertexInputBindingStride = 2048,
1211 .maxVertexOutputComponents = 128,
1212 .maxTessellationGenerationLevel = 64,
1213 .maxTessellationPatchSize = 32,
1214 .maxTessellationControlPerVertexInputComponents = 128,
1215 .maxTessellationControlPerVertexOutputComponents = 128,
1216 .maxTessellationControlPerPatchOutputComponents = 128,
1217 .maxTessellationControlTotalOutputComponents = 2048,
1218 .maxTessellationEvaluationInputComponents = 128,
1219 .maxTessellationEvaluationOutputComponents = 128,
1220 .maxGeometryShaderInvocations = 32,
1221 .maxGeometryInputComponents = 64,
1222 .maxGeometryOutputComponents = 128,
1223 .maxGeometryOutputVertices = 256,
1224 .maxGeometryTotalOutputComponents = 1024,
1225 .maxFragmentInputComponents = 112, /* 128 components - (POS, PSIZ, CLIP_DIST0, CLIP_DIST1) */
1226 .maxFragmentOutputAttachments = 8,
1227 .maxFragmentDualSrcAttachments = 1,
1228 .maxFragmentCombinedOutputResources = 8,
1229 .maxComputeSharedMemorySize = 32768,
1230 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
1231 .maxComputeWorkGroupInvocations = 32 * devinfo->max_cs_threads,
1232 .maxComputeWorkGroupSize = {
1233 16 * devinfo->max_cs_threads,
1234 16 * devinfo->max_cs_threads,
1235 16 * devinfo->max_cs_threads,
1236 },
1237 .subPixelPrecisionBits = 8,
1238 .subTexelPrecisionBits = 8,
1239 .mipmapPrecisionBits = 8,
1240 .maxDrawIndexedIndexValue = UINT32_MAX,
1241 .maxDrawIndirectCount = UINT32_MAX,
1242 .maxSamplerLodBias = 16,
1243 .maxSamplerAnisotropy = 16,
1244 .maxViewports = MAX_VIEWPORTS,
1245 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1246 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1247 .viewportSubPixelBits = 13, /* We take a float? */
1248 .minMemoryMapAlignment = 4096, /* A page */
1249 .minTexelBufferOffsetAlignment = 1,
1250 /* We need 16 for UBO block reads to work and 32 for push UBOs */
1251 .minUniformBufferOffsetAlignment = 32,
1252 .minStorageBufferOffsetAlignment = 4,
1253 .minTexelOffset = -8,
1254 .maxTexelOffset = 7,
1255 .minTexelGatherOffset = -32,
1256 .maxTexelGatherOffset = 31,
1257 .minInterpolationOffset = -0.5,
1258 .maxInterpolationOffset = 0.4375,
1259 .subPixelInterpolationOffsetBits = 4,
1260 .maxFramebufferWidth = (1 << 14),
1261 .maxFramebufferHeight = (1 << 14),
1262 .maxFramebufferLayers = (1 << 11),
1263 .framebufferColorSampleCounts = sample_counts,
1264 .framebufferDepthSampleCounts = sample_counts,
1265 .framebufferStencilSampleCounts = sample_counts,
1266 .framebufferNoAttachmentsSampleCounts = sample_counts,
1267 .maxColorAttachments = MAX_RTS,
1268 .sampledImageColorSampleCounts = sample_counts,
1269 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1270 .sampledImageDepthSampleCounts = sample_counts,
1271 .sampledImageStencilSampleCounts = sample_counts,
1272 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1273 .maxSampleMaskWords = 1,
1274 .timestampComputeAndGraphics = false,
1275 .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
1276 .maxClipDistances = 8,
1277 .maxCullDistances = 8,
1278 .maxCombinedClipAndCullDistances = 8,
1279 .discreteQueuePriorities = 2,
1280 .pointSizeRange = { 0.125, 255.875 },
1281 .lineWidthRange = { 0.0, 7.9921875 },
1282 .pointSizeGranularity = (1.0 / 8.0),
1283 .lineWidthGranularity = (1.0 / 128.0),
1284 .strictLines = false, /* FINISHME */
1285 .standardSampleLocations = true,
1286 .optimalBufferCopyOffsetAlignment = 128,
1287 .optimalBufferCopyRowPitchAlignment = 128,
1288 .nonCoherentAtomSize = 64,
1289 };
1290
1291 *pProperties = (VkPhysicalDeviceProperties) {
1292 .apiVersion = anv_physical_device_api_version(pdevice),
1293 .driverVersion = vk_get_driver_version(),
1294 .vendorID = 0x8086,
1295 .deviceID = pdevice->chipset_id,
1296 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1297 .limits = limits,
1298 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
1299 };
1300
1301 snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
1302 "%s", pdevice->name);
1303 memcpy(pProperties->pipelineCacheUUID,
1304 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
1305 }
1306
1307 void anv_GetPhysicalDeviceProperties2(
1308 VkPhysicalDevice physicalDevice,
1309 VkPhysicalDeviceProperties2* pProperties)
1310 {
1311 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
1312
1313 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1314
1315 vk_foreach_struct(ext, pProperties->pNext) {
1316 switch (ext->sType) {
1317 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR: {
1318 VkPhysicalDeviceDepthStencilResolvePropertiesKHR *props =
1319 (VkPhysicalDeviceDepthStencilResolvePropertiesKHR *)ext;
1320
1321 /* We support all of the depth resolve modes */
1322 props->supportedDepthResolveModes =
1323 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1324 VK_RESOLVE_MODE_AVERAGE_BIT_KHR |
1325 VK_RESOLVE_MODE_MIN_BIT_KHR |
1326 VK_RESOLVE_MODE_MAX_BIT_KHR;
1327
1328 /* Average doesn't make sense for stencil so we don't support that */
1329 props->supportedStencilResolveModes =
1330 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR;
1331 if (pdevice->info.gen >= 8) {
1332 /* The advanced stencil resolve modes currently require stencil
1333 * sampling be supported by the hardware.
1334 */
1335 props->supportedStencilResolveModes |=
1336 VK_RESOLVE_MODE_MIN_BIT_KHR |
1337 VK_RESOLVE_MODE_MAX_BIT_KHR;
1338 }
1339
1340 props->independentResolveNone = true;
1341 props->independentResolve = true;
1342 break;
1343 }
1344
1345 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT: {
1346 VkPhysicalDeviceDescriptorIndexingPropertiesEXT *props =
1347 (VkPhysicalDeviceDescriptorIndexingPropertiesEXT *)ext;
1348
1349 /* It's a bit hard to exactly map our implementation to the limits
1350 * described here. The bindless surface handle in the extended
1351 * message descriptors is 20 bits and it's an index into the table of
1352 * RENDER_SURFACE_STATE structs that starts at bindless surface base
1353 * address. Given that most things consume two surface states per
1354 * view (general/sampled for textures and write-only/read-write for
1355 * images), we claim 2^19 things.
1356 *
1357 * For SSBOs, we just use A64 messages so there is no real limit
1358 * there beyond the limit on the total size of a descriptor set.
1359 */
1360 const unsigned max_bindless_views = 1 << 19;
1361
1362 props->maxUpdateAfterBindDescriptorsInAllPools = max_bindless_views;
1363 props->shaderUniformBufferArrayNonUniformIndexingNative = false;
1364 props->shaderSampledImageArrayNonUniformIndexingNative = false;
1365 props->shaderStorageBufferArrayNonUniformIndexingNative = true;
1366 props->shaderStorageImageArrayNonUniformIndexingNative = false;
1367 props->shaderInputAttachmentArrayNonUniformIndexingNative = false;
1368 props->robustBufferAccessUpdateAfterBind = true;
1369 props->quadDivergentImplicitLod = false;
1370 props->maxPerStageDescriptorUpdateAfterBindSamplers = max_bindless_views;
1371 props->maxPerStageDescriptorUpdateAfterBindUniformBuffers = 0;
1372 props->maxPerStageDescriptorUpdateAfterBindStorageBuffers = UINT32_MAX;
1373 props->maxPerStageDescriptorUpdateAfterBindSampledImages = max_bindless_views;
1374 props->maxPerStageDescriptorUpdateAfterBindStorageImages = max_bindless_views;
1375 props->maxPerStageDescriptorUpdateAfterBindInputAttachments = 0;
1376 props->maxPerStageUpdateAfterBindResources = UINT32_MAX;
1377 props->maxDescriptorSetUpdateAfterBindSamplers = max_bindless_views;
1378 props->maxDescriptorSetUpdateAfterBindUniformBuffers = 0;
1379 props->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = 0;
1380 props->maxDescriptorSetUpdateAfterBindStorageBuffers = UINT32_MAX;
1381 props->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2;
1382 props->maxDescriptorSetUpdateAfterBindSampledImages = max_bindless_views;
1383 props->maxDescriptorSetUpdateAfterBindStorageImages = max_bindless_views;
1384 props->maxDescriptorSetUpdateAfterBindInputAttachments = 0;
1385 break;
1386 }
1387
1388 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
1389 VkPhysicalDeviceDriverPropertiesKHR *driver_props =
1390 (VkPhysicalDeviceDriverPropertiesKHR *) ext;
1391
1392 driver_props->driverID = VK_DRIVER_ID_INTEL_OPEN_SOURCE_MESA_KHR;
1393 util_snprintf(driver_props->driverName, VK_MAX_DRIVER_NAME_SIZE_KHR,
1394 "Intel open-source Mesa driver");
1395
1396 util_snprintf(driver_props->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1397 "Mesa " PACKAGE_VERSION MESA_GIT_SHA1);
1398
1399 driver_props->conformanceVersion = (VkConformanceVersionKHR) {
1400 .major = 1,
1401 .minor = 1,
1402 .subminor = 2,
1403 .patch = 0,
1404 };
1405 break;
1406 }
1407
1408 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1409 VkPhysicalDeviceExternalMemoryHostPropertiesEXT *props =
1410 (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1411 /* Userptr needs page aligned memory. */
1412 props->minImportedHostPointerAlignment = 4096;
1413 break;
1414 }
1415
1416 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1417 VkPhysicalDeviceIDProperties *id_props =
1418 (VkPhysicalDeviceIDProperties *)ext;
1419 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1420 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1421 /* The LUID is for Windows. */
1422 id_props->deviceLUIDValid = false;
1423 break;
1424 }
1425
1426 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT: {
1427 VkPhysicalDeviceInlineUniformBlockPropertiesEXT *props =
1428 (VkPhysicalDeviceInlineUniformBlockPropertiesEXT *)ext;
1429 props->maxInlineUniformBlockSize = MAX_INLINE_UNIFORM_BLOCK_SIZE;
1430 props->maxPerStageDescriptorInlineUniformBlocks =
1431 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1432 props->maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks =
1433 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1434 props->maxDescriptorSetInlineUniformBlocks =
1435 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1436 props->maxDescriptorSetUpdateAfterBindInlineUniformBlocks =
1437 MAX_INLINE_UNIFORM_BLOCK_DESCRIPTORS;
1438 break;
1439 }
1440
1441 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1442 VkPhysicalDeviceMaintenance3Properties *props =
1443 (VkPhysicalDeviceMaintenance3Properties *)ext;
1444 /* This value doesn't matter for us today as our per-stage
1445 * descriptors are the real limit.
1446 */
1447 props->maxPerSetDescriptors = 1024;
1448 props->maxMemoryAllocationSize = MAX_MEMORY_ALLOCATION_SIZE;
1449 break;
1450 }
1451
1452 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1453 VkPhysicalDeviceMultiviewProperties *properties =
1454 (VkPhysicalDeviceMultiviewProperties *)ext;
1455 properties->maxMultiviewViewCount = 16;
1456 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
1457 break;
1458 }
1459
1460 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1461 VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1462 (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1463 properties->pciDomain = pdevice->pci_info.domain;
1464 properties->pciBus = pdevice->pci_info.bus;
1465 properties->pciDevice = pdevice->pci_info.device;
1466 properties->pciFunction = pdevice->pci_info.function;
1467 break;
1468 }
1469
1470 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1471 VkPhysicalDevicePointClippingProperties *properties =
1472 (VkPhysicalDevicePointClippingProperties *) ext;
1473 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1474 anv_finishme("Implement pop-free point clipping");
1475 break;
1476 }
1477
1478 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
1479 VkPhysicalDeviceProtectedMemoryProperties *props =
1480 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
1481 props->protectedNoFault = false;
1482 break;
1483 }
1484
1485 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1486 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1487 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1488
1489 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1490 break;
1491 }
1492
1493 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
1494 VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
1495 (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
1496 properties->filterMinmaxImageComponentMapping = pdevice->info.gen >= 9;
1497 properties->filterMinmaxSingleComponentFormats = true;
1498 break;
1499 }
1500
1501 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1502 VkPhysicalDeviceSubgroupProperties *properties = (void *)ext;
1503
1504 properties->subgroupSize = BRW_SUBGROUP_SIZE;
1505
1506 VkShaderStageFlags scalar_stages = 0;
1507 for (unsigned stage = 0; stage < MESA_SHADER_STAGES; stage++) {
1508 if (pdevice->compiler->scalar_stage[stage])
1509 scalar_stages |= mesa_to_vk_shader_stage(stage);
1510 }
1511 properties->supportedStages = scalar_stages;
1512
1513 properties->supportedOperations = VK_SUBGROUP_FEATURE_BASIC_BIT |
1514 VK_SUBGROUP_FEATURE_VOTE_BIT |
1515 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1516 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1517 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1518 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT |
1519 VK_SUBGROUP_FEATURE_CLUSTERED_BIT |
1520 VK_SUBGROUP_FEATURE_QUAD_BIT;
1521 properties->quadOperationsInAllStages = true;
1522 break;
1523 }
1524
1525 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
1526 VkPhysicalDeviceTransformFeedbackPropertiesEXT *props =
1527 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
1528
1529 props->maxTransformFeedbackStreams = MAX_XFB_STREAMS;
1530 props->maxTransformFeedbackBuffers = MAX_XFB_BUFFERS;
1531 props->maxTransformFeedbackBufferSize = (1ull << 32);
1532 props->maxTransformFeedbackStreamDataSize = 128 * 4;
1533 props->maxTransformFeedbackBufferDataSize = 128 * 4;
1534 props->maxTransformFeedbackBufferDataStride = 2048;
1535 props->transformFeedbackQueries = true;
1536 props->transformFeedbackStreamsLinesTriangles = false;
1537 props->transformFeedbackRasterizationStreamSelect = false;
1538 props->transformFeedbackDraw = true;
1539 break;
1540 }
1541
1542 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1543 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *props =
1544 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1545 /* We have to restrict this a bit for multiview */
1546 props->maxVertexAttribDivisor = UINT32_MAX / 16;
1547 break;
1548 }
1549
1550 default:
1551 anv_debug_ignored_stype(ext->sType);
1552 break;
1553 }
1554 }
1555 }
1556
1557 /* We support exactly one queue family. */
1558 static const VkQueueFamilyProperties
1559 anv_queue_family_properties = {
1560 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1561 VK_QUEUE_COMPUTE_BIT |
1562 VK_QUEUE_TRANSFER_BIT,
1563 .queueCount = 1,
1564 .timestampValidBits = 36, /* XXX: Real value here */
1565 .minImageTransferGranularity = { 1, 1, 1 },
1566 };
1567
1568 void anv_GetPhysicalDeviceQueueFamilyProperties(
1569 VkPhysicalDevice physicalDevice,
1570 uint32_t* pCount,
1571 VkQueueFamilyProperties* pQueueFamilyProperties)
1572 {
1573 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
1574
1575 vk_outarray_append(&out, p) {
1576 *p = anv_queue_family_properties;
1577 }
1578 }
1579
1580 void anv_GetPhysicalDeviceQueueFamilyProperties2(
1581 VkPhysicalDevice physicalDevice,
1582 uint32_t* pQueueFamilyPropertyCount,
1583 VkQueueFamilyProperties2* pQueueFamilyProperties)
1584 {
1585
1586 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
1587
1588 vk_outarray_append(&out, p) {
1589 p->queueFamilyProperties = anv_queue_family_properties;
1590
1591 vk_foreach_struct(s, p->pNext) {
1592 anv_debug_ignored_stype(s->sType);
1593 }
1594 }
1595 }
1596
1597 void anv_GetPhysicalDeviceMemoryProperties(
1598 VkPhysicalDevice physicalDevice,
1599 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
1600 {
1601 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1602
1603 pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
1604 for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
1605 pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
1606 .propertyFlags = physical_device->memory.types[i].propertyFlags,
1607 .heapIndex = physical_device->memory.types[i].heapIndex,
1608 };
1609 }
1610
1611 pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
1612 for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
1613 pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
1614 .size = physical_device->memory.heaps[i].size,
1615 .flags = physical_device->memory.heaps[i].flags,
1616 };
1617 }
1618 }
1619
1620 void anv_GetPhysicalDeviceMemoryProperties2(
1621 VkPhysicalDevice physicalDevice,
1622 VkPhysicalDeviceMemoryProperties2* pMemoryProperties)
1623 {
1624 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1625 &pMemoryProperties->memoryProperties);
1626
1627 vk_foreach_struct(ext, pMemoryProperties->pNext) {
1628 switch (ext->sType) {
1629 default:
1630 anv_debug_ignored_stype(ext->sType);
1631 break;
1632 }
1633 }
1634 }
1635
1636 void
1637 anv_GetDeviceGroupPeerMemoryFeatures(
1638 VkDevice device,
1639 uint32_t heapIndex,
1640 uint32_t localDeviceIndex,
1641 uint32_t remoteDeviceIndex,
1642 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
1643 {
1644 assert(localDeviceIndex == 0 && remoteDeviceIndex == 0);
1645 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
1646 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
1647 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
1648 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
1649 }
1650
1651 PFN_vkVoidFunction anv_GetInstanceProcAddr(
1652 VkInstance _instance,
1653 const char* pName)
1654 {
1655 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1656
1657 /* The Vulkan 1.0 spec for vkGetInstanceProcAddr has a table of exactly
1658 * when we have to return valid function pointers, NULL, or it's left
1659 * undefined. See the table for exact details.
1660 */
1661 if (pName == NULL)
1662 return NULL;
1663
1664 #define LOOKUP_ANV_ENTRYPOINT(entrypoint) \
1665 if (strcmp(pName, "vk" #entrypoint) == 0) \
1666 return (PFN_vkVoidFunction)anv_##entrypoint
1667
1668 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceExtensionProperties);
1669 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceLayerProperties);
1670 LOOKUP_ANV_ENTRYPOINT(EnumerateInstanceVersion);
1671 LOOKUP_ANV_ENTRYPOINT(CreateInstance);
1672
1673 #undef LOOKUP_ANV_ENTRYPOINT
1674
1675 if (instance == NULL)
1676 return NULL;
1677
1678 int idx = anv_get_instance_entrypoint_index(pName);
1679 if (idx >= 0)
1680 return instance->dispatch.entrypoints[idx];
1681
1682 idx = anv_get_device_entrypoint_index(pName);
1683 if (idx >= 0)
1684 return instance->device_dispatch.entrypoints[idx];
1685
1686 return NULL;
1687 }
1688
1689 /* With version 1+ of the loader interface the ICD should expose
1690 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
1691 */
1692 PUBLIC
1693 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1694 VkInstance instance,
1695 const char* pName);
1696
1697 PUBLIC
1698 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
1699 VkInstance instance,
1700 const char* pName)
1701 {
1702 return anv_GetInstanceProcAddr(instance, pName);
1703 }
1704
1705 PFN_vkVoidFunction anv_GetDeviceProcAddr(
1706 VkDevice _device,
1707 const char* pName)
1708 {
1709 ANV_FROM_HANDLE(anv_device, device, _device);
1710
1711 if (!device || !pName)
1712 return NULL;
1713
1714 int idx = anv_get_device_entrypoint_index(pName);
1715 if (idx < 0)
1716 return NULL;
1717
1718 return device->dispatch.entrypoints[idx];
1719 }
1720
1721 VkResult
1722 anv_CreateDebugReportCallbackEXT(VkInstance _instance,
1723 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
1724 const VkAllocationCallbacks* pAllocator,
1725 VkDebugReportCallbackEXT* pCallback)
1726 {
1727 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1728 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
1729 pCreateInfo, pAllocator, &instance->alloc,
1730 pCallback);
1731 }
1732
1733 void
1734 anv_DestroyDebugReportCallbackEXT(VkInstance _instance,
1735 VkDebugReportCallbackEXT _callback,
1736 const VkAllocationCallbacks* pAllocator)
1737 {
1738 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1739 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
1740 _callback, pAllocator, &instance->alloc);
1741 }
1742
1743 void
1744 anv_DebugReportMessageEXT(VkInstance _instance,
1745 VkDebugReportFlagsEXT flags,
1746 VkDebugReportObjectTypeEXT objectType,
1747 uint64_t object,
1748 size_t location,
1749 int32_t messageCode,
1750 const char* pLayerPrefix,
1751 const char* pMessage)
1752 {
1753 ANV_FROM_HANDLE(anv_instance, instance, _instance);
1754 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
1755 object, location, messageCode, pLayerPrefix, pMessage);
1756 }
1757
1758 static void
1759 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
1760 {
1761 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1762 queue->device = device;
1763 queue->flags = 0;
1764 }
1765
1766 static void
1767 anv_queue_finish(struct anv_queue *queue)
1768 {
1769 }
1770
1771 static struct anv_state
1772 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
1773 {
1774 struct anv_state state;
1775
1776 state = anv_state_pool_alloc(pool, size, align);
1777 memcpy(state.map, p, size);
1778
1779 return state;
1780 }
1781
1782 struct gen8_border_color {
1783 union {
1784 float float32[4];
1785 uint32_t uint32[4];
1786 };
1787 /* Pad out to 64 bytes */
1788 uint32_t _pad[12];
1789 };
1790
1791 static void
1792 anv_device_init_border_colors(struct anv_device *device)
1793 {
1794 static const struct gen8_border_color border_colors[] = {
1795 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1796 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1797 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1798 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1799 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1800 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1801 };
1802
1803 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1804 sizeof(border_colors), 64,
1805 border_colors);
1806 }
1807
1808 static void
1809 anv_device_init_trivial_batch(struct anv_device *device)
1810 {
1811 anv_bo_init_new(&device->trivial_batch_bo, device, 4096);
1812
1813 if (device->instance->physicalDevice.has_exec_async)
1814 device->trivial_batch_bo.flags |= EXEC_OBJECT_ASYNC;
1815
1816 if (device->instance->physicalDevice.use_softpin)
1817 device->trivial_batch_bo.flags |= EXEC_OBJECT_PINNED;
1818
1819 anv_vma_alloc(device, &device->trivial_batch_bo);
1820
1821 void *map = anv_gem_mmap(device, device->trivial_batch_bo.gem_handle,
1822 0, 4096, 0);
1823
1824 struct anv_batch batch = {
1825 .start = map,
1826 .next = map,
1827 .end = map + 4096,
1828 };
1829
1830 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1831 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1832
1833 if (!device->info.has_llc)
1834 gen_clflush_range(map, batch.next - map);
1835
1836 anv_gem_munmap(map, device->trivial_batch_bo.size);
1837 }
1838
1839 VkResult anv_EnumerateDeviceExtensionProperties(
1840 VkPhysicalDevice physicalDevice,
1841 const char* pLayerName,
1842 uint32_t* pPropertyCount,
1843 VkExtensionProperties* pProperties)
1844 {
1845 ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);
1846 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
1847
1848 for (int i = 0; i < ANV_DEVICE_EXTENSION_COUNT; i++) {
1849 if (device->supported_extensions.extensions[i]) {
1850 vk_outarray_append(&out, prop) {
1851 *prop = anv_device_extensions[i];
1852 }
1853 }
1854 }
1855
1856 return vk_outarray_status(&out);
1857 }
1858
1859 static void
1860 anv_device_init_dispatch(struct anv_device *device)
1861 {
1862 const struct anv_device_dispatch_table *genX_table;
1863 switch (device->info.gen) {
1864 case 11:
1865 genX_table = &gen11_device_dispatch_table;
1866 break;
1867 case 10:
1868 genX_table = &gen10_device_dispatch_table;
1869 break;
1870 case 9:
1871 genX_table = &gen9_device_dispatch_table;
1872 break;
1873 case 8:
1874 genX_table = &gen8_device_dispatch_table;
1875 break;
1876 case 7:
1877 if (device->info.is_haswell)
1878 genX_table = &gen75_device_dispatch_table;
1879 else
1880 genX_table = &gen7_device_dispatch_table;
1881 break;
1882 default:
1883 unreachable("unsupported gen\n");
1884 }
1885
1886 for (unsigned i = 0; i < ARRAY_SIZE(device->dispatch.entrypoints); i++) {
1887 /* Vulkan requires that entrypoints for extensions which have not been
1888 * enabled must not be advertised.
1889 */
1890 if (!anv_device_entrypoint_is_enabled(i, device->instance->app_info.api_version,
1891 &device->instance->enabled_extensions,
1892 &device->enabled_extensions)) {
1893 device->dispatch.entrypoints[i] = NULL;
1894 } else if (genX_table->entrypoints[i]) {
1895 device->dispatch.entrypoints[i] = genX_table->entrypoints[i];
1896 } else {
1897 device->dispatch.entrypoints[i] =
1898 anv_device_dispatch_table.entrypoints[i];
1899 }
1900 }
1901 }
1902
1903 static int
1904 vk_priority_to_gen(int priority)
1905 {
1906 switch (priority) {
1907 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1908 return GEN_CONTEXT_LOW_PRIORITY;
1909 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1910 return GEN_CONTEXT_MEDIUM_PRIORITY;
1911 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1912 return GEN_CONTEXT_HIGH_PRIORITY;
1913 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1914 return GEN_CONTEXT_REALTIME_PRIORITY;
1915 default:
1916 unreachable("Invalid priority");
1917 }
1918 }
1919
1920 static void
1921 anv_device_init_hiz_clear_value_bo(struct anv_device *device)
1922 {
1923 anv_bo_init_new(&device->hiz_clear_bo, device, 4096);
1924
1925 if (device->instance->physicalDevice.has_exec_async)
1926 device->hiz_clear_bo.flags |= EXEC_OBJECT_ASYNC;
1927
1928 if (device->instance->physicalDevice.use_softpin)
1929 device->hiz_clear_bo.flags |= EXEC_OBJECT_PINNED;
1930
1931 anv_vma_alloc(device, &device->hiz_clear_bo);
1932
1933 uint32_t *map = anv_gem_mmap(device, device->hiz_clear_bo.gem_handle,
1934 0, 4096, 0);
1935
1936 union isl_color_value hiz_clear = { .u32 = { 0, } };
1937 hiz_clear.f32[0] = ANV_HZ_FC_VAL;
1938
1939 memcpy(map, hiz_clear.u32, sizeof(hiz_clear.u32));
1940 anv_gem_munmap(map, device->hiz_clear_bo.size);
1941 }
1942
1943 static bool
1944 get_bo_from_pool(struct gen_batch_decode_bo *ret,
1945 struct anv_block_pool *pool,
1946 uint64_t address)
1947 {
1948 for (uint32_t i = 0; i < pool->nbos; i++) {
1949 uint64_t bo_address = pool->bos[i].offset & (~0ull >> 16);
1950 uint32_t bo_size = pool->bos[i].size;
1951 if (address >= bo_address && address < (bo_address + bo_size)) {
1952 *ret = (struct gen_batch_decode_bo) {
1953 .addr = bo_address,
1954 .size = bo_size,
1955 .map = pool->bos[i].map,
1956 };
1957 return true;
1958 }
1959 }
1960 return false;
1961 }
1962
1963 /* Finding a buffer for batch decoding */
1964 static struct gen_batch_decode_bo
1965 decode_get_bo(void *v_batch, bool ppgtt, uint64_t address)
1966 {
1967 struct anv_device *device = v_batch;
1968 struct gen_batch_decode_bo ret_bo = {};
1969
1970 assert(ppgtt);
1971
1972 if (get_bo_from_pool(&ret_bo, &device->dynamic_state_pool.block_pool, address))
1973 return ret_bo;
1974 if (get_bo_from_pool(&ret_bo, &device->instruction_state_pool.block_pool, address))
1975 return ret_bo;
1976 if (get_bo_from_pool(&ret_bo, &device->binding_table_pool.block_pool, address))
1977 return ret_bo;
1978 if (get_bo_from_pool(&ret_bo, &device->surface_state_pool.block_pool, address))
1979 return ret_bo;
1980
1981 if (!device->cmd_buffer_being_decoded)
1982 return (struct gen_batch_decode_bo) { };
1983
1984 struct anv_batch_bo **bo;
1985
1986 u_vector_foreach(bo, &device->cmd_buffer_being_decoded->seen_bbos) {
1987 /* The decoder zeroes out the top 16 bits, so we need to as well */
1988 uint64_t bo_address = (*bo)->bo.offset & (~0ull >> 16);
1989
1990 if (address >= bo_address && address < bo_address + (*bo)->bo.size) {
1991 return (struct gen_batch_decode_bo) {
1992 .addr = bo_address,
1993 .size = (*bo)->bo.size,
1994 .map = (*bo)->bo.map,
1995 };
1996 }
1997 }
1998
1999 return (struct gen_batch_decode_bo) { };
2000 }
2001
2002 VkResult anv_CreateDevice(
2003 VkPhysicalDevice physicalDevice,
2004 const VkDeviceCreateInfo* pCreateInfo,
2005 const VkAllocationCallbacks* pAllocator,
2006 VkDevice* pDevice)
2007 {
2008 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
2009 VkResult result;
2010 struct anv_device *device;
2011
2012 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
2013
2014 struct anv_device_extension_table enabled_extensions = { };
2015 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
2016 int idx;
2017 for (idx = 0; idx < ANV_DEVICE_EXTENSION_COUNT; idx++) {
2018 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
2019 anv_device_extensions[idx].extensionName) == 0)
2020 break;
2021 }
2022
2023 if (idx >= ANV_DEVICE_EXTENSION_COUNT)
2024 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
2025
2026 if (!physical_device->supported_extensions.extensions[idx])
2027 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
2028
2029 enabled_extensions.extensions[idx] = true;
2030 }
2031
2032 /* Check enabled features */
2033 if (pCreateInfo->pEnabledFeatures) {
2034 VkPhysicalDeviceFeatures supported_features;
2035 anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
2036 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
2037 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
2038 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
2039 for (uint32_t i = 0; i < num_features; i++) {
2040 if (enabled_feature[i] && !supported_feature[i])
2041 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
2042 }
2043 }
2044
2045 /* Check requested queues and fail if we are requested to create any
2046 * queues with flags we don't support.
2047 */
2048 assert(pCreateInfo->queueCreateInfoCount > 0);
2049 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
2050 if (pCreateInfo->pQueueCreateInfos[i].flags != 0)
2051 return vk_error(VK_ERROR_INITIALIZATION_FAILED);
2052 }
2053
2054 /* Check if client specified queue priority. */
2055 const VkDeviceQueueGlobalPriorityCreateInfoEXT *queue_priority =
2056 vk_find_struct_const(pCreateInfo->pQueueCreateInfos[0].pNext,
2057 DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
2058
2059 VkQueueGlobalPriorityEXT priority =
2060 queue_priority ? queue_priority->globalPriority :
2061 VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
2062
2063 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
2064 sizeof(*device), 8,
2065 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
2066 if (!device)
2067 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2068
2069 const unsigned decode_flags =
2070 GEN_BATCH_DECODE_FULL |
2071 ((INTEL_DEBUG & DEBUG_COLOR) ? GEN_BATCH_DECODE_IN_COLOR : 0) |
2072 GEN_BATCH_DECODE_OFFSETS |
2073 GEN_BATCH_DECODE_FLOATS;
2074
2075 gen_batch_decode_ctx_init(&device->decoder_ctx,
2076 &physical_device->info,
2077 stderr, decode_flags, NULL,
2078 decode_get_bo, NULL, device);
2079
2080 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
2081 device->instance = physical_device->instance;
2082 device->chipset_id = physical_device->chipset_id;
2083 device->no_hw = physical_device->no_hw;
2084 device->_lost = false;
2085
2086 if (pAllocator)
2087 device->alloc = *pAllocator;
2088 else
2089 device->alloc = physical_device->instance->alloc;
2090
2091 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
2092 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
2093 if (device->fd == -1) {
2094 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2095 goto fail_device;
2096 }
2097
2098 device->context_id = anv_gem_create_context(device);
2099 if (device->context_id == -1) {
2100 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2101 goto fail_fd;
2102 }
2103
2104 if (physical_device->use_softpin) {
2105 if (pthread_mutex_init(&device->vma_mutex, NULL) != 0) {
2106 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2107 goto fail_fd;
2108 }
2109
2110 /* keep the page with address zero out of the allocator */
2111 struct anv_memory_heap *low_heap =
2112 &physical_device->memory.heaps[physical_device->memory.heap_count - 1];
2113 util_vma_heap_init(&device->vma_lo, low_heap->vma_start, low_heap->vma_size);
2114 device->vma_lo_available = low_heap->size;
2115
2116 struct anv_memory_heap *high_heap =
2117 &physical_device->memory.heaps[0];
2118 util_vma_heap_init(&device->vma_hi, high_heap->vma_start, high_heap->vma_size);
2119 device->vma_hi_available = physical_device->memory.heap_count == 1 ? 0 :
2120 high_heap->size;
2121 }
2122
2123 list_inithead(&device->memory_objects);
2124
2125 /* As per spec, the driver implementation may deny requests to acquire
2126 * a priority above the default priority (MEDIUM) if the caller does not
2127 * have sufficient privileges. In this scenario VK_ERROR_NOT_PERMITTED_EXT
2128 * is returned.
2129 */
2130 if (physical_device->has_context_priority) {
2131 int err = anv_gem_set_context_param(device->fd, device->context_id,
2132 I915_CONTEXT_PARAM_PRIORITY,
2133 vk_priority_to_gen(priority));
2134 if (err != 0 && priority > VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT) {
2135 result = vk_error(VK_ERROR_NOT_PERMITTED_EXT);
2136 goto fail_fd;
2137 }
2138 }
2139
2140 device->info = physical_device->info;
2141 device->isl_dev = physical_device->isl_dev;
2142
2143 /* On Broadwell and later, we can use batch chaining to more efficiently
2144 * implement growing command buffers. Prior to Haswell, the kernel
2145 * command parser gets in the way and we have to fall back to growing
2146 * the batch.
2147 */
2148 device->can_chain_batches = device->info.gen >= 8;
2149
2150 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
2151 pCreateInfo->pEnabledFeatures->robustBufferAccess;
2152 device->enabled_extensions = enabled_extensions;
2153
2154 anv_device_init_dispatch(device);
2155
2156 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
2157 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2158 goto fail_context_id;
2159 }
2160
2161 pthread_condattr_t condattr;
2162 if (pthread_condattr_init(&condattr) != 0) {
2163 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2164 goto fail_mutex;
2165 }
2166 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
2167 pthread_condattr_destroy(&condattr);
2168 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2169 goto fail_mutex;
2170 }
2171 if (pthread_cond_init(&device->queue_submit, &condattr) != 0) {
2172 pthread_condattr_destroy(&condattr);
2173 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
2174 goto fail_mutex;
2175 }
2176 pthread_condattr_destroy(&condattr);
2177
2178 uint64_t bo_flags =
2179 (physical_device->supports_48bit_addresses ? EXEC_OBJECT_SUPPORTS_48B_ADDRESS : 0) |
2180 (physical_device->has_exec_async ? EXEC_OBJECT_ASYNC : 0) |
2181 (physical_device->has_exec_capture ? EXEC_OBJECT_CAPTURE : 0) |
2182 (physical_device->use_softpin ? EXEC_OBJECT_PINNED : 0);
2183
2184 anv_bo_pool_init(&device->batch_bo_pool, device, bo_flags);
2185
2186 result = anv_bo_cache_init(&device->bo_cache);
2187 if (result != VK_SUCCESS)
2188 goto fail_batch_bo_pool;
2189
2190 if (!physical_device->use_softpin)
2191 bo_flags &= ~EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2192
2193 result = anv_state_pool_init(&device->dynamic_state_pool, device,
2194 DYNAMIC_STATE_POOL_MIN_ADDRESS,
2195 16384,
2196 bo_flags);
2197 if (result != VK_SUCCESS)
2198 goto fail_bo_cache;
2199
2200 result = anv_state_pool_init(&device->instruction_state_pool, device,
2201 INSTRUCTION_STATE_POOL_MIN_ADDRESS,
2202 16384,
2203 bo_flags);
2204 if (result != VK_SUCCESS)
2205 goto fail_dynamic_state_pool;
2206
2207 result = anv_state_pool_init(&device->surface_state_pool, device,
2208 SURFACE_STATE_POOL_MIN_ADDRESS,
2209 4096,
2210 bo_flags);
2211 if (result != VK_SUCCESS)
2212 goto fail_instruction_state_pool;
2213
2214 if (physical_device->use_softpin) {
2215 result = anv_state_pool_init(&device->binding_table_pool, device,
2216 BINDING_TABLE_POOL_MIN_ADDRESS,
2217 4096,
2218 bo_flags);
2219 if (result != VK_SUCCESS)
2220 goto fail_surface_state_pool;
2221 }
2222
2223 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
2224 if (result != VK_SUCCESS)
2225 goto fail_binding_table_pool;
2226
2227 if (physical_device->use_softpin)
2228 device->workaround_bo.flags |= EXEC_OBJECT_PINNED;
2229
2230 if (!anv_vma_alloc(device, &device->workaround_bo))
2231 goto fail_workaround_bo;
2232
2233 anv_device_init_trivial_batch(device);
2234
2235 if (device->info.gen >= 10)
2236 anv_device_init_hiz_clear_value_bo(device);
2237
2238 anv_scratch_pool_init(device, &device->scratch_pool);
2239
2240 anv_queue_init(device, &device->queue);
2241
2242 switch (device->info.gen) {
2243 case 7:
2244 if (!device->info.is_haswell)
2245 result = gen7_init_device_state(device);
2246 else
2247 result = gen75_init_device_state(device);
2248 break;
2249 case 8:
2250 result = gen8_init_device_state(device);
2251 break;
2252 case 9:
2253 result = gen9_init_device_state(device);
2254 break;
2255 case 10:
2256 result = gen10_init_device_state(device);
2257 break;
2258 case 11:
2259 result = gen11_init_device_state(device);
2260 break;
2261 default:
2262 /* Shouldn't get here as we don't create physical devices for any other
2263 * gens. */
2264 unreachable("unhandled gen");
2265 }
2266 if (result != VK_SUCCESS)
2267 goto fail_workaround_bo;
2268
2269 anv_pipeline_cache_init(&device->default_pipeline_cache, device, true);
2270
2271 anv_device_init_blorp(device);
2272
2273 anv_device_init_border_colors(device);
2274
2275 *pDevice = anv_device_to_handle(device);
2276
2277 return VK_SUCCESS;
2278
2279 fail_workaround_bo:
2280 anv_queue_finish(&device->queue);
2281 anv_scratch_pool_finish(device, &device->scratch_pool);
2282 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
2283 anv_gem_close(device, device->workaround_bo.gem_handle);
2284 fail_binding_table_pool:
2285 if (physical_device->use_softpin)
2286 anv_state_pool_finish(&device->binding_table_pool);
2287 fail_surface_state_pool:
2288 anv_state_pool_finish(&device->surface_state_pool);
2289 fail_instruction_state_pool:
2290 anv_state_pool_finish(&device->instruction_state_pool);
2291 fail_dynamic_state_pool:
2292 anv_state_pool_finish(&device->dynamic_state_pool);
2293 fail_bo_cache:
2294 anv_bo_cache_finish(&device->bo_cache);
2295 fail_batch_bo_pool:
2296 anv_bo_pool_finish(&device->batch_bo_pool);
2297 pthread_cond_destroy(&device->queue_submit);
2298 fail_mutex:
2299 pthread_mutex_destroy(&device->mutex);
2300 fail_context_id:
2301 anv_gem_destroy_context(device, device->context_id);
2302 fail_fd:
2303 close(device->fd);
2304 fail_device:
2305 vk_free(&device->alloc, device);
2306
2307 return result;
2308 }
2309
2310 void anv_DestroyDevice(
2311 VkDevice _device,
2312 const VkAllocationCallbacks* pAllocator)
2313 {
2314 ANV_FROM_HANDLE(anv_device, device, _device);
2315 struct anv_physical_device *physical_device;
2316
2317 if (!device)
2318 return;
2319
2320 physical_device = &device->instance->physicalDevice;
2321
2322 anv_device_finish_blorp(device);
2323
2324 anv_pipeline_cache_finish(&device->default_pipeline_cache);
2325
2326 anv_queue_finish(&device->queue);
2327
2328 #ifdef HAVE_VALGRIND
2329 /* We only need to free these to prevent valgrind errors. The backing
2330 * BO will go away in a couple of lines so we don't actually leak.
2331 */
2332 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
2333 #endif
2334
2335 anv_scratch_pool_finish(device, &device->scratch_pool);
2336
2337 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
2338 anv_vma_free(device, &device->workaround_bo);
2339 anv_gem_close(device, device->workaround_bo.gem_handle);
2340
2341 anv_vma_free(device, &device->trivial_batch_bo);
2342 anv_gem_close(device, device->trivial_batch_bo.gem_handle);
2343 if (device->info.gen >= 10)
2344 anv_gem_close(device, device->hiz_clear_bo.gem_handle);
2345
2346 if (physical_device->use_softpin)
2347 anv_state_pool_finish(&device->binding_table_pool);
2348 anv_state_pool_finish(&device->surface_state_pool);
2349 anv_state_pool_finish(&device->instruction_state_pool);
2350 anv_state_pool_finish(&device->dynamic_state_pool);
2351
2352 anv_bo_cache_finish(&device->bo_cache);
2353
2354 anv_bo_pool_finish(&device->batch_bo_pool);
2355
2356 pthread_cond_destroy(&device->queue_submit);
2357 pthread_mutex_destroy(&device->mutex);
2358
2359 anv_gem_destroy_context(device, device->context_id);
2360
2361 gen_batch_decode_ctx_finish(&device->decoder_ctx);
2362
2363 close(device->fd);
2364
2365 vk_free(&device->alloc, device);
2366 }
2367
2368 VkResult anv_EnumerateInstanceLayerProperties(
2369 uint32_t* pPropertyCount,
2370 VkLayerProperties* pProperties)
2371 {
2372 if (pProperties == NULL) {
2373 *pPropertyCount = 0;
2374 return VK_SUCCESS;
2375 }
2376
2377 /* None supported at this time */
2378 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
2379 }
2380
2381 VkResult anv_EnumerateDeviceLayerProperties(
2382 VkPhysicalDevice physicalDevice,
2383 uint32_t* pPropertyCount,
2384 VkLayerProperties* pProperties)
2385 {
2386 if (pProperties == NULL) {
2387 *pPropertyCount = 0;
2388 return VK_SUCCESS;
2389 }
2390
2391 /* None supported at this time */
2392 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
2393 }
2394
2395 void anv_GetDeviceQueue(
2396 VkDevice _device,
2397 uint32_t queueNodeIndex,
2398 uint32_t queueIndex,
2399 VkQueue* pQueue)
2400 {
2401 ANV_FROM_HANDLE(anv_device, device, _device);
2402
2403 assert(queueIndex == 0);
2404
2405 *pQueue = anv_queue_to_handle(&device->queue);
2406 }
2407
2408 void anv_GetDeviceQueue2(
2409 VkDevice _device,
2410 const VkDeviceQueueInfo2* pQueueInfo,
2411 VkQueue* pQueue)
2412 {
2413 ANV_FROM_HANDLE(anv_device, device, _device);
2414
2415 assert(pQueueInfo->queueIndex == 0);
2416
2417 if (pQueueInfo->flags == device->queue.flags)
2418 *pQueue = anv_queue_to_handle(&device->queue);
2419 else
2420 *pQueue = NULL;
2421 }
2422
2423 VkResult
2424 _anv_device_set_lost(struct anv_device *device,
2425 const char *file, int line,
2426 const char *msg, ...)
2427 {
2428 VkResult err;
2429 va_list ap;
2430
2431 device->_lost = true;
2432
2433 va_start(ap, msg);
2434 err = __vk_errorv(device->instance, device,
2435 VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT,
2436 VK_ERROR_DEVICE_LOST, file, line, msg, ap);
2437 va_end(ap);
2438
2439 if (env_var_as_boolean("ANV_ABORT_ON_DEVICE_LOSS", false))
2440 abort();
2441
2442 return err;
2443 }
2444
2445 VkResult
2446 anv_device_query_status(struct anv_device *device)
2447 {
2448 /* This isn't likely as most of the callers of this function already check
2449 * for it. However, it doesn't hurt to check and it potentially lets us
2450 * avoid an ioctl.
2451 */
2452 if (anv_device_is_lost(device))
2453 return VK_ERROR_DEVICE_LOST;
2454
2455 uint32_t active, pending;
2456 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
2457 if (ret == -1) {
2458 /* We don't know the real error. */
2459 return anv_device_set_lost(device, "get_reset_stats failed: %m");
2460 }
2461
2462 if (active) {
2463 return anv_device_set_lost(device, "GPU hung on one of our command buffers");
2464 } else if (pending) {
2465 return anv_device_set_lost(device, "GPU hung with commands in-flight");
2466 }
2467
2468 return VK_SUCCESS;
2469 }
2470
2471 VkResult
2472 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
2473 {
2474 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
2475 * Other usages of the BO (such as on different hardware) will not be
2476 * flagged as "busy" by this ioctl. Use with care.
2477 */
2478 int ret = anv_gem_busy(device, bo->gem_handle);
2479 if (ret == 1) {
2480 return VK_NOT_READY;
2481 } else if (ret == -1) {
2482 /* We don't know the real error. */
2483 return anv_device_set_lost(device, "gem wait failed: %m");
2484 }
2485
2486 /* Query for device status after the busy call. If the BO we're checking
2487 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
2488 * client because it clearly doesn't have valid data. Yes, this most
2489 * likely means an ioctl, but we just did an ioctl to query the busy status
2490 * so it's no great loss.
2491 */
2492 return anv_device_query_status(device);
2493 }
2494
2495 VkResult
2496 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
2497 int64_t timeout)
2498 {
2499 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
2500 if (ret == -1 && errno == ETIME) {
2501 return VK_TIMEOUT;
2502 } else if (ret == -1) {
2503 /* We don't know the real error. */
2504 return anv_device_set_lost(device, "gem wait failed: %m");
2505 }
2506
2507 /* Query for device status after the wait. If the BO we're waiting on got
2508 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
2509 * because it clearly doesn't have valid data. Yes, this most likely means
2510 * an ioctl, but we just did an ioctl to wait so it's no great loss.
2511 */
2512 return anv_device_query_status(device);
2513 }
2514
2515 VkResult anv_DeviceWaitIdle(
2516 VkDevice _device)
2517 {
2518 ANV_FROM_HANDLE(anv_device, device, _device);
2519 if (anv_device_is_lost(device))
2520 return VK_ERROR_DEVICE_LOST;
2521
2522 struct anv_batch batch;
2523
2524 uint32_t cmds[8];
2525 batch.start = batch.next = cmds;
2526 batch.end = (void *) cmds + sizeof(cmds);
2527
2528 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
2529 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
2530
2531 return anv_device_submit_simple_batch(device, &batch);
2532 }
2533
2534 bool
2535 anv_vma_alloc(struct anv_device *device, struct anv_bo *bo)
2536 {
2537 if (!(bo->flags & EXEC_OBJECT_PINNED))
2538 return true;
2539
2540 pthread_mutex_lock(&device->vma_mutex);
2541
2542 bo->offset = 0;
2543
2544 if (bo->flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS &&
2545 device->vma_hi_available >= bo->size) {
2546 uint64_t addr = util_vma_heap_alloc(&device->vma_hi, bo->size, 4096);
2547 if (addr) {
2548 bo->offset = gen_canonical_address(addr);
2549 assert(addr == gen_48b_address(bo->offset));
2550 device->vma_hi_available -= bo->size;
2551 }
2552 }
2553
2554 if (bo->offset == 0 && device->vma_lo_available >= bo->size) {
2555 uint64_t addr = util_vma_heap_alloc(&device->vma_lo, bo->size, 4096);
2556 if (addr) {
2557 bo->offset = gen_canonical_address(addr);
2558 assert(addr == gen_48b_address(bo->offset));
2559 device->vma_lo_available -= bo->size;
2560 }
2561 }
2562
2563 pthread_mutex_unlock(&device->vma_mutex);
2564
2565 return bo->offset != 0;
2566 }
2567
2568 void
2569 anv_vma_free(struct anv_device *device, struct anv_bo *bo)
2570 {
2571 if (!(bo->flags & EXEC_OBJECT_PINNED))
2572 return;
2573
2574 const uint64_t addr_48b = gen_48b_address(bo->offset);
2575
2576 pthread_mutex_lock(&device->vma_mutex);
2577
2578 if (addr_48b >= LOW_HEAP_MIN_ADDRESS &&
2579 addr_48b <= LOW_HEAP_MAX_ADDRESS) {
2580 util_vma_heap_free(&device->vma_lo, addr_48b, bo->size);
2581 device->vma_lo_available += bo->size;
2582 } else {
2583 MAYBE_UNUSED const struct anv_physical_device *physical_device =
2584 &device->instance->physicalDevice;
2585 assert(addr_48b >= physical_device->memory.heaps[0].vma_start &&
2586 addr_48b < (physical_device->memory.heaps[0].vma_start +
2587 physical_device->memory.heaps[0].vma_size));
2588 util_vma_heap_free(&device->vma_hi, addr_48b, bo->size);
2589 device->vma_hi_available += bo->size;
2590 }
2591
2592 pthread_mutex_unlock(&device->vma_mutex);
2593
2594 bo->offset = 0;
2595 }
2596
2597 VkResult
2598 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
2599 {
2600 uint32_t gem_handle = anv_gem_create(device, size);
2601 if (!gem_handle)
2602 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
2603
2604 anv_bo_init(bo, gem_handle, size);
2605
2606 return VK_SUCCESS;
2607 }
2608
2609 VkResult anv_AllocateMemory(
2610 VkDevice _device,
2611 const VkMemoryAllocateInfo* pAllocateInfo,
2612 const VkAllocationCallbacks* pAllocator,
2613 VkDeviceMemory* pMem)
2614 {
2615 ANV_FROM_HANDLE(anv_device, device, _device);
2616 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2617 struct anv_device_memory *mem;
2618 VkResult result = VK_SUCCESS;
2619
2620 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
2621
2622 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
2623 assert(pAllocateInfo->allocationSize > 0);
2624
2625 if (pAllocateInfo->allocationSize > MAX_MEMORY_ALLOCATION_SIZE)
2626 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2627
2628 /* FINISHME: Fail if allocation request exceeds heap size. */
2629
2630 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
2631 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2632 if (mem == NULL)
2633 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2634
2635 assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
2636 mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
2637 mem->map = NULL;
2638 mem->map_size = 0;
2639 mem->ahw = NULL;
2640 mem->host_ptr = NULL;
2641
2642 uint64_t bo_flags = 0;
2643
2644 assert(mem->type->heapIndex < pdevice->memory.heap_count);
2645 if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
2646 bo_flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
2647
2648 const struct wsi_memory_allocate_info *wsi_info =
2649 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
2650 if (wsi_info && wsi_info->implicit_sync) {
2651 /* We need to set the WRITE flag on window system buffers so that GEM
2652 * will know we're writing to them and synchronize uses on other rings
2653 * (eg if the display server uses the blitter ring).
2654 */
2655 bo_flags |= EXEC_OBJECT_WRITE;
2656 } else if (pdevice->has_exec_async) {
2657 bo_flags |= EXEC_OBJECT_ASYNC;
2658 }
2659
2660 if (pdevice->use_softpin)
2661 bo_flags |= EXEC_OBJECT_PINNED;
2662
2663 const VkExportMemoryAllocateInfo *export_info =
2664 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
2665
2666 /* Check if we need to support Android HW buffer export. If so,
2667 * create AHardwareBuffer and import memory from it.
2668 */
2669 bool android_export = false;
2670 if (export_info && export_info->handleTypes &
2671 VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID)
2672 android_export = true;
2673
2674 /* Android memory import. */
2675 const struct VkImportAndroidHardwareBufferInfoANDROID *ahw_import_info =
2676 vk_find_struct_const(pAllocateInfo->pNext,
2677 IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID);
2678
2679 if (ahw_import_info) {
2680 result = anv_import_ahw_memory(_device, mem, ahw_import_info);
2681 if (result != VK_SUCCESS)
2682 goto fail;
2683
2684 goto success;
2685 } else if (android_export) {
2686 result = anv_create_ahw_memory(_device, mem, pAllocateInfo);
2687 if (result != VK_SUCCESS)
2688 goto fail;
2689
2690 const struct VkImportAndroidHardwareBufferInfoANDROID import_info = {
2691 .buffer = mem->ahw,
2692 };
2693 result = anv_import_ahw_memory(_device, mem, &import_info);
2694 if (result != VK_SUCCESS)
2695 goto fail;
2696
2697 goto success;
2698 }
2699
2700 const VkImportMemoryFdInfoKHR *fd_info =
2701 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
2702
2703 /* The Vulkan spec permits handleType to be 0, in which case the struct is
2704 * ignored.
2705 */
2706 if (fd_info && fd_info->handleType) {
2707 /* At the moment, we support only the below handle types. */
2708 assert(fd_info->handleType ==
2709 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2710 fd_info->handleType ==
2711 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2712
2713 result = anv_bo_cache_import(device, &device->bo_cache, fd_info->fd,
2714 bo_flags | ANV_BO_EXTERNAL, &mem->bo);
2715 if (result != VK_SUCCESS)
2716 goto fail;
2717
2718 VkDeviceSize aligned_alloc_size =
2719 align_u64(pAllocateInfo->allocationSize, 4096);
2720
2721 /* For security purposes, we reject importing the bo if it's smaller
2722 * than the requested allocation size. This prevents a malicious client
2723 * from passing a buffer to a trusted client, lying about the size, and
2724 * telling the trusted client to try and texture from an image that goes
2725 * out-of-bounds. This sort of thing could lead to GPU hangs or worse
2726 * in the trusted client. The trusted client can protect itself against
2727 * this sort of attack but only if it can trust the buffer size.
2728 */
2729 if (mem->bo->size < aligned_alloc_size) {
2730 result = vk_errorf(device->instance, device,
2731 VK_ERROR_INVALID_EXTERNAL_HANDLE,
2732 "aligned allocationSize too large for "
2733 "VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT: "
2734 "%"PRIu64"B > %"PRIu64"B",
2735 aligned_alloc_size, mem->bo->size);
2736 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2737 goto fail;
2738 }
2739
2740 /* From the Vulkan spec:
2741 *
2742 * "Importing memory from a file descriptor transfers ownership of
2743 * the file descriptor from the application to the Vulkan
2744 * implementation. The application must not perform any operations on
2745 * the file descriptor after a successful import."
2746 *
2747 * If the import fails, we leave the file descriptor open.
2748 */
2749 close(fd_info->fd);
2750 goto success;
2751 }
2752
2753 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
2754 vk_find_struct_const(pAllocateInfo->pNext,
2755 IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
2756 if (host_ptr_info && host_ptr_info->handleType) {
2757 if (host_ptr_info->handleType ==
2758 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT) {
2759 result = vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2760 goto fail;
2761 }
2762
2763 assert(host_ptr_info->handleType ==
2764 VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
2765
2766 result = anv_bo_cache_import_host_ptr(
2767 device, &device->bo_cache, host_ptr_info->pHostPointer,
2768 pAllocateInfo->allocationSize, bo_flags, &mem->bo);
2769
2770 if (result != VK_SUCCESS)
2771 goto fail;
2772
2773 mem->host_ptr = host_ptr_info->pHostPointer;
2774 goto success;
2775 }
2776
2777 /* Regular allocate (not importing memory). */
2778
2779 if (export_info && export_info->handleTypes)
2780 bo_flags |= ANV_BO_EXTERNAL;
2781
2782 result = anv_bo_cache_alloc(device, &device->bo_cache,
2783 pAllocateInfo->allocationSize, bo_flags,
2784 &mem->bo);
2785 if (result != VK_SUCCESS)
2786 goto fail;
2787
2788 const VkMemoryDedicatedAllocateInfo *dedicated_info =
2789 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
2790 if (dedicated_info && dedicated_info->image != VK_NULL_HANDLE) {
2791 ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);
2792
2793 /* Some legacy (non-modifiers) consumers need the tiling to be set on
2794 * the BO. In this case, we have a dedicated allocation.
2795 */
2796 if (image->needs_set_tiling) {
2797 const uint32_t i915_tiling =
2798 isl_tiling_to_i915_tiling(image->planes[0].surface.isl.tiling);
2799 int ret = anv_gem_set_tiling(device, mem->bo->gem_handle,
2800 image->planes[0].surface.isl.row_pitch_B,
2801 i915_tiling);
2802 if (ret) {
2803 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2804 return vk_errorf(device->instance, NULL,
2805 VK_ERROR_OUT_OF_DEVICE_MEMORY,
2806 "failed to set BO tiling: %m");
2807 }
2808 }
2809 }
2810
2811 success:
2812 pthread_mutex_lock(&device->mutex);
2813 list_addtail(&mem->link, &device->memory_objects);
2814 pthread_mutex_unlock(&device->mutex);
2815
2816 *pMem = anv_device_memory_to_handle(mem);
2817
2818 return VK_SUCCESS;
2819
2820 fail:
2821 vk_free2(&device->alloc, pAllocator, mem);
2822
2823 return result;
2824 }
2825
2826 VkResult anv_GetMemoryFdKHR(
2827 VkDevice device_h,
2828 const VkMemoryGetFdInfoKHR* pGetFdInfo,
2829 int* pFd)
2830 {
2831 ANV_FROM_HANDLE(anv_device, dev, device_h);
2832 ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
2833
2834 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
2835
2836 assert(pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
2837 pGetFdInfo->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
2838
2839 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
2840 }
2841
2842 VkResult anv_GetMemoryFdPropertiesKHR(
2843 VkDevice _device,
2844 VkExternalMemoryHandleTypeFlagBits handleType,
2845 int fd,
2846 VkMemoryFdPropertiesKHR* pMemoryFdProperties)
2847 {
2848 ANV_FROM_HANDLE(anv_device, device, _device);
2849 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2850
2851 switch (handleType) {
2852 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
2853 /* dma-buf can be imported as any memory type */
2854 pMemoryFdProperties->memoryTypeBits =
2855 (1 << pdevice->memory.type_count) - 1;
2856 return VK_SUCCESS;
2857
2858 default:
2859 /* The valid usage section for this function says:
2860 *
2861 * "handleType must not be one of the handle types defined as
2862 * opaque."
2863 *
2864 * So opaque handle types fall into the default "unsupported" case.
2865 */
2866 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE);
2867 }
2868 }
2869
2870 VkResult anv_GetMemoryHostPointerPropertiesEXT(
2871 VkDevice _device,
2872 VkExternalMemoryHandleTypeFlagBits handleType,
2873 const void* pHostPointer,
2874 VkMemoryHostPointerPropertiesEXT* pMemoryHostPointerProperties)
2875 {
2876 ANV_FROM_HANDLE(anv_device, device, _device);
2877
2878 assert(pMemoryHostPointerProperties->sType ==
2879 VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT);
2880
2881 switch (handleType) {
2882 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT: {
2883 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
2884
2885 /* Host memory can be imported as any memory type. */
2886 pMemoryHostPointerProperties->memoryTypeBits =
2887 (1ull << pdevice->memory.type_count) - 1;
2888
2889 return VK_SUCCESS;
2890 }
2891 default:
2892 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
2893 }
2894 }
2895
2896 void anv_FreeMemory(
2897 VkDevice _device,
2898 VkDeviceMemory _mem,
2899 const VkAllocationCallbacks* pAllocator)
2900 {
2901 ANV_FROM_HANDLE(anv_device, device, _device);
2902 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
2903
2904 if (mem == NULL)
2905 return;
2906
2907 pthread_mutex_lock(&device->mutex);
2908 list_del(&mem->link);
2909 pthread_mutex_unlock(&device->mutex);
2910
2911 if (mem->map)
2912 anv_UnmapMemory(_device, _mem);
2913
2914 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
2915
2916 #if defined(ANDROID) && ANDROID_API_LEVEL >= 26
2917 if (mem->ahw)
2918 AHardwareBuffer_release(mem->ahw);
2919 #endif
2920
2921 vk_free2(&device->alloc, pAllocator, mem);
2922 }
2923
2924 VkResult anv_MapMemory(
2925 VkDevice _device,
2926 VkDeviceMemory _memory,
2927 VkDeviceSize offset,
2928 VkDeviceSize size,
2929 VkMemoryMapFlags flags,
2930 void** ppData)
2931 {
2932 ANV_FROM_HANDLE(anv_device, device, _device);
2933 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2934
2935 if (mem == NULL) {
2936 *ppData = NULL;
2937 return VK_SUCCESS;
2938 }
2939
2940 if (mem->host_ptr) {
2941 *ppData = mem->host_ptr + offset;
2942 return VK_SUCCESS;
2943 }
2944
2945 if (size == VK_WHOLE_SIZE)
2946 size = mem->bo->size - offset;
2947
2948 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
2949 *
2950 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
2951 * assert(size != 0);
2952 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
2953 * equal to the size of the memory minus offset
2954 */
2955 assert(size > 0);
2956 assert(offset + size <= mem->bo->size);
2957
2958 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
2959 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
2960 * at a time is valid. We could just mmap up front and return an offset
2961 * pointer here, but that may exhaust virtual memory on 32 bit
2962 * userspace. */
2963
2964 uint32_t gem_flags = 0;
2965
2966 if (!device->info.has_llc &&
2967 (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
2968 gem_flags |= I915_MMAP_WC;
2969
2970 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
2971 uint64_t map_offset = offset & ~4095ull;
2972 assert(offset >= map_offset);
2973 uint64_t map_size = (offset + size) - map_offset;
2974
2975 /* Let's map whole pages */
2976 map_size = align_u64(map_size, 4096);
2977
2978 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
2979 map_offset, map_size, gem_flags);
2980 if (map == MAP_FAILED)
2981 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
2982
2983 mem->map = map;
2984 mem->map_size = map_size;
2985
2986 *ppData = mem->map + (offset - map_offset);
2987
2988 return VK_SUCCESS;
2989 }
2990
2991 void anv_UnmapMemory(
2992 VkDevice _device,
2993 VkDeviceMemory _memory)
2994 {
2995 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
2996
2997 if (mem == NULL || mem->host_ptr)
2998 return;
2999
3000 anv_gem_munmap(mem->map, mem->map_size);
3001
3002 mem->map = NULL;
3003 mem->map_size = 0;
3004 }
3005
3006 static void
3007 clflush_mapped_ranges(struct anv_device *device,
3008 uint32_t count,
3009 const VkMappedMemoryRange *ranges)
3010 {
3011 for (uint32_t i = 0; i < count; i++) {
3012 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
3013 if (ranges[i].offset >= mem->map_size)
3014 continue;
3015
3016 gen_clflush_range(mem->map + ranges[i].offset,
3017 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
3018 }
3019 }
3020
3021 VkResult anv_FlushMappedMemoryRanges(
3022 VkDevice _device,
3023 uint32_t memoryRangeCount,
3024 const VkMappedMemoryRange* pMemoryRanges)
3025 {
3026 ANV_FROM_HANDLE(anv_device, device, _device);
3027
3028 if (device->info.has_llc)
3029 return VK_SUCCESS;
3030
3031 /* Make sure the writes we're flushing have landed. */
3032 __builtin_ia32_mfence();
3033
3034 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
3035
3036 return VK_SUCCESS;
3037 }
3038
3039 VkResult anv_InvalidateMappedMemoryRanges(
3040 VkDevice _device,
3041 uint32_t memoryRangeCount,
3042 const VkMappedMemoryRange* pMemoryRanges)
3043 {
3044 ANV_FROM_HANDLE(anv_device, device, _device);
3045
3046 if (device->info.has_llc)
3047 return VK_SUCCESS;
3048
3049 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
3050
3051 /* Make sure no reads get moved up above the invalidate. */
3052 __builtin_ia32_mfence();
3053
3054 return VK_SUCCESS;
3055 }
3056
3057 void anv_GetBufferMemoryRequirements(
3058 VkDevice _device,
3059 VkBuffer _buffer,
3060 VkMemoryRequirements* pMemoryRequirements)
3061 {
3062 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3063 ANV_FROM_HANDLE(anv_device, device, _device);
3064 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
3065
3066 /* The Vulkan spec (git aaed022) says:
3067 *
3068 * memoryTypeBits is a bitfield and contains one bit set for every
3069 * supported memory type for the resource. The bit `1<<i` is set if and
3070 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
3071 * structure for the physical device is supported.
3072 */
3073 uint32_t memory_types = 0;
3074 for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
3075 uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
3076 if ((valid_usage & buffer->usage) == buffer->usage)
3077 memory_types |= (1u << i);
3078 }
3079
3080 /* Base alignment requirement of a cache line */
3081 uint32_t alignment = 16;
3082
3083 /* We need an alignment of 32 for pushing UBOs */
3084 if (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)
3085 alignment = MAX2(alignment, 32);
3086
3087 pMemoryRequirements->size = buffer->size;
3088 pMemoryRequirements->alignment = alignment;
3089
3090 /* Storage and Uniform buffers should have their size aligned to
3091 * 32-bits to avoid boundary checks when last DWord is not complete.
3092 * This would ensure that not internal padding would be needed for
3093 * 16-bit types.
3094 */
3095 if (device->robust_buffer_access &&
3096 (buffer->usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ||
3097 buffer->usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT))
3098 pMemoryRequirements->size = align_u64(buffer->size, 4);
3099
3100 pMemoryRequirements->memoryTypeBits = memory_types;
3101 }
3102
3103 void anv_GetBufferMemoryRequirements2(
3104 VkDevice _device,
3105 const VkBufferMemoryRequirementsInfo2* pInfo,
3106 VkMemoryRequirements2* pMemoryRequirements)
3107 {
3108 anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
3109 &pMemoryRequirements->memoryRequirements);
3110
3111 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3112 switch (ext->sType) {
3113 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3114 VkMemoryDedicatedRequirements *requirements = (void *)ext;
3115 requirements->prefersDedicatedAllocation = false;
3116 requirements->requiresDedicatedAllocation = false;
3117 break;
3118 }
3119
3120 default:
3121 anv_debug_ignored_stype(ext->sType);
3122 break;
3123 }
3124 }
3125 }
3126
3127 void anv_GetImageMemoryRequirements(
3128 VkDevice _device,
3129 VkImage _image,
3130 VkMemoryRequirements* pMemoryRequirements)
3131 {
3132 ANV_FROM_HANDLE(anv_image, image, _image);
3133 ANV_FROM_HANDLE(anv_device, device, _device);
3134 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
3135
3136 /* The Vulkan spec (git aaed022) says:
3137 *
3138 * memoryTypeBits is a bitfield and contains one bit set for every
3139 * supported memory type for the resource. The bit `1<<i` is set if and
3140 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
3141 * structure for the physical device is supported.
3142 *
3143 * All types are currently supported for images.
3144 */
3145 uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
3146
3147 /* We must have image allocated or imported at this point. According to the
3148 * specification, external images must have been bound to memory before
3149 * calling GetImageMemoryRequirements.
3150 */
3151 assert(image->size > 0);
3152
3153 pMemoryRequirements->size = image->size;
3154 pMemoryRequirements->alignment = image->alignment;
3155 pMemoryRequirements->memoryTypeBits = memory_types;
3156 }
3157
3158 void anv_GetImageMemoryRequirements2(
3159 VkDevice _device,
3160 const VkImageMemoryRequirementsInfo2* pInfo,
3161 VkMemoryRequirements2* pMemoryRequirements)
3162 {
3163 ANV_FROM_HANDLE(anv_device, device, _device);
3164 ANV_FROM_HANDLE(anv_image, image, pInfo->image);
3165
3166 anv_GetImageMemoryRequirements(_device, pInfo->image,
3167 &pMemoryRequirements->memoryRequirements);
3168
3169 vk_foreach_struct_const(ext, pInfo->pNext) {
3170 switch (ext->sType) {
3171 case VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO: {
3172 struct anv_physical_device *pdevice = &device->instance->physicalDevice;
3173 const VkImagePlaneMemoryRequirementsInfo *plane_reqs =
3174 (const VkImagePlaneMemoryRequirementsInfo *) ext;
3175 uint32_t plane = anv_image_aspect_to_plane(image->aspects,
3176 plane_reqs->planeAspect);
3177
3178 assert(image->planes[plane].offset == 0);
3179
3180 /* The Vulkan spec (git aaed022) says:
3181 *
3182 * memoryTypeBits is a bitfield and contains one bit set for every
3183 * supported memory type for the resource. The bit `1<<i` is set
3184 * if and only if the memory type `i` in the
3185 * VkPhysicalDeviceMemoryProperties structure for the physical
3186 * device is supported.
3187 *
3188 * All types are currently supported for images.
3189 */
3190 pMemoryRequirements->memoryRequirements.memoryTypeBits =
3191 (1ull << pdevice->memory.type_count) - 1;
3192
3193 /* We must have image allocated or imported at this point. According to the
3194 * specification, external images must have been bound to memory before
3195 * calling GetImageMemoryRequirements.
3196 */
3197 assert(image->planes[plane].size > 0);
3198
3199 pMemoryRequirements->memoryRequirements.size = image->planes[plane].size;
3200 pMemoryRequirements->memoryRequirements.alignment =
3201 image->planes[plane].alignment;
3202 break;
3203 }
3204
3205 default:
3206 anv_debug_ignored_stype(ext->sType);
3207 break;
3208 }
3209 }
3210
3211 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3212 switch (ext->sType) {
3213 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3214 VkMemoryDedicatedRequirements *requirements = (void *)ext;
3215 if (image->needs_set_tiling || image->external_format) {
3216 /* If we need to set the tiling for external consumers, we need a
3217 * dedicated allocation.
3218 *
3219 * See also anv_AllocateMemory.
3220 */
3221 requirements->prefersDedicatedAllocation = true;
3222 requirements->requiresDedicatedAllocation = true;
3223 } else {
3224 requirements->prefersDedicatedAllocation = false;
3225 requirements->requiresDedicatedAllocation = false;
3226 }
3227 break;
3228 }
3229
3230 default:
3231 anv_debug_ignored_stype(ext->sType);
3232 break;
3233 }
3234 }
3235 }
3236
3237 void anv_GetImageSparseMemoryRequirements(
3238 VkDevice device,
3239 VkImage image,
3240 uint32_t* pSparseMemoryRequirementCount,
3241 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
3242 {
3243 *pSparseMemoryRequirementCount = 0;
3244 }
3245
3246 void anv_GetImageSparseMemoryRequirements2(
3247 VkDevice device,
3248 const VkImageSparseMemoryRequirementsInfo2* pInfo,
3249 uint32_t* pSparseMemoryRequirementCount,
3250 VkSparseImageMemoryRequirements2* pSparseMemoryRequirements)
3251 {
3252 *pSparseMemoryRequirementCount = 0;
3253 }
3254
3255 void anv_GetDeviceMemoryCommitment(
3256 VkDevice device,
3257 VkDeviceMemory memory,
3258 VkDeviceSize* pCommittedMemoryInBytes)
3259 {
3260 *pCommittedMemoryInBytes = 0;
3261 }
3262
3263 static void
3264 anv_bind_buffer_memory(const VkBindBufferMemoryInfo *pBindInfo)
3265 {
3266 ANV_FROM_HANDLE(anv_device_memory, mem, pBindInfo->memory);
3267 ANV_FROM_HANDLE(anv_buffer, buffer, pBindInfo->buffer);
3268
3269 assert(pBindInfo->sType == VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO);
3270
3271 if (mem) {
3272 assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
3273 buffer->address = (struct anv_address) {
3274 .bo = mem->bo,
3275 .offset = pBindInfo->memoryOffset,
3276 };
3277 } else {
3278 buffer->address = ANV_NULL_ADDRESS;
3279 }
3280 }
3281
3282 VkResult anv_BindBufferMemory(
3283 VkDevice device,
3284 VkBuffer buffer,
3285 VkDeviceMemory memory,
3286 VkDeviceSize memoryOffset)
3287 {
3288 anv_bind_buffer_memory(
3289 &(VkBindBufferMemoryInfo) {
3290 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
3291 .buffer = buffer,
3292 .memory = memory,
3293 .memoryOffset = memoryOffset,
3294 });
3295
3296 return VK_SUCCESS;
3297 }
3298
3299 VkResult anv_BindBufferMemory2(
3300 VkDevice device,
3301 uint32_t bindInfoCount,
3302 const VkBindBufferMemoryInfo* pBindInfos)
3303 {
3304 for (uint32_t i = 0; i < bindInfoCount; i++)
3305 anv_bind_buffer_memory(&pBindInfos[i]);
3306
3307 return VK_SUCCESS;
3308 }
3309
3310 VkResult anv_QueueBindSparse(
3311 VkQueue _queue,
3312 uint32_t bindInfoCount,
3313 const VkBindSparseInfo* pBindInfo,
3314 VkFence fence)
3315 {
3316 ANV_FROM_HANDLE(anv_queue, queue, _queue);
3317 if (anv_device_is_lost(queue->device))
3318 return VK_ERROR_DEVICE_LOST;
3319
3320 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
3321 }
3322
3323 // Event functions
3324
3325 VkResult anv_CreateEvent(
3326 VkDevice _device,
3327 const VkEventCreateInfo* pCreateInfo,
3328 const VkAllocationCallbacks* pAllocator,
3329 VkEvent* pEvent)
3330 {
3331 ANV_FROM_HANDLE(anv_device, device, _device);
3332 struct anv_state state;
3333 struct anv_event *event;
3334
3335 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
3336
3337 state = anv_state_pool_alloc(&device->dynamic_state_pool,
3338 sizeof(*event), 8);
3339 event = state.map;
3340 event->state = state;
3341 event->semaphore = VK_EVENT_RESET;
3342
3343 if (!device->info.has_llc) {
3344 /* Make sure the writes we're flushing have landed. */
3345 __builtin_ia32_mfence();
3346 __builtin_ia32_clflush(event);
3347 }
3348
3349 *pEvent = anv_event_to_handle(event);
3350
3351 return VK_SUCCESS;
3352 }
3353
3354 void anv_DestroyEvent(
3355 VkDevice _device,
3356 VkEvent _event,
3357 const VkAllocationCallbacks* pAllocator)
3358 {
3359 ANV_FROM_HANDLE(anv_device, device, _device);
3360 ANV_FROM_HANDLE(anv_event, event, _event);
3361
3362 if (!event)
3363 return;
3364
3365 anv_state_pool_free(&device->dynamic_state_pool, event->state);
3366 }
3367
3368 VkResult anv_GetEventStatus(
3369 VkDevice _device,
3370 VkEvent _event)
3371 {
3372 ANV_FROM_HANDLE(anv_device, device, _device);
3373 ANV_FROM_HANDLE(anv_event, event, _event);
3374
3375 if (anv_device_is_lost(device))
3376 return VK_ERROR_DEVICE_LOST;
3377
3378 if (!device->info.has_llc) {
3379 /* Invalidate read cache before reading event written by GPU. */
3380 __builtin_ia32_clflush(event);
3381 __builtin_ia32_mfence();
3382
3383 }
3384
3385 return event->semaphore;
3386 }
3387
3388 VkResult anv_SetEvent(
3389 VkDevice _device,
3390 VkEvent _event)
3391 {
3392 ANV_FROM_HANDLE(anv_device, device, _device);
3393 ANV_FROM_HANDLE(anv_event, event, _event);
3394
3395 event->semaphore = VK_EVENT_SET;
3396
3397 if (!device->info.has_llc) {
3398 /* Make sure the writes we're flushing have landed. */
3399 __builtin_ia32_mfence();
3400 __builtin_ia32_clflush(event);
3401 }
3402
3403 return VK_SUCCESS;
3404 }
3405
3406 VkResult anv_ResetEvent(
3407 VkDevice _device,
3408 VkEvent _event)
3409 {
3410 ANV_FROM_HANDLE(anv_device, device, _device);
3411 ANV_FROM_HANDLE(anv_event, event, _event);
3412
3413 event->semaphore = VK_EVENT_RESET;
3414
3415 if (!device->info.has_llc) {
3416 /* Make sure the writes we're flushing have landed. */
3417 __builtin_ia32_mfence();
3418 __builtin_ia32_clflush(event);
3419 }
3420
3421 return VK_SUCCESS;
3422 }
3423
3424 // Buffer functions
3425
3426 VkResult anv_CreateBuffer(
3427 VkDevice _device,
3428 const VkBufferCreateInfo* pCreateInfo,
3429 const VkAllocationCallbacks* pAllocator,
3430 VkBuffer* pBuffer)
3431 {
3432 ANV_FROM_HANDLE(anv_device, device, _device);
3433 struct anv_buffer *buffer;
3434
3435 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
3436
3437 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
3438 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3439 if (buffer == NULL)
3440 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3441
3442 buffer->size = pCreateInfo->size;
3443 buffer->usage = pCreateInfo->usage;
3444 buffer->address = ANV_NULL_ADDRESS;
3445
3446 *pBuffer = anv_buffer_to_handle(buffer);
3447
3448 return VK_SUCCESS;
3449 }
3450
3451 void anv_DestroyBuffer(
3452 VkDevice _device,
3453 VkBuffer _buffer,
3454 const VkAllocationCallbacks* pAllocator)
3455 {
3456 ANV_FROM_HANDLE(anv_device, device, _device);
3457 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
3458
3459 if (!buffer)
3460 return;
3461
3462 vk_free2(&device->alloc, pAllocator, buffer);
3463 }
3464
3465 VkDeviceAddress anv_GetBufferDeviceAddressEXT(
3466 VkDevice device,
3467 const VkBufferDeviceAddressInfoEXT* pInfo)
3468 {
3469 ANV_FROM_HANDLE(anv_buffer, buffer, pInfo->buffer);
3470
3471 assert(buffer->address.bo->flags & EXEC_OBJECT_PINNED);
3472
3473 return anv_address_physical(buffer->address);
3474 }
3475
3476 void
3477 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
3478 enum isl_format format,
3479 struct anv_address address,
3480 uint32_t range, uint32_t stride)
3481 {
3482 isl_buffer_fill_state(&device->isl_dev, state.map,
3483 .address = anv_address_physical(address),
3484 .mocs = device->default_mocs,
3485 .size_B = range,
3486 .format = format,
3487 .swizzle = ISL_SWIZZLE_IDENTITY,
3488 .stride_B = stride);
3489 }
3490
3491 void anv_DestroySampler(
3492 VkDevice _device,
3493 VkSampler _sampler,
3494 const VkAllocationCallbacks* pAllocator)
3495 {
3496 ANV_FROM_HANDLE(anv_device, device, _device);
3497 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
3498
3499 if (!sampler)
3500 return;
3501
3502 if (sampler->bindless_state.map) {
3503 anv_state_pool_free(&device->dynamic_state_pool,
3504 sampler->bindless_state);
3505 }
3506
3507 vk_free2(&device->alloc, pAllocator, sampler);
3508 }
3509
3510 VkResult anv_CreateFramebuffer(
3511 VkDevice _device,
3512 const VkFramebufferCreateInfo* pCreateInfo,
3513 const VkAllocationCallbacks* pAllocator,
3514 VkFramebuffer* pFramebuffer)
3515 {
3516 ANV_FROM_HANDLE(anv_device, device, _device);
3517 struct anv_framebuffer *framebuffer;
3518
3519 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
3520
3521 size_t size = sizeof(*framebuffer) +
3522 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
3523 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
3524 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3525 if (framebuffer == NULL)
3526 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3527
3528 framebuffer->attachment_count = pCreateInfo->attachmentCount;
3529 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
3530 VkImageView _iview = pCreateInfo->pAttachments[i];
3531 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
3532 }
3533
3534 framebuffer->width = pCreateInfo->width;
3535 framebuffer->height = pCreateInfo->height;
3536 framebuffer->layers = pCreateInfo->layers;
3537
3538 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
3539
3540 return VK_SUCCESS;
3541 }
3542
3543 void anv_DestroyFramebuffer(
3544 VkDevice _device,
3545 VkFramebuffer _fb,
3546 const VkAllocationCallbacks* pAllocator)
3547 {
3548 ANV_FROM_HANDLE(anv_device, device, _device);
3549 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
3550
3551 if (!fb)
3552 return;
3553
3554 vk_free2(&device->alloc, pAllocator, fb);
3555 }
3556
3557 static const VkTimeDomainEXT anv_time_domains[] = {
3558 VK_TIME_DOMAIN_DEVICE_EXT,
3559 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
3560 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
3561 };
3562
3563 VkResult anv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
3564 VkPhysicalDevice physicalDevice,
3565 uint32_t *pTimeDomainCount,
3566 VkTimeDomainEXT *pTimeDomains)
3567 {
3568 int d;
3569 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
3570
3571 for (d = 0; d < ARRAY_SIZE(anv_time_domains); d++) {
3572 vk_outarray_append(&out, i) {
3573 *i = anv_time_domains[d];
3574 }
3575 }
3576
3577 return vk_outarray_status(&out);
3578 }
3579
3580 static uint64_t
3581 anv_clock_gettime(clockid_t clock_id)
3582 {
3583 struct timespec current;
3584 int ret;
3585
3586 ret = clock_gettime(clock_id, &current);
3587 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
3588 ret = clock_gettime(CLOCK_MONOTONIC, &current);
3589 if (ret < 0)
3590 return 0;
3591
3592 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
3593 }
3594
3595 #define TIMESTAMP 0x2358
3596
3597 VkResult anv_GetCalibratedTimestampsEXT(
3598 VkDevice _device,
3599 uint32_t timestampCount,
3600 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
3601 uint64_t *pTimestamps,
3602 uint64_t *pMaxDeviation)
3603 {
3604 ANV_FROM_HANDLE(anv_device, device, _device);
3605 uint64_t timestamp_frequency = device->info.timestamp_frequency;
3606 int ret;
3607 int d;
3608 uint64_t begin, end;
3609 uint64_t max_clock_period = 0;
3610
3611 begin = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
3612
3613 for (d = 0; d < timestampCount; d++) {
3614 switch (pTimestampInfos[d].timeDomain) {
3615 case VK_TIME_DOMAIN_DEVICE_EXT:
3616 ret = anv_gem_reg_read(device, TIMESTAMP | 1,
3617 &pTimestamps[d]);
3618
3619 if (ret != 0) {
3620 return anv_device_set_lost(device, "Failed to read the TIMESTAMP "
3621 "register: %m");
3622 }
3623 uint64_t device_period = DIV_ROUND_UP(1000000000, timestamp_frequency);
3624 max_clock_period = MAX2(max_clock_period, device_period);
3625 break;
3626 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
3627 pTimestamps[d] = anv_clock_gettime(CLOCK_MONOTONIC);
3628 max_clock_period = MAX2(max_clock_period, 1);
3629 break;
3630
3631 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
3632 pTimestamps[d] = begin;
3633 break;
3634 default:
3635 pTimestamps[d] = 0;
3636 break;
3637 }
3638 }
3639
3640 end = anv_clock_gettime(CLOCK_MONOTONIC_RAW);
3641
3642 /*
3643 * The maximum deviation is the sum of the interval over which we
3644 * perform the sampling and the maximum period of any sampled
3645 * clock. That's because the maximum skew between any two sampled
3646 * clock edges is when the sampled clock with the largest period is
3647 * sampled at the end of that period but right at the beginning of the
3648 * sampling interval and some other clock is sampled right at the
3649 * begining of its sampling period and right at the end of the
3650 * sampling interval. Let's assume the GPU has the longest clock
3651 * period and that the application is sampling GPU and monotonic:
3652 *
3653 * s e
3654 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
3655 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
3656 *
3657 * g
3658 * 0 1 2 3
3659 * GPU -----_____-----_____-----_____-----_____
3660 *
3661 * m
3662 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
3663 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
3664 *
3665 * Interval <----------------->
3666 * Deviation <-------------------------->
3667 *
3668 * s = read(raw) 2
3669 * g = read(GPU) 1
3670 * m = read(monotonic) 2
3671 * e = read(raw) b
3672 *
3673 * We round the sample interval up by one tick to cover sampling error
3674 * in the interval clock
3675 */
3676
3677 uint64_t sample_interval = end - begin + 1;
3678
3679 *pMaxDeviation = sample_interval + max_clock_period;
3680
3681 return VK_SUCCESS;
3682 }
3683
3684 /* vk_icd.h does not declare this function, so we declare it here to
3685 * suppress Wmissing-prototypes.
3686 */
3687 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
3688 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
3689
3690 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
3691 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
3692 {
3693 /* For the full details on loader interface versioning, see
3694 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
3695 * What follows is a condensed summary, to help you navigate the large and
3696 * confusing official doc.
3697 *
3698 * - Loader interface v0 is incompatible with later versions. We don't
3699 * support it.
3700 *
3701 * - In loader interface v1:
3702 * - The first ICD entrypoint called by the loader is
3703 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
3704 * entrypoint.
3705 * - The ICD must statically expose no other Vulkan symbol unless it is
3706 * linked with -Bsymbolic.
3707 * - Each dispatchable Vulkan handle created by the ICD must be
3708 * a pointer to a struct whose first member is VK_LOADER_DATA. The
3709 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
3710 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
3711 * vkDestroySurfaceKHR(). The ICD must be capable of working with
3712 * such loader-managed surfaces.
3713 *
3714 * - Loader interface v2 differs from v1 in:
3715 * - The first ICD entrypoint called by the loader is
3716 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
3717 * statically expose this entrypoint.
3718 *
3719 * - Loader interface v3 differs from v2 in:
3720 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
3721 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
3722 * because the loader no longer does so.
3723 */
3724 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
3725 return VK_SUCCESS;
3726 }