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