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