62974f19d806509ab906d2e0c9028853b7166b90
[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
33 #include "anv_private.h"
34 #include "util/strtod.h"
35 #include "util/debug.h"
36 #include "util/build_id.h"
37 #include "util/mesa-sha1.h"
38 #include "util/vk_util.h"
39
40 #include "genxml/gen7_pack.h"
41
42 static void
43 compiler_debug_log(void *data, const char *fmt, ...)
44 { }
45
46 static void
47 compiler_perf_log(void *data, const char *fmt, ...)
48 {
49 va_list args;
50 va_start(args, fmt);
51
52 if (unlikely(INTEL_DEBUG & DEBUG_PERF))
53 vfprintf(stderr, fmt, args);
54
55 va_end(args);
56 }
57
58 static VkResult
59 anv_compute_heap_size(int fd, uint64_t *heap_size)
60 {
61 uint64_t gtt_size;
62 if (anv_gem_get_context_param(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE,
63 &gtt_size) == -1) {
64 /* If, for whatever reason, we can't actually get the GTT size from the
65 * kernel (too old?) fall back to the aperture size.
66 */
67 anv_perf_warn("Failed to get I915_CONTEXT_PARAM_GTT_SIZE: %m");
68
69 if (anv_gem_get_aperture(fd, &gtt_size) == -1) {
70 return vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
71 "failed to get aperture size: %m");
72 }
73 }
74
75 /* Query the total ram from the system */
76 struct sysinfo info;
77 sysinfo(&info);
78
79 uint64_t total_ram = (uint64_t)info.totalram * (uint64_t)info.mem_unit;
80
81 /* We don't want to burn too much ram with the GPU. If the user has 4GiB
82 * or less, we use at most half. If they have more than 4GiB, we use 3/4.
83 */
84 uint64_t available_ram;
85 if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
86 available_ram = total_ram / 2;
87 else
88 available_ram = total_ram * 3 / 4;
89
90 /* We also want to leave some padding for things we allocate in the driver,
91 * so don't go over 3/4 of the GTT either.
92 */
93 uint64_t available_gtt = gtt_size * 3 / 4;
94
95 *heap_size = MIN2(available_ram, available_gtt);
96
97 return VK_SUCCESS;
98 }
99
100 static VkResult
101 anv_physical_device_init_uuids(struct anv_physical_device *device)
102 {
103 const struct build_id_note *note = build_id_find_nhdr("libvulkan_intel.so");
104 if (!note) {
105 return vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
106 "Failed to find build-id");
107 }
108
109 unsigned build_id_len = build_id_length(note);
110 if (build_id_len < 20) {
111 return vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
112 "build-id too short. It needs to be a SHA");
113 }
114
115 struct mesa_sha1 sha1_ctx;
116 uint8_t sha1[20];
117 STATIC_ASSERT(VK_UUID_SIZE <= sizeof(sha1));
118
119 /* The pipeline cache UUID is used for determining when a pipeline cache is
120 * invalid. It needs both a driver build and the PCI ID of the device.
121 */
122 _mesa_sha1_init(&sha1_ctx);
123 _mesa_sha1_update(&sha1_ctx, build_id_data(note), build_id_len);
124 _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
125 sizeof(device->chipset_id));
126 _mesa_sha1_final(&sha1_ctx, sha1);
127 memcpy(device->pipeline_cache_uuid, sha1, VK_UUID_SIZE);
128
129 /* The driver UUID is used for determining sharability of images and memory
130 * between two Vulkan instances in separate processes. People who want to
131 * share memory need to also check the device UUID (below) so all this
132 * needs to be is the build-id.
133 */
134 memcpy(device->driver_uuid, build_id_data(note), VK_UUID_SIZE);
135
136 /* The device UUID uniquely identifies the given device within the machine.
137 * Since we never have more than one device, this doesn't need to be a real
138 * UUID. However, on the off-chance that someone tries to use this to
139 * cache pre-tiled images or something of the like, we use the PCI ID and
140 * some bits of ISL info to ensure that this is safe.
141 */
142 _mesa_sha1_init(&sha1_ctx);
143 _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
144 sizeof(device->chipset_id));
145 _mesa_sha1_update(&sha1_ctx, &device->isl_dev.has_bit6_swizzling,
146 sizeof(device->isl_dev.has_bit6_swizzling));
147 _mesa_sha1_final(&sha1_ctx, sha1);
148 memcpy(device->device_uuid, sha1, VK_UUID_SIZE);
149
150 return VK_SUCCESS;
151 }
152
153 static VkResult
154 anv_physical_device_init(struct anv_physical_device *device,
155 struct anv_instance *instance,
156 const char *path)
157 {
158 VkResult result;
159 int fd;
160
161 fd = open(path, O_RDWR | O_CLOEXEC);
162 if (fd < 0)
163 return vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
164
165 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
166 device->instance = instance;
167
168 assert(strlen(path) < ARRAY_SIZE(device->path));
169 strncpy(device->path, path, ARRAY_SIZE(device->path));
170
171 device->chipset_id = anv_gem_get_param(fd, I915_PARAM_CHIPSET_ID);
172 if (!device->chipset_id) {
173 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
174 goto fail;
175 }
176
177 device->name = gen_get_device_name(device->chipset_id);
178 if (!gen_get_device_info(device->chipset_id, &device->info)) {
179 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
180 goto fail;
181 }
182
183 if (device->info.is_haswell) {
184 fprintf(stderr, "WARNING: Haswell Vulkan support is incomplete\n");
185 } else if (device->info.gen == 7 && !device->info.is_baytrail) {
186 fprintf(stderr, "WARNING: Ivy Bridge Vulkan support is incomplete\n");
187 } else if (device->info.gen == 7 && device->info.is_baytrail) {
188 fprintf(stderr, "WARNING: Bay Trail Vulkan support is incomplete\n");
189 } else if (device->info.gen >= 8) {
190 /* Broadwell, Cherryview, Skylake, Broxton, Kabylake is as fully
191 * supported as anything */
192 } else {
193 result = vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
194 "Vulkan not yet supported on %s", device->name);
195 goto fail;
196 }
197
198 device->cmd_parser_version = -1;
199 if (device->info.gen == 7) {
200 device->cmd_parser_version =
201 anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
202 if (device->cmd_parser_version == -1) {
203 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
204 "failed to get command parser version");
205 goto fail;
206 }
207 }
208
209 if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
210 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
211 "kernel missing gem wait");
212 goto fail;
213 }
214
215 if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
216 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
217 "kernel missing execbuf2");
218 goto fail;
219 }
220
221 if (!device->info.has_llc &&
222 anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
223 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
224 "kernel missing wc mmap");
225 goto fail;
226 }
227
228 device->supports_48bit_addresses = anv_gem_supports_48b_addresses(fd);
229
230 result = anv_compute_heap_size(fd, &device->heap_size);
231 if (result != VK_SUCCESS)
232 goto fail;
233
234 device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
235
236 bool swizzled = anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
237
238 /* GENs prior to 8 do not support EU/Subslice info */
239 if (device->info.gen >= 8) {
240 device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
241 device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
242
243 /* Without this information, we cannot get the right Braswell
244 * brandstrings, and we have to use conservative numbers for GPGPU on
245 * many platforms, but otherwise, things will just work.
246 */
247 if (device->subslice_total < 1 || device->eu_total < 1) {
248 fprintf(stderr, "WARNING: Kernel 4.1 required to properly"
249 " query GPU properties.\n");
250 }
251 } else if (device->info.gen == 7) {
252 device->subslice_total = 1 << (device->info.gt - 1);
253 }
254
255 if (device->info.is_cherryview &&
256 device->subslice_total > 0 && device->eu_total > 0) {
257 /* Logical CS threads = EUs per subslice * 7 threads per EU */
258 uint32_t max_cs_threads = device->eu_total / device->subslice_total * 7;
259
260 /* Fuse configurations may give more threads than expected, never less. */
261 if (max_cs_threads > device->info.max_cs_threads)
262 device->info.max_cs_threads = max_cs_threads;
263 }
264
265 brw_process_intel_debug_variable();
266
267 device->compiler = brw_compiler_create(NULL, &device->info);
268 if (device->compiler == NULL) {
269 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
270 goto fail;
271 }
272 device->compiler->shader_debug_log = compiler_debug_log;
273 device->compiler->shader_perf_log = compiler_perf_log;
274
275 isl_device_init(&device->isl_dev, &device->info, swizzled);
276
277 result = anv_physical_device_init_uuids(device);
278 if (result != VK_SUCCESS)
279 goto fail;
280
281 result = anv_init_wsi(device);
282 if (result != VK_SUCCESS) {
283 ralloc_free(device->compiler);
284 goto fail;
285 }
286
287 device->local_fd = fd;
288 return VK_SUCCESS;
289
290 fail:
291 close(fd);
292 return result;
293 }
294
295 static void
296 anv_physical_device_finish(struct anv_physical_device *device)
297 {
298 anv_finish_wsi(device);
299 ralloc_free(device->compiler);
300 close(device->local_fd);
301 }
302
303 static const VkExtensionProperties global_extensions[] = {
304 {
305 .extensionName = VK_KHR_SURFACE_EXTENSION_NAME,
306 .specVersion = 25,
307 },
308 #ifdef VK_USE_PLATFORM_XCB_KHR
309 {
310 .extensionName = VK_KHR_XCB_SURFACE_EXTENSION_NAME,
311 .specVersion = 6,
312 },
313 #endif
314 #ifdef VK_USE_PLATFORM_XLIB_KHR
315 {
316 .extensionName = VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
317 .specVersion = 6,
318 },
319 #endif
320 #ifdef VK_USE_PLATFORM_WAYLAND_KHR
321 {
322 .extensionName = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME,
323 .specVersion = 5,
324 },
325 #endif
326 {
327 .extensionName = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
328 .specVersion = 1,
329 },
330 {
331 .extensionName = VK_KHX_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME,
332 .specVersion = 1,
333 },
334 };
335
336 static const VkExtensionProperties device_extensions[] = {
337 {
338 .extensionName = VK_KHR_SWAPCHAIN_EXTENSION_NAME,
339 .specVersion = 68,
340 },
341 {
342 .extensionName = VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME,
343 .specVersion = 1,
344 },
345 {
346 .extensionName = VK_KHR_MAINTENANCE1_EXTENSION_NAME,
347 .specVersion = 1,
348 },
349 {
350 .extensionName = VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME,
351 .specVersion = 1,
352 },
353 {
354 .extensionName = VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME,
355 .specVersion = 1,
356 },
357 {
358 .extensionName = VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME,
359 .specVersion = 1,
360 },
361 {
362 .extensionName = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME,
363 .specVersion = 1,
364 },
365 {
366 .extensionName = VK_KHX_EXTERNAL_MEMORY_EXTENSION_NAME,
367 .specVersion = 1,
368 },
369 {
370 .extensionName = VK_KHX_EXTERNAL_MEMORY_FD_EXTENSION_NAME,
371 .specVersion = 1,
372 },
373 };
374
375 static void *
376 default_alloc_func(void *pUserData, size_t size, size_t align,
377 VkSystemAllocationScope allocationScope)
378 {
379 return malloc(size);
380 }
381
382 static void *
383 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
384 size_t align, VkSystemAllocationScope allocationScope)
385 {
386 return realloc(pOriginal, size);
387 }
388
389 static void
390 default_free_func(void *pUserData, void *pMemory)
391 {
392 free(pMemory);
393 }
394
395 static const VkAllocationCallbacks default_alloc = {
396 .pUserData = NULL,
397 .pfnAllocation = default_alloc_func,
398 .pfnReallocation = default_realloc_func,
399 .pfnFree = default_free_func,
400 };
401
402 VkResult anv_CreateInstance(
403 const VkInstanceCreateInfo* pCreateInfo,
404 const VkAllocationCallbacks* pAllocator,
405 VkInstance* pInstance)
406 {
407 struct anv_instance *instance;
408
409 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
410
411 uint32_t client_version;
412 if (pCreateInfo->pApplicationInfo &&
413 pCreateInfo->pApplicationInfo->apiVersion != 0) {
414 client_version = pCreateInfo->pApplicationInfo->apiVersion;
415 } else {
416 client_version = VK_MAKE_VERSION(1, 0, 0);
417 }
418
419 if (VK_MAKE_VERSION(1, 0, 0) > client_version ||
420 client_version > VK_MAKE_VERSION(1, 0, 0xfff)) {
421 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
422 "Client requested version %d.%d.%d",
423 VK_VERSION_MAJOR(client_version),
424 VK_VERSION_MINOR(client_version),
425 VK_VERSION_PATCH(client_version));
426 }
427
428 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
429 bool found = false;
430 for (uint32_t j = 0; j < ARRAY_SIZE(global_extensions); j++) {
431 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
432 global_extensions[j].extensionName) == 0) {
433 found = true;
434 break;
435 }
436 }
437 if (!found)
438 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
439 }
440
441 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
442 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
443 if (!instance)
444 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
445
446 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
447
448 if (pAllocator)
449 instance->alloc = *pAllocator;
450 else
451 instance->alloc = default_alloc;
452
453 instance->apiVersion = client_version;
454 instance->physicalDeviceCount = -1;
455
456 _mesa_locale_init();
457
458 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
459
460 *pInstance = anv_instance_to_handle(instance);
461
462 return VK_SUCCESS;
463 }
464
465 void anv_DestroyInstance(
466 VkInstance _instance,
467 const VkAllocationCallbacks* pAllocator)
468 {
469 ANV_FROM_HANDLE(anv_instance, instance, _instance);
470
471 if (!instance)
472 return;
473
474 if (instance->physicalDeviceCount > 0) {
475 /* We support at most one physical device. */
476 assert(instance->physicalDeviceCount == 1);
477 anv_physical_device_finish(&instance->physicalDevice);
478 }
479
480 VG(VALGRIND_DESTROY_MEMPOOL(instance));
481
482 _mesa_locale_fini();
483
484 vk_free(&instance->alloc, instance);
485 }
486
487 static VkResult
488 anv_enumerate_devices(struct anv_instance *instance)
489 {
490 /* TODO: Check for more devices ? */
491 drmDevicePtr devices[8];
492 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
493 int max_devices;
494
495 instance->physicalDeviceCount = 0;
496
497 max_devices = drmGetDevices2(0, devices, sizeof(devices));
498 if (max_devices < 1)
499 return VK_ERROR_INCOMPATIBLE_DRIVER;
500
501 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
502 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
503 devices[i]->bustype == DRM_BUS_PCI &&
504 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
505
506 result = anv_physical_device_init(&instance->physicalDevice,
507 instance,
508 devices[i]->nodes[DRM_NODE_RENDER]);
509 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
510 break;
511 }
512 }
513
514 if (result == VK_SUCCESS)
515 instance->physicalDeviceCount = 1;
516
517 return result;
518 }
519
520
521 VkResult anv_EnumeratePhysicalDevices(
522 VkInstance _instance,
523 uint32_t* pPhysicalDeviceCount,
524 VkPhysicalDevice* pPhysicalDevices)
525 {
526 ANV_FROM_HANDLE(anv_instance, instance, _instance);
527 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
528 VkResult result;
529
530 if (instance->physicalDeviceCount < 0) {
531 result = anv_enumerate_devices(instance);
532 if (result != VK_SUCCESS &&
533 result != VK_ERROR_INCOMPATIBLE_DRIVER)
534 return result;
535 }
536
537 if (instance->physicalDeviceCount > 0) {
538 assert(instance->physicalDeviceCount == 1);
539 vk_outarray_append(&out, i) {
540 *i = anv_physical_device_to_handle(&instance->physicalDevice);
541 }
542 }
543
544 return vk_outarray_status(&out);
545 }
546
547 void anv_GetPhysicalDeviceFeatures(
548 VkPhysicalDevice physicalDevice,
549 VkPhysicalDeviceFeatures* pFeatures)
550 {
551 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
552
553 *pFeatures = (VkPhysicalDeviceFeatures) {
554 .robustBufferAccess = true,
555 .fullDrawIndexUint32 = true,
556 .imageCubeArray = true,
557 .independentBlend = true,
558 .geometryShader = true,
559 .tessellationShader = true,
560 .sampleRateShading = true,
561 .dualSrcBlend = true,
562 .logicOp = true,
563 .multiDrawIndirect = false,
564 .drawIndirectFirstInstance = true,
565 .depthClamp = true,
566 .depthBiasClamp = true,
567 .fillModeNonSolid = true,
568 .depthBounds = false,
569 .wideLines = true,
570 .largePoints = true,
571 .alphaToOne = true,
572 .multiViewport = true,
573 .samplerAnisotropy = true,
574 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
575 pdevice->info.is_baytrail,
576 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
577 .textureCompressionBC = true,
578 .occlusionQueryPrecise = true,
579 .pipelineStatisticsQuery = true,
580 .fragmentStoresAndAtomics = true,
581 .shaderTessellationAndGeometryPointSize = true,
582 .shaderImageGatherExtended = true,
583 .shaderStorageImageExtendedFormats = true,
584 .shaderStorageImageMultisample = false,
585 .shaderStorageImageReadWithoutFormat = false,
586 .shaderStorageImageWriteWithoutFormat = true,
587 .shaderUniformBufferArrayDynamicIndexing = true,
588 .shaderSampledImageArrayDynamicIndexing = true,
589 .shaderStorageBufferArrayDynamicIndexing = true,
590 .shaderStorageImageArrayDynamicIndexing = true,
591 .shaderClipDistance = true,
592 .shaderCullDistance = true,
593 .shaderFloat64 = pdevice->info.gen >= 8,
594 .shaderInt64 = pdevice->info.gen >= 8,
595 .shaderInt16 = false,
596 .shaderResourceMinLod = false,
597 .variableMultisampleRate = false,
598 .inheritedQueries = true,
599 };
600
601 /* We can't do image stores in vec4 shaders */
602 pFeatures->vertexPipelineStoresAndAtomics =
603 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
604 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
605 }
606
607 void anv_GetPhysicalDeviceFeatures2KHR(
608 VkPhysicalDevice physicalDevice,
609 VkPhysicalDeviceFeatures2KHR* pFeatures)
610 {
611 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
612
613 vk_foreach_struct(ext, pFeatures->pNext) {
614 switch (ext->sType) {
615 default:
616 anv_debug_ignored_stype(ext->sType);
617 break;
618 }
619 }
620 }
621
622 void anv_GetPhysicalDeviceProperties(
623 VkPhysicalDevice physicalDevice,
624 VkPhysicalDeviceProperties* pProperties)
625 {
626 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
627 const struct gen_device_info *devinfo = &pdevice->info;
628
629 /* See assertions made when programming the buffer surface state. */
630 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
631 (1ul << 30) : (1ul << 27);
632
633 VkSampleCountFlags sample_counts =
634 isl_device_get_sample_counts(&pdevice->isl_dev);
635
636 VkPhysicalDeviceLimits limits = {
637 .maxImageDimension1D = (1 << 14),
638 .maxImageDimension2D = (1 << 14),
639 .maxImageDimension3D = (1 << 11),
640 .maxImageDimensionCube = (1 << 14),
641 .maxImageArrayLayers = (1 << 11),
642 .maxTexelBufferElements = 128 * 1024 * 1024,
643 .maxUniformBufferRange = (1ul << 27),
644 .maxStorageBufferRange = max_raw_buffer_sz,
645 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
646 .maxMemoryAllocationCount = UINT32_MAX,
647 .maxSamplerAllocationCount = 64 * 1024,
648 .bufferImageGranularity = 64, /* A cache line */
649 .sparseAddressSpaceSize = 0,
650 .maxBoundDescriptorSets = MAX_SETS,
651 .maxPerStageDescriptorSamplers = 64,
652 .maxPerStageDescriptorUniformBuffers = 64,
653 .maxPerStageDescriptorStorageBuffers = 64,
654 .maxPerStageDescriptorSampledImages = 64,
655 .maxPerStageDescriptorStorageImages = 64,
656 .maxPerStageDescriptorInputAttachments = 64,
657 .maxPerStageResources = 128,
658 .maxDescriptorSetSamplers = 256,
659 .maxDescriptorSetUniformBuffers = 256,
660 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
661 .maxDescriptorSetStorageBuffers = 256,
662 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
663 .maxDescriptorSetSampledImages = 256,
664 .maxDescriptorSetStorageImages = 256,
665 .maxDescriptorSetInputAttachments = 256,
666 .maxVertexInputAttributes = MAX_VBS,
667 .maxVertexInputBindings = MAX_VBS,
668 .maxVertexInputAttributeOffset = 2047,
669 .maxVertexInputBindingStride = 2048,
670 .maxVertexOutputComponents = 128,
671 .maxTessellationGenerationLevel = 64,
672 .maxTessellationPatchSize = 32,
673 .maxTessellationControlPerVertexInputComponents = 128,
674 .maxTessellationControlPerVertexOutputComponents = 128,
675 .maxTessellationControlPerPatchOutputComponents = 128,
676 .maxTessellationControlTotalOutputComponents = 2048,
677 .maxTessellationEvaluationInputComponents = 128,
678 .maxTessellationEvaluationOutputComponents = 128,
679 .maxGeometryShaderInvocations = 32,
680 .maxGeometryInputComponents = 64,
681 .maxGeometryOutputComponents = 128,
682 .maxGeometryOutputVertices = 256,
683 .maxGeometryTotalOutputComponents = 1024,
684 .maxFragmentInputComponents = 128,
685 .maxFragmentOutputAttachments = 8,
686 .maxFragmentDualSrcAttachments = 1,
687 .maxFragmentCombinedOutputResources = 8,
688 .maxComputeSharedMemorySize = 32768,
689 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
690 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
691 .maxComputeWorkGroupSize = {
692 16 * devinfo->max_cs_threads,
693 16 * devinfo->max_cs_threads,
694 16 * devinfo->max_cs_threads,
695 },
696 .subPixelPrecisionBits = 4 /* FIXME */,
697 .subTexelPrecisionBits = 4 /* FIXME */,
698 .mipmapPrecisionBits = 4 /* FIXME */,
699 .maxDrawIndexedIndexValue = UINT32_MAX,
700 .maxDrawIndirectCount = UINT32_MAX,
701 .maxSamplerLodBias = 16,
702 .maxSamplerAnisotropy = 16,
703 .maxViewports = MAX_VIEWPORTS,
704 .maxViewportDimensions = { (1 << 14), (1 << 14) },
705 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
706 .viewportSubPixelBits = 13, /* We take a float? */
707 .minMemoryMapAlignment = 4096, /* A page */
708 .minTexelBufferOffsetAlignment = 1,
709 .minUniformBufferOffsetAlignment = 16,
710 .minStorageBufferOffsetAlignment = 4,
711 .minTexelOffset = -8,
712 .maxTexelOffset = 7,
713 .minTexelGatherOffset = -32,
714 .maxTexelGatherOffset = 31,
715 .minInterpolationOffset = -0.5,
716 .maxInterpolationOffset = 0.4375,
717 .subPixelInterpolationOffsetBits = 4,
718 .maxFramebufferWidth = (1 << 14),
719 .maxFramebufferHeight = (1 << 14),
720 .maxFramebufferLayers = (1 << 11),
721 .framebufferColorSampleCounts = sample_counts,
722 .framebufferDepthSampleCounts = sample_counts,
723 .framebufferStencilSampleCounts = sample_counts,
724 .framebufferNoAttachmentsSampleCounts = sample_counts,
725 .maxColorAttachments = MAX_RTS,
726 .sampledImageColorSampleCounts = sample_counts,
727 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
728 .sampledImageDepthSampleCounts = sample_counts,
729 .sampledImageStencilSampleCounts = sample_counts,
730 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
731 .maxSampleMaskWords = 1,
732 .timestampComputeAndGraphics = false,
733 .timestampPeriod = devinfo->timebase_scale,
734 .maxClipDistances = 8,
735 .maxCullDistances = 8,
736 .maxCombinedClipAndCullDistances = 8,
737 .discreteQueuePriorities = 1,
738 .pointSizeRange = { 0.125, 255.875 },
739 .lineWidthRange = { 0.0, 7.9921875 },
740 .pointSizeGranularity = (1.0 / 8.0),
741 .lineWidthGranularity = (1.0 / 128.0),
742 .strictLines = false, /* FINISHME */
743 .standardSampleLocations = true,
744 .optimalBufferCopyOffsetAlignment = 128,
745 .optimalBufferCopyRowPitchAlignment = 128,
746 .nonCoherentAtomSize = 64,
747 };
748
749 *pProperties = (VkPhysicalDeviceProperties) {
750 .apiVersion = VK_MAKE_VERSION(1, 0, 42),
751 .driverVersion = 1,
752 .vendorID = 0x8086,
753 .deviceID = pdevice->chipset_id,
754 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
755 .limits = limits,
756 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
757 };
758
759 strcpy(pProperties->deviceName, pdevice->name);
760 memcpy(pProperties->pipelineCacheUUID,
761 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
762 }
763
764 void anv_GetPhysicalDeviceProperties2KHR(
765 VkPhysicalDevice physicalDevice,
766 VkPhysicalDeviceProperties2KHR* pProperties)
767 {
768 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
769
770 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
771
772 vk_foreach_struct(ext, pProperties->pNext) {
773 switch (ext->sType) {
774 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
775 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
776 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
777
778 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
779 break;
780 }
781
782 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHX: {
783 VkPhysicalDeviceIDPropertiesKHX *id_props =
784 (VkPhysicalDeviceIDPropertiesKHX *)ext;
785 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
786 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
787 /* The LUID is for Windows. */
788 id_props->deviceLUIDValid = false;
789 break;
790 }
791
792 default:
793 anv_debug_ignored_stype(ext->sType);
794 break;
795 }
796 }
797 }
798
799 /* We support exactly one queue family. */
800 static const VkQueueFamilyProperties
801 anv_queue_family_properties = {
802 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
803 VK_QUEUE_COMPUTE_BIT |
804 VK_QUEUE_TRANSFER_BIT,
805 .queueCount = 1,
806 .timestampValidBits = 36, /* XXX: Real value here */
807 .minImageTransferGranularity = { 1, 1, 1 },
808 };
809
810 void anv_GetPhysicalDeviceQueueFamilyProperties(
811 VkPhysicalDevice physicalDevice,
812 uint32_t* pCount,
813 VkQueueFamilyProperties* pQueueFamilyProperties)
814 {
815 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
816
817 vk_outarray_append(&out, p) {
818 *p = anv_queue_family_properties;
819 }
820 }
821
822 void anv_GetPhysicalDeviceQueueFamilyProperties2KHR(
823 VkPhysicalDevice physicalDevice,
824 uint32_t* pQueueFamilyPropertyCount,
825 VkQueueFamilyProperties2KHR* pQueueFamilyProperties)
826 {
827
828 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
829
830 vk_outarray_append(&out, p) {
831 p->queueFamilyProperties = anv_queue_family_properties;
832
833 vk_foreach_struct(s, p->pNext) {
834 anv_debug_ignored_stype(s->sType);
835 }
836 }
837 }
838
839 void anv_GetPhysicalDeviceMemoryProperties(
840 VkPhysicalDevice physicalDevice,
841 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
842 {
843 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
844
845 if (physical_device->info.has_llc) {
846 /* Big core GPUs share LLC with the CPU and thus one memory type can be
847 * both cached and coherent at the same time.
848 */
849 pMemoryProperties->memoryTypeCount = 1;
850 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
851 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
852 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
853 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
854 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
855 .heapIndex = 0,
856 };
857 } else {
858 /* The spec requires that we expose a host-visible, coherent memory
859 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
860 * to give the application a choice between cached, but not coherent and
861 * coherent but uncached (WC though).
862 */
863 pMemoryProperties->memoryTypeCount = 2;
864 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
865 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
866 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
867 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
868 .heapIndex = 0,
869 };
870 pMemoryProperties->memoryTypes[1] = (VkMemoryType) {
871 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
872 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
873 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
874 .heapIndex = 0,
875 };
876 }
877
878 pMemoryProperties->memoryHeapCount = 1;
879 pMemoryProperties->memoryHeaps[0] = (VkMemoryHeap) {
880 .size = physical_device->heap_size,
881 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
882 };
883 }
884
885 void anv_GetPhysicalDeviceMemoryProperties2KHR(
886 VkPhysicalDevice physicalDevice,
887 VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties)
888 {
889 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
890 &pMemoryProperties->memoryProperties);
891
892 vk_foreach_struct(ext, pMemoryProperties->pNext) {
893 switch (ext->sType) {
894 default:
895 anv_debug_ignored_stype(ext->sType);
896 break;
897 }
898 }
899 }
900
901 PFN_vkVoidFunction anv_GetInstanceProcAddr(
902 VkInstance instance,
903 const char* pName)
904 {
905 return anv_lookup_entrypoint(NULL, pName);
906 }
907
908 /* With version 1+ of the loader interface the ICD should expose
909 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
910 */
911 PUBLIC
912 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
913 VkInstance instance,
914 const char* pName);
915
916 PUBLIC
917 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
918 VkInstance instance,
919 const char* pName)
920 {
921 return anv_GetInstanceProcAddr(instance, pName);
922 }
923
924 PFN_vkVoidFunction anv_GetDeviceProcAddr(
925 VkDevice _device,
926 const char* pName)
927 {
928 ANV_FROM_HANDLE(anv_device, device, _device);
929 return anv_lookup_entrypoint(&device->info, pName);
930 }
931
932 static void
933 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
934 {
935 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
936 queue->device = device;
937 queue->pool = &device->surface_state_pool;
938 }
939
940 static void
941 anv_queue_finish(struct anv_queue *queue)
942 {
943 }
944
945 static struct anv_state
946 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
947 {
948 struct anv_state state;
949
950 state = anv_state_pool_alloc(pool, size, align);
951 memcpy(state.map, p, size);
952
953 anv_state_flush(pool->block_pool->device, state);
954
955 return state;
956 }
957
958 struct gen8_border_color {
959 union {
960 float float32[4];
961 uint32_t uint32[4];
962 };
963 /* Pad out to 64 bytes */
964 uint32_t _pad[12];
965 };
966
967 static void
968 anv_device_init_border_colors(struct anv_device *device)
969 {
970 static const struct gen8_border_color border_colors[] = {
971 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
972 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
973 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
974 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
975 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
976 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
977 };
978
979 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
980 sizeof(border_colors), 64,
981 border_colors);
982 }
983
984 VkResult
985 anv_device_submit_simple_batch(struct anv_device *device,
986 struct anv_batch *batch)
987 {
988 struct drm_i915_gem_execbuffer2 execbuf;
989 struct drm_i915_gem_exec_object2 exec2_objects[1];
990 struct anv_bo bo, *exec_bos[1];
991 VkResult result = VK_SUCCESS;
992 uint32_t size;
993
994 /* Kernel driver requires 8 byte aligned batch length */
995 size = align_u32(batch->next - batch->start, 8);
996 result = anv_bo_pool_alloc(&device->batch_bo_pool, &bo, size);
997 if (result != VK_SUCCESS)
998 return result;
999
1000 memcpy(bo.map, batch->start, size);
1001 if (!device->info.has_llc)
1002 anv_flush_range(bo.map, size);
1003
1004 exec_bos[0] = &bo;
1005 exec2_objects[0].handle = bo.gem_handle;
1006 exec2_objects[0].relocation_count = 0;
1007 exec2_objects[0].relocs_ptr = 0;
1008 exec2_objects[0].alignment = 0;
1009 exec2_objects[0].offset = bo.offset;
1010 exec2_objects[0].flags = 0;
1011 exec2_objects[0].rsvd1 = 0;
1012 exec2_objects[0].rsvd2 = 0;
1013
1014 execbuf.buffers_ptr = (uintptr_t) exec2_objects;
1015 execbuf.buffer_count = 1;
1016 execbuf.batch_start_offset = 0;
1017 execbuf.batch_len = size;
1018 execbuf.cliprects_ptr = 0;
1019 execbuf.num_cliprects = 0;
1020 execbuf.DR1 = 0;
1021 execbuf.DR4 = 0;
1022
1023 execbuf.flags =
1024 I915_EXEC_HANDLE_LUT | I915_EXEC_NO_RELOC | I915_EXEC_RENDER;
1025 execbuf.rsvd1 = device->context_id;
1026 execbuf.rsvd2 = 0;
1027
1028 result = anv_device_execbuf(device, &execbuf, exec_bos);
1029 if (result != VK_SUCCESS)
1030 goto fail;
1031
1032 result = anv_device_wait(device, &bo, INT64_MAX);
1033
1034 fail:
1035 anv_bo_pool_free(&device->batch_bo_pool, &bo);
1036
1037 return result;
1038 }
1039
1040 VkResult anv_CreateDevice(
1041 VkPhysicalDevice physicalDevice,
1042 const VkDeviceCreateInfo* pCreateInfo,
1043 const VkAllocationCallbacks* pAllocator,
1044 VkDevice* pDevice)
1045 {
1046 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1047 VkResult result;
1048 struct anv_device *device;
1049
1050 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1051
1052 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1053 bool found = false;
1054 for (uint32_t j = 0; j < ARRAY_SIZE(device_extensions); j++) {
1055 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1056 device_extensions[j].extensionName) == 0) {
1057 found = true;
1058 break;
1059 }
1060 }
1061 if (!found)
1062 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1063 }
1064
1065 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1066 sizeof(*device), 8,
1067 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1068 if (!device)
1069 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1070
1071 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1072 device->instance = physical_device->instance;
1073 device->chipset_id = physical_device->chipset_id;
1074 device->lost = false;
1075
1076 if (pAllocator)
1077 device->alloc = *pAllocator;
1078 else
1079 device->alloc = physical_device->instance->alloc;
1080
1081 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1082 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1083 if (device->fd == -1) {
1084 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1085 goto fail_device;
1086 }
1087
1088 device->context_id = anv_gem_create_context(device);
1089 if (device->context_id == -1) {
1090 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1091 goto fail_fd;
1092 }
1093
1094 device->info = physical_device->info;
1095 device->isl_dev = physical_device->isl_dev;
1096
1097 /* On Broadwell and later, we can use batch chaining to more efficiently
1098 * implement growing command buffers. Prior to Haswell, the kernel
1099 * command parser gets in the way and we have to fall back to growing
1100 * the batch.
1101 */
1102 device->can_chain_batches = device->info.gen >= 8;
1103
1104 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1105 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1106
1107 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1108 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1109 goto fail_context_id;
1110 }
1111
1112 pthread_condattr_t condattr;
1113 if (pthread_condattr_init(&condattr) != 0) {
1114 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1115 goto fail_mutex;
1116 }
1117 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1118 pthread_condattr_destroy(&condattr);
1119 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1120 goto fail_mutex;
1121 }
1122 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1123 pthread_condattr_destroy(&condattr);
1124 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1125 goto fail_mutex;
1126 }
1127 pthread_condattr_destroy(&condattr);
1128
1129 anv_bo_pool_init(&device->batch_bo_pool, device);
1130
1131 result = anv_bo_cache_init(&device->bo_cache);
1132 if (result != VK_SUCCESS)
1133 goto fail_batch_bo_pool;
1134
1135 result = anv_block_pool_init(&device->dynamic_state_block_pool, device,
1136 16384);
1137 if (result != VK_SUCCESS)
1138 goto fail_bo_cache;
1139
1140 anv_state_pool_init(&device->dynamic_state_pool,
1141 &device->dynamic_state_block_pool);
1142
1143 result = anv_block_pool_init(&device->instruction_block_pool, device,
1144 1024 * 1024);
1145 if (result != VK_SUCCESS)
1146 goto fail_dynamic_state_pool;
1147
1148 anv_state_pool_init(&device->instruction_state_pool,
1149 &device->instruction_block_pool);
1150
1151 result = anv_block_pool_init(&device->surface_state_block_pool, device,
1152 4096);
1153 if (result != VK_SUCCESS)
1154 goto fail_instruction_state_pool;
1155
1156 anv_state_pool_init(&device->surface_state_pool,
1157 &device->surface_state_block_pool);
1158
1159 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1160 if (result != VK_SUCCESS)
1161 goto fail_surface_state_pool;
1162
1163 anv_scratch_pool_init(device, &device->scratch_pool);
1164
1165 anv_queue_init(device, &device->queue);
1166
1167 switch (device->info.gen) {
1168 case 7:
1169 if (!device->info.is_haswell)
1170 result = gen7_init_device_state(device);
1171 else
1172 result = gen75_init_device_state(device);
1173 break;
1174 case 8:
1175 result = gen8_init_device_state(device);
1176 break;
1177 case 9:
1178 result = gen9_init_device_state(device);
1179 break;
1180 default:
1181 /* Shouldn't get here as we don't create physical devices for any other
1182 * gens. */
1183 unreachable("unhandled gen");
1184 }
1185 if (result != VK_SUCCESS)
1186 goto fail_workaround_bo;
1187
1188 anv_device_init_blorp(device);
1189
1190 anv_device_init_border_colors(device);
1191
1192 *pDevice = anv_device_to_handle(device);
1193
1194 return VK_SUCCESS;
1195
1196 fail_workaround_bo:
1197 anv_queue_finish(&device->queue);
1198 anv_scratch_pool_finish(device, &device->scratch_pool);
1199 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1200 anv_gem_close(device, device->workaround_bo.gem_handle);
1201 fail_surface_state_pool:
1202 anv_state_pool_finish(&device->surface_state_pool);
1203 anv_block_pool_finish(&device->surface_state_block_pool);
1204 fail_instruction_state_pool:
1205 anv_state_pool_finish(&device->instruction_state_pool);
1206 anv_block_pool_finish(&device->instruction_block_pool);
1207 fail_dynamic_state_pool:
1208 anv_state_pool_finish(&device->dynamic_state_pool);
1209 anv_block_pool_finish(&device->dynamic_state_block_pool);
1210 fail_bo_cache:
1211 anv_bo_cache_finish(&device->bo_cache);
1212 fail_batch_bo_pool:
1213 anv_bo_pool_finish(&device->batch_bo_pool);
1214 pthread_cond_destroy(&device->queue_submit);
1215 fail_mutex:
1216 pthread_mutex_destroy(&device->mutex);
1217 fail_context_id:
1218 anv_gem_destroy_context(device, device->context_id);
1219 fail_fd:
1220 close(device->fd);
1221 fail_device:
1222 vk_free(&device->alloc, device);
1223
1224 return result;
1225 }
1226
1227 void anv_DestroyDevice(
1228 VkDevice _device,
1229 const VkAllocationCallbacks* pAllocator)
1230 {
1231 ANV_FROM_HANDLE(anv_device, device, _device);
1232
1233 if (!device)
1234 return;
1235
1236 anv_device_finish_blorp(device);
1237
1238 anv_queue_finish(&device->queue);
1239
1240 #ifdef HAVE_VALGRIND
1241 /* We only need to free these to prevent valgrind errors. The backing
1242 * BO will go away in a couple of lines so we don't actually leak.
1243 */
1244 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1245 #endif
1246
1247 anv_scratch_pool_finish(device, &device->scratch_pool);
1248
1249 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1250 anv_gem_close(device, device->workaround_bo.gem_handle);
1251
1252 anv_state_pool_finish(&device->surface_state_pool);
1253 anv_block_pool_finish(&device->surface_state_block_pool);
1254 anv_state_pool_finish(&device->instruction_state_pool);
1255 anv_block_pool_finish(&device->instruction_block_pool);
1256 anv_state_pool_finish(&device->dynamic_state_pool);
1257 anv_block_pool_finish(&device->dynamic_state_block_pool);
1258
1259 anv_bo_cache_finish(&device->bo_cache);
1260
1261 anv_bo_pool_finish(&device->batch_bo_pool);
1262
1263 pthread_cond_destroy(&device->queue_submit);
1264 pthread_mutex_destroy(&device->mutex);
1265
1266 anv_gem_destroy_context(device, device->context_id);
1267
1268 close(device->fd);
1269
1270 vk_free(&device->alloc, device);
1271 }
1272
1273 VkResult anv_EnumerateInstanceExtensionProperties(
1274 const char* pLayerName,
1275 uint32_t* pPropertyCount,
1276 VkExtensionProperties* pProperties)
1277 {
1278 if (pProperties == NULL) {
1279 *pPropertyCount = ARRAY_SIZE(global_extensions);
1280 return VK_SUCCESS;
1281 }
1282
1283 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(global_extensions));
1284 typed_memcpy(pProperties, global_extensions, *pPropertyCount);
1285
1286 if (*pPropertyCount < ARRAY_SIZE(global_extensions))
1287 return VK_INCOMPLETE;
1288
1289 return VK_SUCCESS;
1290 }
1291
1292 VkResult anv_EnumerateDeviceExtensionProperties(
1293 VkPhysicalDevice physicalDevice,
1294 const char* pLayerName,
1295 uint32_t* pPropertyCount,
1296 VkExtensionProperties* pProperties)
1297 {
1298 if (pProperties == NULL) {
1299 *pPropertyCount = ARRAY_SIZE(device_extensions);
1300 return VK_SUCCESS;
1301 }
1302
1303 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(device_extensions));
1304 typed_memcpy(pProperties, device_extensions, *pPropertyCount);
1305
1306 if (*pPropertyCount < ARRAY_SIZE(device_extensions))
1307 return VK_INCOMPLETE;
1308
1309 return VK_SUCCESS;
1310 }
1311
1312 VkResult anv_EnumerateInstanceLayerProperties(
1313 uint32_t* pPropertyCount,
1314 VkLayerProperties* pProperties)
1315 {
1316 if (pProperties == NULL) {
1317 *pPropertyCount = 0;
1318 return VK_SUCCESS;
1319 }
1320
1321 /* None supported at this time */
1322 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1323 }
1324
1325 VkResult anv_EnumerateDeviceLayerProperties(
1326 VkPhysicalDevice physicalDevice,
1327 uint32_t* pPropertyCount,
1328 VkLayerProperties* pProperties)
1329 {
1330 if (pProperties == NULL) {
1331 *pPropertyCount = 0;
1332 return VK_SUCCESS;
1333 }
1334
1335 /* None supported at this time */
1336 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1337 }
1338
1339 void anv_GetDeviceQueue(
1340 VkDevice _device,
1341 uint32_t queueNodeIndex,
1342 uint32_t queueIndex,
1343 VkQueue* pQueue)
1344 {
1345 ANV_FROM_HANDLE(anv_device, device, _device);
1346
1347 assert(queueIndex == 0);
1348
1349 *pQueue = anv_queue_to_handle(&device->queue);
1350 }
1351
1352 VkResult
1353 anv_device_execbuf(struct anv_device *device,
1354 struct drm_i915_gem_execbuffer2 *execbuf,
1355 struct anv_bo **execbuf_bos)
1356 {
1357 int ret = anv_gem_execbuffer(device, execbuf);
1358 if (ret != 0) {
1359 /* We don't know the real error. */
1360 device->lost = true;
1361 return vk_errorf(VK_ERROR_DEVICE_LOST, "execbuf2 failed: %m");
1362 }
1363
1364 struct drm_i915_gem_exec_object2 *objects =
1365 (void *)(uintptr_t)execbuf->buffers_ptr;
1366 for (uint32_t k = 0; k < execbuf->buffer_count; k++)
1367 execbuf_bos[k]->offset = objects[k].offset;
1368
1369 return VK_SUCCESS;
1370 }
1371
1372 VkResult
1373 anv_device_query_status(struct anv_device *device)
1374 {
1375 /* This isn't likely as most of the callers of this function already check
1376 * for it. However, it doesn't hurt to check and it potentially lets us
1377 * avoid an ioctl.
1378 */
1379 if (unlikely(device->lost))
1380 return VK_ERROR_DEVICE_LOST;
1381
1382 uint32_t active, pending;
1383 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
1384 if (ret == -1) {
1385 /* We don't know the real error. */
1386 device->lost = true;
1387 return vk_errorf(VK_ERROR_DEVICE_LOST, "get_reset_stats failed: %m");
1388 }
1389
1390 if (active) {
1391 device->lost = true;
1392 return vk_errorf(VK_ERROR_DEVICE_LOST,
1393 "GPU hung on one of our command buffers");
1394 } else if (pending) {
1395 device->lost = true;
1396 return vk_errorf(VK_ERROR_DEVICE_LOST,
1397 "GPU hung with commands in-flight");
1398 }
1399
1400 return VK_SUCCESS;
1401 }
1402
1403 VkResult
1404 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
1405 {
1406 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
1407 * Other usages of the BO (such as on different hardware) will not be
1408 * flagged as "busy" by this ioctl. Use with care.
1409 */
1410 int ret = anv_gem_busy(device, bo->gem_handle);
1411 if (ret == 1) {
1412 return VK_NOT_READY;
1413 } else if (ret == -1) {
1414 /* We don't know the real error. */
1415 device->lost = true;
1416 return vk_errorf(VK_ERROR_DEVICE_LOST, "gem wait failed: %m");
1417 }
1418
1419 /* Query for device status after the busy call. If the BO we're checking
1420 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
1421 * client because it clearly doesn't have valid data. Yes, this most
1422 * likely means an ioctl, but we just did an ioctl to query the busy status
1423 * so it's no great loss.
1424 */
1425 return anv_device_query_status(device);
1426 }
1427
1428 VkResult
1429 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
1430 int64_t timeout)
1431 {
1432 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
1433 if (ret == -1 && errno == ETIME) {
1434 return VK_TIMEOUT;
1435 } else if (ret == -1) {
1436 /* We don't know the real error. */
1437 device->lost = true;
1438 return vk_errorf(VK_ERROR_DEVICE_LOST, "gem wait failed: %m");
1439 }
1440
1441 /* Query for device status after the wait. If the BO we're waiting on got
1442 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
1443 * because it clearly doesn't have valid data. Yes, this most likely means
1444 * an ioctl, but we just did an ioctl to wait so it's no great loss.
1445 */
1446 return anv_device_query_status(device);
1447 }
1448
1449 VkResult anv_QueueSubmit(
1450 VkQueue _queue,
1451 uint32_t submitCount,
1452 const VkSubmitInfo* pSubmits,
1453 VkFence _fence)
1454 {
1455 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1456 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1457 struct anv_device *device = queue->device;
1458
1459 /* Query for device status prior to submitting. Technically, we don't need
1460 * to do this. However, if we have a client that's submitting piles of
1461 * garbage, we would rather break as early as possible to keep the GPU
1462 * hanging contained. If we don't check here, we'll either be waiting for
1463 * the kernel to kick us or we'll have to wait until the client waits on a
1464 * fence before we actually know whether or not we've hung.
1465 */
1466 VkResult result = anv_device_query_status(device);
1467 if (result != VK_SUCCESS)
1468 return result;
1469
1470 /* We lock around QueueSubmit for three main reasons:
1471 *
1472 * 1) When a block pool is resized, we create a new gem handle with a
1473 * different size and, in the case of surface states, possibly a
1474 * different center offset but we re-use the same anv_bo struct when
1475 * we do so. If this happens in the middle of setting up an execbuf,
1476 * we could end up with our list of BOs out of sync with our list of
1477 * gem handles.
1478 *
1479 * 2) The algorithm we use for building the list of unique buffers isn't
1480 * thread-safe. While the client is supposed to syncronize around
1481 * QueueSubmit, this would be extremely difficult to debug if it ever
1482 * came up in the wild due to a broken app. It's better to play it
1483 * safe and just lock around QueueSubmit.
1484 *
1485 * 3) The anv_cmd_buffer_execbuf function may perform relocations in
1486 * userspace. Due to the fact that the surface state buffer is shared
1487 * between batches, we can't afford to have that happen from multiple
1488 * threads at the same time. Even though the user is supposed to
1489 * ensure this doesn't happen, we play it safe as in (2) above.
1490 *
1491 * Since the only other things that ever take the device lock such as block
1492 * pool resize only rarely happen, this will almost never be contended so
1493 * taking a lock isn't really an expensive operation in this case.
1494 */
1495 pthread_mutex_lock(&device->mutex);
1496
1497 for (uint32_t i = 0; i < submitCount; i++) {
1498 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
1499 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer,
1500 pSubmits[i].pCommandBuffers[j]);
1501 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1502 assert(!anv_batch_has_error(&cmd_buffer->batch));
1503
1504 result = anv_cmd_buffer_execbuf(device, cmd_buffer);
1505 if (result != VK_SUCCESS)
1506 goto out;
1507 }
1508 }
1509
1510 if (fence) {
1511 struct anv_bo *fence_bo = &fence->bo;
1512 result = anv_device_execbuf(device, &fence->execbuf, &fence_bo);
1513 if (result != VK_SUCCESS)
1514 goto out;
1515
1516 /* Update the fence and wake up any waiters */
1517 assert(fence->state == ANV_FENCE_STATE_RESET);
1518 fence->state = ANV_FENCE_STATE_SUBMITTED;
1519 pthread_cond_broadcast(&device->queue_submit);
1520 }
1521
1522 out:
1523 if (result != VK_SUCCESS) {
1524 /* In the case that something has gone wrong we may end up with an
1525 * inconsistent state from which it may not be trivial to recover.
1526 * For example, we might have computed address relocations and
1527 * any future attempt to re-submit this job will need to know about
1528 * this and avoid computing relocation addresses again.
1529 *
1530 * To avoid this sort of issues, we assume that if something was
1531 * wrong during submission we must already be in a really bad situation
1532 * anyway (such us being out of memory) and return
1533 * VK_ERROR_DEVICE_LOST to ensure that clients do not attempt to
1534 * submit the same job again to this device.
1535 */
1536 result = VK_ERROR_DEVICE_LOST;
1537 device->lost = true;
1538
1539 /* If we return VK_ERROR_DEVICE LOST here, we need to ensure that
1540 * vkWaitForFences() and vkGetFenceStatus() return a valid result
1541 * (VK_SUCCESS or VK_ERROR_DEVICE_LOST) in a finite amount of time.
1542 * Setting the fence status to SIGNALED ensures this will happen in
1543 * any case.
1544 */
1545 if (fence)
1546 fence->state = ANV_FENCE_STATE_SIGNALED;
1547 }
1548
1549 pthread_mutex_unlock(&device->mutex);
1550
1551 return result;
1552 }
1553
1554 VkResult anv_QueueWaitIdle(
1555 VkQueue _queue)
1556 {
1557 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1558
1559 return anv_DeviceWaitIdle(anv_device_to_handle(queue->device));
1560 }
1561
1562 VkResult anv_DeviceWaitIdle(
1563 VkDevice _device)
1564 {
1565 ANV_FROM_HANDLE(anv_device, device, _device);
1566 if (unlikely(device->lost))
1567 return VK_ERROR_DEVICE_LOST;
1568
1569 struct anv_batch batch;
1570
1571 uint32_t cmds[8];
1572 batch.start = batch.next = cmds;
1573 batch.end = (void *) cmds + sizeof(cmds);
1574
1575 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1576 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1577
1578 return anv_device_submit_simple_batch(device, &batch);
1579 }
1580
1581 VkResult
1582 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
1583 {
1584 uint32_t gem_handle = anv_gem_create(device, size);
1585 if (!gem_handle)
1586 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1587
1588 anv_bo_init(bo, gem_handle, size);
1589
1590 if (device->instance->physicalDevice.supports_48bit_addresses)
1591 bo->flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1592
1593 if (device->instance->physicalDevice.has_exec_async)
1594 bo->flags |= EXEC_OBJECT_ASYNC;
1595
1596 return VK_SUCCESS;
1597 }
1598
1599 VkResult anv_AllocateMemory(
1600 VkDevice _device,
1601 const VkMemoryAllocateInfo* pAllocateInfo,
1602 const VkAllocationCallbacks* pAllocator,
1603 VkDeviceMemory* pMem)
1604 {
1605 ANV_FROM_HANDLE(anv_device, device, _device);
1606 struct anv_device_memory *mem;
1607 VkResult result = VK_SUCCESS;
1608
1609 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1610
1611 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
1612 assert(pAllocateInfo->allocationSize > 0);
1613
1614 /* We support exactly one memory heap. */
1615 assert(pAllocateInfo->memoryTypeIndex == 0 ||
1616 (!device->info.has_llc && pAllocateInfo->memoryTypeIndex < 2));
1617
1618 /* The kernel relocation API has a limitation of a 32-bit delta value
1619 * applied to the address before it is written which, in spite of it being
1620 * unsigned, is treated as signed . Because of the way that this maps to
1621 * the Vulkan API, we cannot handle an offset into a buffer that does not
1622 * fit into a signed 32 bits. The only mechanism we have for dealing with
1623 * this at the moment is to limit all VkDeviceMemory objects to a maximum
1624 * of 2GB each. The Vulkan spec allows us to do this:
1625 *
1626 * "Some platforms may have a limit on the maximum size of a single
1627 * allocation. For example, certain systems may fail to create
1628 * allocations with a size greater than or equal to 4GB. Such a limit is
1629 * implementation-dependent, and if such a failure occurs then the error
1630 * VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
1631 *
1632 * We don't use vk_error here because it's not an error so much as an
1633 * indication to the application that the allocation is too large.
1634 */
1635 if (pAllocateInfo->allocationSize > (1ull << 31))
1636 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1637
1638 /* FINISHME: Fail if allocation request exceeds heap size. */
1639
1640 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1641 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1642 if (mem == NULL)
1643 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1644
1645 mem->type_index = pAllocateInfo->memoryTypeIndex;
1646 mem->map = NULL;
1647 mem->map_size = 0;
1648
1649 const VkImportMemoryFdInfoKHX *fd_info =
1650 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHX);
1651
1652 /* The Vulkan spec permits handleType to be 0, in which case the struct is
1653 * ignored.
1654 */
1655 if (fd_info && fd_info->handleType) {
1656 /* At the moment, we only support the OPAQUE_FD memory type which is
1657 * just a GEM buffer.
1658 */
1659 assert(fd_info->handleType ==
1660 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHX);
1661
1662 result = anv_bo_cache_import(device, &device->bo_cache,
1663 fd_info->fd, pAllocateInfo->allocationSize,
1664 &mem->bo);
1665 if (result != VK_SUCCESS)
1666 goto fail;
1667 } else {
1668 result = anv_bo_cache_alloc(device, &device->bo_cache,
1669 pAllocateInfo->allocationSize,
1670 &mem->bo);
1671 if (result != VK_SUCCESS)
1672 goto fail;
1673 }
1674
1675 *pMem = anv_device_memory_to_handle(mem);
1676
1677 return VK_SUCCESS;
1678
1679 fail:
1680 vk_free2(&device->alloc, pAllocator, mem);
1681
1682 return result;
1683 }
1684
1685 VkResult anv_GetMemoryFdKHX(
1686 VkDevice device_h,
1687 VkDeviceMemory memory_h,
1688 VkExternalMemoryHandleTypeFlagBitsKHX handleType,
1689 int* pFd)
1690 {
1691 ANV_FROM_HANDLE(anv_device, dev, device_h);
1692 ANV_FROM_HANDLE(anv_device_memory, mem, memory_h);
1693
1694 /* We support only one handle type. */
1695 assert(handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHX);
1696
1697 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
1698 }
1699
1700 VkResult anv_GetMemoryFdPropertiesKHX(
1701 VkDevice device_h,
1702 VkExternalMemoryHandleTypeFlagBitsKHX handleType,
1703 int fd,
1704 VkMemoryFdPropertiesKHX* pMemoryFdProperties)
1705 {
1706 /* The valid usage section for this function says:
1707 *
1708 * "handleType must not be one of the handle types defined as opaque."
1709 *
1710 * Since we only handle opaque handles for now, there are no FD properties.
1711 */
1712 return VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX;
1713 }
1714
1715 void anv_FreeMemory(
1716 VkDevice _device,
1717 VkDeviceMemory _mem,
1718 const VkAllocationCallbacks* pAllocator)
1719 {
1720 ANV_FROM_HANDLE(anv_device, device, _device);
1721 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
1722
1723 if (mem == NULL)
1724 return;
1725
1726 if (mem->map)
1727 anv_UnmapMemory(_device, _mem);
1728
1729 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1730
1731 vk_free2(&device->alloc, pAllocator, mem);
1732 }
1733
1734 VkResult anv_MapMemory(
1735 VkDevice _device,
1736 VkDeviceMemory _memory,
1737 VkDeviceSize offset,
1738 VkDeviceSize size,
1739 VkMemoryMapFlags flags,
1740 void** ppData)
1741 {
1742 ANV_FROM_HANDLE(anv_device, device, _device);
1743 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1744
1745 if (mem == NULL) {
1746 *ppData = NULL;
1747 return VK_SUCCESS;
1748 }
1749
1750 if (size == VK_WHOLE_SIZE)
1751 size = mem->bo->size - offset;
1752
1753 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
1754 *
1755 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
1756 * assert(size != 0);
1757 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
1758 * equal to the size of the memory minus offset
1759 */
1760 assert(size > 0);
1761 assert(offset + size <= mem->bo->size);
1762
1763 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
1764 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
1765 * at a time is valid. We could just mmap up front and return an offset
1766 * pointer here, but that may exhaust virtual memory on 32 bit
1767 * userspace. */
1768
1769 uint32_t gem_flags = 0;
1770 if (!device->info.has_llc && mem->type_index == 0)
1771 gem_flags |= I915_MMAP_WC;
1772
1773 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
1774 uint64_t map_offset = offset & ~4095ull;
1775 assert(offset >= map_offset);
1776 uint64_t map_size = (offset + size) - map_offset;
1777
1778 /* Let's map whole pages */
1779 map_size = align_u64(map_size, 4096);
1780
1781 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
1782 map_offset, map_size, gem_flags);
1783 if (map == MAP_FAILED)
1784 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1785
1786 mem->map = map;
1787 mem->map_size = map_size;
1788
1789 *ppData = mem->map + (offset - map_offset);
1790
1791 return VK_SUCCESS;
1792 }
1793
1794 void anv_UnmapMemory(
1795 VkDevice _device,
1796 VkDeviceMemory _memory)
1797 {
1798 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1799
1800 if (mem == NULL)
1801 return;
1802
1803 anv_gem_munmap(mem->map, mem->map_size);
1804
1805 mem->map = NULL;
1806 mem->map_size = 0;
1807 }
1808
1809 static void
1810 clflush_mapped_ranges(struct anv_device *device,
1811 uint32_t count,
1812 const VkMappedMemoryRange *ranges)
1813 {
1814 for (uint32_t i = 0; i < count; i++) {
1815 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
1816 if (ranges[i].offset >= mem->map_size)
1817 continue;
1818
1819 anv_clflush_range(mem->map + ranges[i].offset,
1820 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
1821 }
1822 }
1823
1824 VkResult anv_FlushMappedMemoryRanges(
1825 VkDevice _device,
1826 uint32_t memoryRangeCount,
1827 const VkMappedMemoryRange* pMemoryRanges)
1828 {
1829 ANV_FROM_HANDLE(anv_device, device, _device);
1830
1831 if (device->info.has_llc)
1832 return VK_SUCCESS;
1833
1834 /* Make sure the writes we're flushing have landed. */
1835 __builtin_ia32_mfence();
1836
1837 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1838
1839 return VK_SUCCESS;
1840 }
1841
1842 VkResult anv_InvalidateMappedMemoryRanges(
1843 VkDevice _device,
1844 uint32_t memoryRangeCount,
1845 const VkMappedMemoryRange* pMemoryRanges)
1846 {
1847 ANV_FROM_HANDLE(anv_device, device, _device);
1848
1849 if (device->info.has_llc)
1850 return VK_SUCCESS;
1851
1852 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1853
1854 /* Make sure no reads get moved up above the invalidate. */
1855 __builtin_ia32_mfence();
1856
1857 return VK_SUCCESS;
1858 }
1859
1860 void anv_GetBufferMemoryRequirements(
1861 VkDevice _device,
1862 VkBuffer _buffer,
1863 VkMemoryRequirements* pMemoryRequirements)
1864 {
1865 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1866 ANV_FROM_HANDLE(anv_device, device, _device);
1867
1868 /* The Vulkan spec (git aaed022) says:
1869 *
1870 * memoryTypeBits is a bitfield and contains one bit set for every
1871 * supported memory type for the resource. The bit `1<<i` is set if and
1872 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1873 * structure for the physical device is supported.
1874 *
1875 * We support exactly one memory type on LLC, two on non-LLC.
1876 */
1877 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1878
1879 pMemoryRequirements->size = buffer->size;
1880 pMemoryRequirements->alignment = 16;
1881 }
1882
1883 void anv_GetImageMemoryRequirements(
1884 VkDevice _device,
1885 VkImage _image,
1886 VkMemoryRequirements* pMemoryRequirements)
1887 {
1888 ANV_FROM_HANDLE(anv_image, image, _image);
1889 ANV_FROM_HANDLE(anv_device, device, _device);
1890
1891 /* The Vulkan spec (git aaed022) says:
1892 *
1893 * memoryTypeBits is a bitfield and contains one bit set for every
1894 * supported memory type for the resource. The bit `1<<i` is set if and
1895 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1896 * structure for the physical device is supported.
1897 *
1898 * We support exactly one memory type on LLC, two on non-LLC.
1899 */
1900 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1901
1902 pMemoryRequirements->size = image->size;
1903 pMemoryRequirements->alignment = image->alignment;
1904 }
1905
1906 void anv_GetImageSparseMemoryRequirements(
1907 VkDevice device,
1908 VkImage image,
1909 uint32_t* pSparseMemoryRequirementCount,
1910 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
1911 {
1912 *pSparseMemoryRequirementCount = 0;
1913 }
1914
1915 void anv_GetDeviceMemoryCommitment(
1916 VkDevice device,
1917 VkDeviceMemory memory,
1918 VkDeviceSize* pCommittedMemoryInBytes)
1919 {
1920 *pCommittedMemoryInBytes = 0;
1921 }
1922
1923 VkResult anv_BindBufferMemory(
1924 VkDevice device,
1925 VkBuffer _buffer,
1926 VkDeviceMemory _memory,
1927 VkDeviceSize memoryOffset)
1928 {
1929 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1930 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1931
1932 if (mem) {
1933 buffer->bo = mem->bo;
1934 buffer->offset = memoryOffset;
1935 } else {
1936 buffer->bo = NULL;
1937 buffer->offset = 0;
1938 }
1939
1940 return VK_SUCCESS;
1941 }
1942
1943 VkResult anv_QueueBindSparse(
1944 VkQueue _queue,
1945 uint32_t bindInfoCount,
1946 const VkBindSparseInfo* pBindInfo,
1947 VkFence fence)
1948 {
1949 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1950 if (unlikely(queue->device->lost))
1951 return VK_ERROR_DEVICE_LOST;
1952
1953 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1954 }
1955
1956 VkResult anv_CreateFence(
1957 VkDevice _device,
1958 const VkFenceCreateInfo* pCreateInfo,
1959 const VkAllocationCallbacks* pAllocator,
1960 VkFence* pFence)
1961 {
1962 ANV_FROM_HANDLE(anv_device, device, _device);
1963 struct anv_bo fence_bo;
1964 struct anv_fence *fence;
1965 struct anv_batch batch;
1966 VkResult result;
1967
1968 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FENCE_CREATE_INFO);
1969
1970 result = anv_bo_pool_alloc(&device->batch_bo_pool, &fence_bo, 4096);
1971 if (result != VK_SUCCESS)
1972 return result;
1973
1974 /* Fences are small. Just store the CPU data structure in the BO. */
1975 fence = fence_bo.map;
1976 fence->bo = fence_bo;
1977
1978 /* Place the batch after the CPU data but on its own cache line. */
1979 const uint32_t batch_offset = align_u32(sizeof(*fence), CACHELINE_SIZE);
1980 batch.next = batch.start = fence->bo.map + batch_offset;
1981 batch.end = fence->bo.map + fence->bo.size;
1982 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1983 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1984
1985 if (!device->info.has_llc) {
1986 assert(((uintptr_t) batch.start & CACHELINE_MASK) == 0);
1987 assert(batch.next - batch.start <= CACHELINE_SIZE);
1988 __builtin_ia32_mfence();
1989 __builtin_ia32_clflush(batch.start);
1990 }
1991
1992 fence->exec2_objects[0].handle = fence->bo.gem_handle;
1993 fence->exec2_objects[0].relocation_count = 0;
1994 fence->exec2_objects[0].relocs_ptr = 0;
1995 fence->exec2_objects[0].alignment = 0;
1996 fence->exec2_objects[0].offset = fence->bo.offset;
1997 fence->exec2_objects[0].flags = 0;
1998 fence->exec2_objects[0].rsvd1 = 0;
1999 fence->exec2_objects[0].rsvd2 = 0;
2000
2001 fence->execbuf.buffers_ptr = (uintptr_t) fence->exec2_objects;
2002 fence->execbuf.buffer_count = 1;
2003 fence->execbuf.batch_start_offset = batch.start - fence->bo.map;
2004 fence->execbuf.batch_len = batch.next - batch.start;
2005 fence->execbuf.cliprects_ptr = 0;
2006 fence->execbuf.num_cliprects = 0;
2007 fence->execbuf.DR1 = 0;
2008 fence->execbuf.DR4 = 0;
2009
2010 fence->execbuf.flags =
2011 I915_EXEC_HANDLE_LUT | I915_EXEC_NO_RELOC | I915_EXEC_RENDER;
2012 fence->execbuf.rsvd1 = device->context_id;
2013 fence->execbuf.rsvd2 = 0;
2014
2015 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
2016 fence->state = ANV_FENCE_STATE_SIGNALED;
2017 } else {
2018 fence->state = ANV_FENCE_STATE_RESET;
2019 }
2020
2021 *pFence = anv_fence_to_handle(fence);
2022
2023 return VK_SUCCESS;
2024 }
2025
2026 void anv_DestroyFence(
2027 VkDevice _device,
2028 VkFence _fence,
2029 const VkAllocationCallbacks* pAllocator)
2030 {
2031 ANV_FROM_HANDLE(anv_device, device, _device);
2032 ANV_FROM_HANDLE(anv_fence, fence, _fence);
2033
2034 if (!fence)
2035 return;
2036
2037 assert(fence->bo.map == fence);
2038 anv_bo_pool_free(&device->batch_bo_pool, &fence->bo);
2039 }
2040
2041 VkResult anv_ResetFences(
2042 VkDevice _device,
2043 uint32_t fenceCount,
2044 const VkFence* pFences)
2045 {
2046 for (uint32_t i = 0; i < fenceCount; i++) {
2047 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
2048 fence->state = ANV_FENCE_STATE_RESET;
2049 }
2050
2051 return VK_SUCCESS;
2052 }
2053
2054 VkResult anv_GetFenceStatus(
2055 VkDevice _device,
2056 VkFence _fence)
2057 {
2058 ANV_FROM_HANDLE(anv_device, device, _device);
2059 ANV_FROM_HANDLE(anv_fence, fence, _fence);
2060
2061 if (unlikely(device->lost))
2062 return VK_ERROR_DEVICE_LOST;
2063
2064 switch (fence->state) {
2065 case ANV_FENCE_STATE_RESET:
2066 /* If it hasn't even been sent off to the GPU yet, it's not ready */
2067 return VK_NOT_READY;
2068
2069 case ANV_FENCE_STATE_SIGNALED:
2070 /* It's been signaled, return success */
2071 return VK_SUCCESS;
2072
2073 case ANV_FENCE_STATE_SUBMITTED: {
2074 VkResult result = anv_device_bo_busy(device, &fence->bo);
2075 if (result == VK_SUCCESS) {
2076 fence->state = ANV_FENCE_STATE_SIGNALED;
2077 return VK_SUCCESS;
2078 } else {
2079 return result;
2080 }
2081 }
2082 default:
2083 unreachable("Invalid fence status");
2084 }
2085 }
2086
2087 #define NSEC_PER_SEC 1000000000
2088 #define INT_TYPE_MAX(type) ((1ull << (sizeof(type) * 8 - 1)) - 1)
2089
2090 VkResult anv_WaitForFences(
2091 VkDevice _device,
2092 uint32_t fenceCount,
2093 const VkFence* pFences,
2094 VkBool32 waitAll,
2095 uint64_t _timeout)
2096 {
2097 ANV_FROM_HANDLE(anv_device, device, _device);
2098 int ret;
2099
2100 if (unlikely(device->lost))
2101 return VK_ERROR_DEVICE_LOST;
2102
2103 /* DRM_IOCTL_I915_GEM_WAIT uses a signed 64 bit timeout and is supposed
2104 * to block indefinitely timeouts <= 0. Unfortunately, this was broken
2105 * for a couple of kernel releases. Since there's no way to know
2106 * whether or not the kernel we're using is one of the broken ones, the
2107 * best we can do is to clamp the timeout to INT64_MAX. This limits the
2108 * maximum timeout from 584 years to 292 years - likely not a big deal.
2109 */
2110 int64_t timeout = MIN2(_timeout, INT64_MAX);
2111
2112 VkResult result = VK_SUCCESS;
2113 uint32_t pending_fences = fenceCount;
2114 while (pending_fences) {
2115 pending_fences = 0;
2116 bool signaled_fences = false;
2117 for (uint32_t i = 0; i < fenceCount; i++) {
2118 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
2119 switch (fence->state) {
2120 case ANV_FENCE_STATE_RESET:
2121 /* This fence hasn't been submitted yet, we'll catch it the next
2122 * time around. Yes, this may mean we dead-loop but, short of
2123 * lots of locking and a condition variable, there's not much that
2124 * we can do about that.
2125 */
2126 pending_fences++;
2127 continue;
2128
2129 case ANV_FENCE_STATE_SIGNALED:
2130 /* This fence is not pending. If waitAll isn't set, we can return
2131 * early. Otherwise, we have to keep going.
2132 */
2133 if (!waitAll) {
2134 result = VK_SUCCESS;
2135 goto done;
2136 }
2137 continue;
2138
2139 case ANV_FENCE_STATE_SUBMITTED:
2140 /* These are the fences we really care about. Go ahead and wait
2141 * on it until we hit a timeout.
2142 */
2143 result = anv_device_wait(device, &fence->bo, timeout);
2144 switch (result) {
2145 case VK_SUCCESS:
2146 fence->state = ANV_FENCE_STATE_SIGNALED;
2147 signaled_fences = true;
2148 if (!waitAll)
2149 goto done;
2150 break;
2151
2152 case VK_TIMEOUT:
2153 goto done;
2154
2155 default:
2156 return result;
2157 }
2158 }
2159 }
2160
2161 if (pending_fences && !signaled_fences) {
2162 /* If we've hit this then someone decided to vkWaitForFences before
2163 * they've actually submitted any of them to a queue. This is a
2164 * fairly pessimal case, so it's ok to lock here and use a standard
2165 * pthreads condition variable.
2166 */
2167 pthread_mutex_lock(&device->mutex);
2168
2169 /* It's possible that some of the fences have changed state since the
2170 * last time we checked. Now that we have the lock, check for
2171 * pending fences again and don't wait if it's changed.
2172 */
2173 uint32_t now_pending_fences = 0;
2174 for (uint32_t i = 0; i < fenceCount; i++) {
2175 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
2176 if (fence->state == ANV_FENCE_STATE_RESET)
2177 now_pending_fences++;
2178 }
2179 assert(now_pending_fences <= pending_fences);
2180
2181 if (now_pending_fences == pending_fences) {
2182 struct timespec before;
2183 clock_gettime(CLOCK_MONOTONIC, &before);
2184
2185 uint32_t abs_nsec = before.tv_nsec + timeout % NSEC_PER_SEC;
2186 uint64_t abs_sec = before.tv_sec + (abs_nsec / NSEC_PER_SEC) +
2187 (timeout / NSEC_PER_SEC);
2188 abs_nsec %= NSEC_PER_SEC;
2189
2190 /* Avoid roll-over in tv_sec on 32-bit systems if the user
2191 * provided timeout is UINT64_MAX
2192 */
2193 struct timespec abstime;
2194 abstime.tv_nsec = abs_nsec;
2195 abstime.tv_sec = MIN2(abs_sec, INT_TYPE_MAX(abstime.tv_sec));
2196
2197 ret = pthread_cond_timedwait(&device->queue_submit,
2198 &device->mutex, &abstime);
2199 assert(ret != EINVAL);
2200
2201 struct timespec after;
2202 clock_gettime(CLOCK_MONOTONIC, &after);
2203 uint64_t time_elapsed =
2204 ((uint64_t)after.tv_sec * NSEC_PER_SEC + after.tv_nsec) -
2205 ((uint64_t)before.tv_sec * NSEC_PER_SEC + before.tv_nsec);
2206
2207 if (time_elapsed >= timeout) {
2208 pthread_mutex_unlock(&device->mutex);
2209 result = VK_TIMEOUT;
2210 goto done;
2211 }
2212
2213 timeout -= time_elapsed;
2214 }
2215
2216 pthread_mutex_unlock(&device->mutex);
2217 }
2218 }
2219
2220 done:
2221 if (unlikely(device->lost))
2222 return VK_ERROR_DEVICE_LOST;
2223
2224 return result;
2225 }
2226
2227 // Queue semaphore functions
2228
2229 VkResult anv_CreateSemaphore(
2230 VkDevice device,
2231 const VkSemaphoreCreateInfo* pCreateInfo,
2232 const VkAllocationCallbacks* pAllocator,
2233 VkSemaphore* pSemaphore)
2234 {
2235 /* The DRM execbuffer ioctl always execute in-oder, even between different
2236 * rings. As such, there's nothing to do for the user space semaphore.
2237 */
2238
2239 *pSemaphore = (VkSemaphore)1;
2240
2241 return VK_SUCCESS;
2242 }
2243
2244 void anv_DestroySemaphore(
2245 VkDevice device,
2246 VkSemaphore semaphore,
2247 const VkAllocationCallbacks* pAllocator)
2248 {
2249 }
2250
2251 // Event functions
2252
2253 VkResult anv_CreateEvent(
2254 VkDevice _device,
2255 const VkEventCreateInfo* pCreateInfo,
2256 const VkAllocationCallbacks* pAllocator,
2257 VkEvent* pEvent)
2258 {
2259 ANV_FROM_HANDLE(anv_device, device, _device);
2260 struct anv_state state;
2261 struct anv_event *event;
2262
2263 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2264
2265 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2266 sizeof(*event), 8);
2267 event = state.map;
2268 event->state = state;
2269 event->semaphore = VK_EVENT_RESET;
2270
2271 if (!device->info.has_llc) {
2272 /* Make sure the writes we're flushing have landed. */
2273 __builtin_ia32_mfence();
2274 __builtin_ia32_clflush(event);
2275 }
2276
2277 *pEvent = anv_event_to_handle(event);
2278
2279 return VK_SUCCESS;
2280 }
2281
2282 void anv_DestroyEvent(
2283 VkDevice _device,
2284 VkEvent _event,
2285 const VkAllocationCallbacks* pAllocator)
2286 {
2287 ANV_FROM_HANDLE(anv_device, device, _device);
2288 ANV_FROM_HANDLE(anv_event, event, _event);
2289
2290 if (!event)
2291 return;
2292
2293 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2294 }
2295
2296 VkResult anv_GetEventStatus(
2297 VkDevice _device,
2298 VkEvent _event)
2299 {
2300 ANV_FROM_HANDLE(anv_device, device, _device);
2301 ANV_FROM_HANDLE(anv_event, event, _event);
2302
2303 if (unlikely(device->lost))
2304 return VK_ERROR_DEVICE_LOST;
2305
2306 if (!device->info.has_llc) {
2307 /* Invalidate read cache before reading event written by GPU. */
2308 __builtin_ia32_clflush(event);
2309 __builtin_ia32_mfence();
2310
2311 }
2312
2313 return event->semaphore;
2314 }
2315
2316 VkResult anv_SetEvent(
2317 VkDevice _device,
2318 VkEvent _event)
2319 {
2320 ANV_FROM_HANDLE(anv_device, device, _device);
2321 ANV_FROM_HANDLE(anv_event, event, _event);
2322
2323 event->semaphore = VK_EVENT_SET;
2324
2325 if (!device->info.has_llc) {
2326 /* Make sure the writes we're flushing have landed. */
2327 __builtin_ia32_mfence();
2328 __builtin_ia32_clflush(event);
2329 }
2330
2331 return VK_SUCCESS;
2332 }
2333
2334 VkResult anv_ResetEvent(
2335 VkDevice _device,
2336 VkEvent _event)
2337 {
2338 ANV_FROM_HANDLE(anv_device, device, _device);
2339 ANV_FROM_HANDLE(anv_event, event, _event);
2340
2341 event->semaphore = VK_EVENT_RESET;
2342
2343 if (!device->info.has_llc) {
2344 /* Make sure the writes we're flushing have landed. */
2345 __builtin_ia32_mfence();
2346 __builtin_ia32_clflush(event);
2347 }
2348
2349 return VK_SUCCESS;
2350 }
2351
2352 // Buffer functions
2353
2354 VkResult anv_CreateBuffer(
2355 VkDevice _device,
2356 const VkBufferCreateInfo* pCreateInfo,
2357 const VkAllocationCallbacks* pAllocator,
2358 VkBuffer* pBuffer)
2359 {
2360 ANV_FROM_HANDLE(anv_device, device, _device);
2361 struct anv_buffer *buffer;
2362
2363 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2364
2365 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2366 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2367 if (buffer == NULL)
2368 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2369
2370 buffer->size = pCreateInfo->size;
2371 buffer->usage = pCreateInfo->usage;
2372 buffer->bo = NULL;
2373 buffer->offset = 0;
2374
2375 *pBuffer = anv_buffer_to_handle(buffer);
2376
2377 return VK_SUCCESS;
2378 }
2379
2380 void anv_DestroyBuffer(
2381 VkDevice _device,
2382 VkBuffer _buffer,
2383 const VkAllocationCallbacks* pAllocator)
2384 {
2385 ANV_FROM_HANDLE(anv_device, device, _device);
2386 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2387
2388 if (!buffer)
2389 return;
2390
2391 vk_free2(&device->alloc, pAllocator, buffer);
2392 }
2393
2394 void
2395 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2396 enum isl_format format,
2397 uint32_t offset, uint32_t range, uint32_t stride)
2398 {
2399 isl_buffer_fill_state(&device->isl_dev, state.map,
2400 .address = offset,
2401 .mocs = device->default_mocs,
2402 .size = range,
2403 .format = format,
2404 .stride = stride);
2405
2406 anv_state_flush(device, state);
2407 }
2408
2409 void anv_DestroySampler(
2410 VkDevice _device,
2411 VkSampler _sampler,
2412 const VkAllocationCallbacks* pAllocator)
2413 {
2414 ANV_FROM_HANDLE(anv_device, device, _device);
2415 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2416
2417 if (!sampler)
2418 return;
2419
2420 vk_free2(&device->alloc, pAllocator, sampler);
2421 }
2422
2423 VkResult anv_CreateFramebuffer(
2424 VkDevice _device,
2425 const VkFramebufferCreateInfo* pCreateInfo,
2426 const VkAllocationCallbacks* pAllocator,
2427 VkFramebuffer* pFramebuffer)
2428 {
2429 ANV_FROM_HANDLE(anv_device, device, _device);
2430 struct anv_framebuffer *framebuffer;
2431
2432 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2433
2434 size_t size = sizeof(*framebuffer) +
2435 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2436 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2437 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2438 if (framebuffer == NULL)
2439 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2440
2441 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2442 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2443 VkImageView _iview = pCreateInfo->pAttachments[i];
2444 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2445 }
2446
2447 framebuffer->width = pCreateInfo->width;
2448 framebuffer->height = pCreateInfo->height;
2449 framebuffer->layers = pCreateInfo->layers;
2450
2451 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2452
2453 return VK_SUCCESS;
2454 }
2455
2456 void anv_DestroyFramebuffer(
2457 VkDevice _device,
2458 VkFramebuffer _fb,
2459 const VkAllocationCallbacks* pAllocator)
2460 {
2461 ANV_FROM_HANDLE(anv_device, device, _device);
2462 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2463
2464 if (!fb)
2465 return;
2466
2467 vk_free2(&device->alloc, pAllocator, fb);
2468 }
2469
2470 /* vk_icd.h does not declare this function, so we declare it here to
2471 * suppress Wmissing-prototypes.
2472 */
2473 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2474 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2475
2476 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2477 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2478 {
2479 /* For the full details on loader interface versioning, see
2480 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2481 * What follows is a condensed summary, to help you navigate the large and
2482 * confusing official doc.
2483 *
2484 * - Loader interface v0 is incompatible with later versions. We don't
2485 * support it.
2486 *
2487 * - In loader interface v1:
2488 * - The first ICD entrypoint called by the loader is
2489 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2490 * entrypoint.
2491 * - The ICD must statically expose no other Vulkan symbol unless it is
2492 * linked with -Bsymbolic.
2493 * - Each dispatchable Vulkan handle created by the ICD must be
2494 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2495 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2496 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2497 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2498 * such loader-managed surfaces.
2499 *
2500 * - Loader interface v2 differs from v1 in:
2501 * - The first ICD entrypoint called by the loader is
2502 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2503 * statically expose this entrypoint.
2504 *
2505 * - Loader interface v3 differs from v2 in:
2506 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2507 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2508 * because the loader no longer does so.
2509 */
2510 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2511 return VK_SUCCESS;
2512 }