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