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