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