anv: Implement VK_KHX_external_semaphore
[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_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
306 .specVersion = 1,
307 },
308 {
309 .extensionName = VK_KHR_SURFACE_EXTENSION_NAME,
310 .specVersion = 25,
311 },
312 #ifdef VK_USE_PLATFORM_WAYLAND_KHR
313 {
314 .extensionName = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME,
315 .specVersion = 5,
316 },
317 #endif
318 #ifdef VK_USE_PLATFORM_XCB_KHR
319 {
320 .extensionName = VK_KHR_XCB_SURFACE_EXTENSION_NAME,
321 .specVersion = 6,
322 },
323 #endif
324 #ifdef VK_USE_PLATFORM_XLIB_KHR
325 {
326 .extensionName = VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
327 .specVersion = 6,
328 },
329 #endif
330 {
331 .extensionName = VK_KHX_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME,
332 .specVersion = 1,
333 },
334 {
335 .extensionName = VK_KHX_EXTERNAL_SEMAPHORE_CAPABILITIES_EXTENSION_NAME,
336 .specVersion = 1,
337 },
338 };
339
340 static const VkExtensionProperties device_extensions[] = {
341 {
342 .extensionName = VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME,
343 .specVersion = 1,
344 },
345 {
346 .extensionName = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME,
347 .specVersion = 1,
348 },
349 {
350 .extensionName = VK_KHR_MAINTENANCE1_EXTENSION_NAME,
351 .specVersion = 1,
352 },
353 {
354 .extensionName = VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME,
355 .specVersion = 1,
356 },
357 {
358 .extensionName = VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME,
359 .specVersion = 1,
360 },
361 {
362 .extensionName = VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME,
363 .specVersion = 1,
364 },
365 {
366 .extensionName = VK_KHR_SWAPCHAIN_EXTENSION_NAME,
367 .specVersion = 68,
368 },
369 {
370 .extensionName = VK_KHX_EXTERNAL_MEMORY_EXTENSION_NAME,
371 .specVersion = 1,
372 },
373 {
374 .extensionName = VK_KHX_EXTERNAL_MEMORY_FD_EXTENSION_NAME,
375 .specVersion = 1,
376 },
377 {
378 .extensionName = VK_KHX_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
379 .specVersion = 1,
380 },
381 {
382 .extensionName = VK_KHX_MULTIVIEW_EXTENSION_NAME,
383 .specVersion = 1,
384 },
385 };
386
387 static void *
388 default_alloc_func(void *pUserData, size_t size, size_t align,
389 VkSystemAllocationScope allocationScope)
390 {
391 return malloc(size);
392 }
393
394 static void *
395 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
396 size_t align, VkSystemAllocationScope allocationScope)
397 {
398 return realloc(pOriginal, size);
399 }
400
401 static void
402 default_free_func(void *pUserData, void *pMemory)
403 {
404 free(pMemory);
405 }
406
407 static const VkAllocationCallbacks default_alloc = {
408 .pUserData = NULL,
409 .pfnAllocation = default_alloc_func,
410 .pfnReallocation = default_realloc_func,
411 .pfnFree = default_free_func,
412 };
413
414 VkResult anv_CreateInstance(
415 const VkInstanceCreateInfo* pCreateInfo,
416 const VkAllocationCallbacks* pAllocator,
417 VkInstance* pInstance)
418 {
419 struct anv_instance *instance;
420
421 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
422
423 uint32_t client_version;
424 if (pCreateInfo->pApplicationInfo &&
425 pCreateInfo->pApplicationInfo->apiVersion != 0) {
426 client_version = pCreateInfo->pApplicationInfo->apiVersion;
427 } else {
428 client_version = VK_MAKE_VERSION(1, 0, 0);
429 }
430
431 if (VK_MAKE_VERSION(1, 0, 0) > client_version ||
432 client_version > VK_MAKE_VERSION(1, 0, 0xfff)) {
433 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
434 "Client requested version %d.%d.%d",
435 VK_VERSION_MAJOR(client_version),
436 VK_VERSION_MINOR(client_version),
437 VK_VERSION_PATCH(client_version));
438 }
439
440 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
441 bool found = false;
442 for (uint32_t j = 0; j < ARRAY_SIZE(global_extensions); j++) {
443 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
444 global_extensions[j].extensionName) == 0) {
445 found = true;
446 break;
447 }
448 }
449 if (!found)
450 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
451 }
452
453 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
454 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
455 if (!instance)
456 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
457
458 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
459
460 if (pAllocator)
461 instance->alloc = *pAllocator;
462 else
463 instance->alloc = default_alloc;
464
465 instance->apiVersion = client_version;
466 instance->physicalDeviceCount = -1;
467
468 _mesa_locale_init();
469
470 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
471
472 *pInstance = anv_instance_to_handle(instance);
473
474 return VK_SUCCESS;
475 }
476
477 void anv_DestroyInstance(
478 VkInstance _instance,
479 const VkAllocationCallbacks* pAllocator)
480 {
481 ANV_FROM_HANDLE(anv_instance, instance, _instance);
482
483 if (!instance)
484 return;
485
486 if (instance->physicalDeviceCount > 0) {
487 /* We support at most one physical device. */
488 assert(instance->physicalDeviceCount == 1);
489 anv_physical_device_finish(&instance->physicalDevice);
490 }
491
492 VG(VALGRIND_DESTROY_MEMPOOL(instance));
493
494 _mesa_locale_fini();
495
496 vk_free(&instance->alloc, instance);
497 }
498
499 static VkResult
500 anv_enumerate_devices(struct anv_instance *instance)
501 {
502 /* TODO: Check for more devices ? */
503 drmDevicePtr devices[8];
504 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
505 int max_devices;
506
507 instance->physicalDeviceCount = 0;
508
509 max_devices = drmGetDevices2(0, devices, sizeof(devices));
510 if (max_devices < 1)
511 return VK_ERROR_INCOMPATIBLE_DRIVER;
512
513 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
514 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
515 devices[i]->bustype == DRM_BUS_PCI &&
516 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
517
518 result = anv_physical_device_init(&instance->physicalDevice,
519 instance,
520 devices[i]->nodes[DRM_NODE_RENDER]);
521 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
522 break;
523 }
524 }
525
526 if (result == VK_SUCCESS)
527 instance->physicalDeviceCount = 1;
528
529 return result;
530 }
531
532
533 VkResult anv_EnumeratePhysicalDevices(
534 VkInstance _instance,
535 uint32_t* pPhysicalDeviceCount,
536 VkPhysicalDevice* pPhysicalDevices)
537 {
538 ANV_FROM_HANDLE(anv_instance, instance, _instance);
539 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
540 VkResult result;
541
542 if (instance->physicalDeviceCount < 0) {
543 result = anv_enumerate_devices(instance);
544 if (result != VK_SUCCESS &&
545 result != VK_ERROR_INCOMPATIBLE_DRIVER)
546 return result;
547 }
548
549 if (instance->physicalDeviceCount > 0) {
550 assert(instance->physicalDeviceCount == 1);
551 vk_outarray_append(&out, i) {
552 *i = anv_physical_device_to_handle(&instance->physicalDevice);
553 }
554 }
555
556 return vk_outarray_status(&out);
557 }
558
559 void anv_GetPhysicalDeviceFeatures(
560 VkPhysicalDevice physicalDevice,
561 VkPhysicalDeviceFeatures* pFeatures)
562 {
563 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
564
565 *pFeatures = (VkPhysicalDeviceFeatures) {
566 .robustBufferAccess = true,
567 .fullDrawIndexUint32 = true,
568 .imageCubeArray = true,
569 .independentBlend = true,
570 .geometryShader = true,
571 .tessellationShader = true,
572 .sampleRateShading = true,
573 .dualSrcBlend = true,
574 .logicOp = true,
575 .multiDrawIndirect = true,
576 .drawIndirectFirstInstance = true,
577 .depthClamp = true,
578 .depthBiasClamp = true,
579 .fillModeNonSolid = true,
580 .depthBounds = false,
581 .wideLines = true,
582 .largePoints = true,
583 .alphaToOne = true,
584 .multiViewport = true,
585 .samplerAnisotropy = true,
586 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
587 pdevice->info.is_baytrail,
588 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
589 .textureCompressionBC = true,
590 .occlusionQueryPrecise = true,
591 .pipelineStatisticsQuery = true,
592 .fragmentStoresAndAtomics = true,
593 .shaderTessellationAndGeometryPointSize = true,
594 .shaderImageGatherExtended = true,
595 .shaderStorageImageExtendedFormats = true,
596 .shaderStorageImageMultisample = false,
597 .shaderStorageImageReadWithoutFormat = false,
598 .shaderStorageImageWriteWithoutFormat = true,
599 .shaderUniformBufferArrayDynamicIndexing = true,
600 .shaderSampledImageArrayDynamicIndexing = true,
601 .shaderStorageBufferArrayDynamicIndexing = true,
602 .shaderStorageImageArrayDynamicIndexing = true,
603 .shaderClipDistance = true,
604 .shaderCullDistance = true,
605 .shaderFloat64 = pdevice->info.gen >= 8,
606 .shaderInt64 = pdevice->info.gen >= 8,
607 .shaderInt16 = false,
608 .shaderResourceMinLod = false,
609 .variableMultisampleRate = false,
610 .inheritedQueries = true,
611 };
612
613 /* We can't do image stores in vec4 shaders */
614 pFeatures->vertexPipelineStoresAndAtomics =
615 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
616 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
617 }
618
619 void anv_GetPhysicalDeviceFeatures2KHR(
620 VkPhysicalDevice physicalDevice,
621 VkPhysicalDeviceFeatures2KHR* pFeatures)
622 {
623 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
624
625 vk_foreach_struct(ext, pFeatures->pNext) {
626 switch (ext->sType) {
627 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHX: {
628 VkPhysicalDeviceMultiviewFeaturesKHX *features =
629 (VkPhysicalDeviceMultiviewFeaturesKHX *)ext;
630 features->multiview = true;
631 features->multiviewGeometryShader = true;
632 features->multiviewTessellationShader = true;
633 break;
634 }
635
636 default:
637 anv_debug_ignored_stype(ext->sType);
638 break;
639 }
640 }
641 }
642
643 void anv_GetPhysicalDeviceProperties(
644 VkPhysicalDevice physicalDevice,
645 VkPhysicalDeviceProperties* pProperties)
646 {
647 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
648 const struct gen_device_info *devinfo = &pdevice->info;
649
650 /* See assertions made when programming the buffer surface state. */
651 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
652 (1ul << 30) : (1ul << 27);
653
654 VkSampleCountFlags sample_counts =
655 isl_device_get_sample_counts(&pdevice->isl_dev);
656
657 VkPhysicalDeviceLimits limits = {
658 .maxImageDimension1D = (1 << 14),
659 .maxImageDimension2D = (1 << 14),
660 .maxImageDimension3D = (1 << 11),
661 .maxImageDimensionCube = (1 << 14),
662 .maxImageArrayLayers = (1 << 11),
663 .maxTexelBufferElements = 128 * 1024 * 1024,
664 .maxUniformBufferRange = (1ul << 27),
665 .maxStorageBufferRange = max_raw_buffer_sz,
666 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
667 .maxMemoryAllocationCount = UINT32_MAX,
668 .maxSamplerAllocationCount = 64 * 1024,
669 .bufferImageGranularity = 64, /* A cache line */
670 .sparseAddressSpaceSize = 0,
671 .maxBoundDescriptorSets = MAX_SETS,
672 .maxPerStageDescriptorSamplers = 64,
673 .maxPerStageDescriptorUniformBuffers = 64,
674 .maxPerStageDescriptorStorageBuffers = 64,
675 .maxPerStageDescriptorSampledImages = 64,
676 .maxPerStageDescriptorStorageImages = 64,
677 .maxPerStageDescriptorInputAttachments = 64,
678 .maxPerStageResources = 128,
679 .maxDescriptorSetSamplers = 256,
680 .maxDescriptorSetUniformBuffers = 256,
681 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
682 .maxDescriptorSetStorageBuffers = 256,
683 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
684 .maxDescriptorSetSampledImages = 256,
685 .maxDescriptorSetStorageImages = 256,
686 .maxDescriptorSetInputAttachments = 256,
687 .maxVertexInputAttributes = MAX_VBS,
688 .maxVertexInputBindings = MAX_VBS,
689 .maxVertexInputAttributeOffset = 2047,
690 .maxVertexInputBindingStride = 2048,
691 .maxVertexOutputComponents = 128,
692 .maxTessellationGenerationLevel = 64,
693 .maxTessellationPatchSize = 32,
694 .maxTessellationControlPerVertexInputComponents = 128,
695 .maxTessellationControlPerVertexOutputComponents = 128,
696 .maxTessellationControlPerPatchOutputComponents = 128,
697 .maxTessellationControlTotalOutputComponents = 2048,
698 .maxTessellationEvaluationInputComponents = 128,
699 .maxTessellationEvaluationOutputComponents = 128,
700 .maxGeometryShaderInvocations = 32,
701 .maxGeometryInputComponents = 64,
702 .maxGeometryOutputComponents = 128,
703 .maxGeometryOutputVertices = 256,
704 .maxGeometryTotalOutputComponents = 1024,
705 .maxFragmentInputComponents = 128,
706 .maxFragmentOutputAttachments = 8,
707 .maxFragmentDualSrcAttachments = 1,
708 .maxFragmentCombinedOutputResources = 8,
709 .maxComputeSharedMemorySize = 32768,
710 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
711 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
712 .maxComputeWorkGroupSize = {
713 16 * devinfo->max_cs_threads,
714 16 * devinfo->max_cs_threads,
715 16 * devinfo->max_cs_threads,
716 },
717 .subPixelPrecisionBits = 4 /* FIXME */,
718 .subTexelPrecisionBits = 4 /* FIXME */,
719 .mipmapPrecisionBits = 4 /* FIXME */,
720 .maxDrawIndexedIndexValue = UINT32_MAX,
721 .maxDrawIndirectCount = UINT32_MAX,
722 .maxSamplerLodBias = 16,
723 .maxSamplerAnisotropy = 16,
724 .maxViewports = MAX_VIEWPORTS,
725 .maxViewportDimensions = { (1 << 14), (1 << 14) },
726 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
727 .viewportSubPixelBits = 13, /* We take a float? */
728 .minMemoryMapAlignment = 4096, /* A page */
729 .minTexelBufferOffsetAlignment = 1,
730 .minUniformBufferOffsetAlignment = 16,
731 .minStorageBufferOffsetAlignment = 4,
732 .minTexelOffset = -8,
733 .maxTexelOffset = 7,
734 .minTexelGatherOffset = -32,
735 .maxTexelGatherOffset = 31,
736 .minInterpolationOffset = -0.5,
737 .maxInterpolationOffset = 0.4375,
738 .subPixelInterpolationOffsetBits = 4,
739 .maxFramebufferWidth = (1 << 14),
740 .maxFramebufferHeight = (1 << 14),
741 .maxFramebufferLayers = (1 << 11),
742 .framebufferColorSampleCounts = sample_counts,
743 .framebufferDepthSampleCounts = sample_counts,
744 .framebufferStencilSampleCounts = sample_counts,
745 .framebufferNoAttachmentsSampleCounts = sample_counts,
746 .maxColorAttachments = MAX_RTS,
747 .sampledImageColorSampleCounts = sample_counts,
748 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
749 .sampledImageDepthSampleCounts = sample_counts,
750 .sampledImageStencilSampleCounts = sample_counts,
751 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
752 .maxSampleMaskWords = 1,
753 .timestampComputeAndGraphics = false,
754 .timestampPeriod = devinfo->timebase_scale,
755 .maxClipDistances = 8,
756 .maxCullDistances = 8,
757 .maxCombinedClipAndCullDistances = 8,
758 .discreteQueuePriorities = 1,
759 .pointSizeRange = { 0.125, 255.875 },
760 .lineWidthRange = { 0.0, 7.9921875 },
761 .pointSizeGranularity = (1.0 / 8.0),
762 .lineWidthGranularity = (1.0 / 128.0),
763 .strictLines = false, /* FINISHME */
764 .standardSampleLocations = true,
765 .optimalBufferCopyOffsetAlignment = 128,
766 .optimalBufferCopyRowPitchAlignment = 128,
767 .nonCoherentAtomSize = 64,
768 };
769
770 *pProperties = (VkPhysicalDeviceProperties) {
771 .apiVersion = VK_MAKE_VERSION(1, 0, 42),
772 .driverVersion = 1,
773 .vendorID = 0x8086,
774 .deviceID = pdevice->chipset_id,
775 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
776 .limits = limits,
777 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
778 };
779
780 strcpy(pProperties->deviceName, pdevice->name);
781 memcpy(pProperties->pipelineCacheUUID,
782 pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
783 }
784
785 void anv_GetPhysicalDeviceProperties2KHR(
786 VkPhysicalDevice physicalDevice,
787 VkPhysicalDeviceProperties2KHR* pProperties)
788 {
789 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
790
791 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
792
793 vk_foreach_struct(ext, pProperties->pNext) {
794 switch (ext->sType) {
795 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
796 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
797 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
798
799 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
800 break;
801 }
802
803 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHX: {
804 VkPhysicalDeviceIDPropertiesKHX *id_props =
805 (VkPhysicalDeviceIDPropertiesKHX *)ext;
806 memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
807 memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
808 /* The LUID is for Windows. */
809 id_props->deviceLUIDValid = false;
810 break;
811 }
812
813 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHX: {
814 VkPhysicalDeviceMultiviewPropertiesKHX *properties =
815 (VkPhysicalDeviceMultiviewPropertiesKHX *)ext;
816 properties->maxMultiviewViewCount = 16;
817 properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
818 break;
819 }
820
821 default:
822 anv_debug_ignored_stype(ext->sType);
823 break;
824 }
825 }
826 }
827
828 /* We support exactly one queue family. */
829 static const VkQueueFamilyProperties
830 anv_queue_family_properties = {
831 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
832 VK_QUEUE_COMPUTE_BIT |
833 VK_QUEUE_TRANSFER_BIT,
834 .queueCount = 1,
835 .timestampValidBits = 36, /* XXX: Real value here */
836 .minImageTransferGranularity = { 1, 1, 1 },
837 };
838
839 void anv_GetPhysicalDeviceQueueFamilyProperties(
840 VkPhysicalDevice physicalDevice,
841 uint32_t* pCount,
842 VkQueueFamilyProperties* pQueueFamilyProperties)
843 {
844 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
845
846 vk_outarray_append(&out, p) {
847 *p = anv_queue_family_properties;
848 }
849 }
850
851 void anv_GetPhysicalDeviceQueueFamilyProperties2KHR(
852 VkPhysicalDevice physicalDevice,
853 uint32_t* pQueueFamilyPropertyCount,
854 VkQueueFamilyProperties2KHR* pQueueFamilyProperties)
855 {
856
857 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
858
859 vk_outarray_append(&out, p) {
860 p->queueFamilyProperties = anv_queue_family_properties;
861
862 vk_foreach_struct(s, p->pNext) {
863 anv_debug_ignored_stype(s->sType);
864 }
865 }
866 }
867
868 void anv_GetPhysicalDeviceMemoryProperties(
869 VkPhysicalDevice physicalDevice,
870 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
871 {
872 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
873
874 if (physical_device->info.has_llc) {
875 /* Big core GPUs share LLC with the CPU and thus one memory type can be
876 * both cached and coherent at the same time.
877 */
878 pMemoryProperties->memoryTypeCount = 1;
879 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
880 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
881 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
882 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
883 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
884 .heapIndex = 0,
885 };
886 } else {
887 /* The spec requires that we expose a host-visible, coherent memory
888 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
889 * to give the application a choice between cached, but not coherent and
890 * coherent but uncached (WC though).
891 */
892 pMemoryProperties->memoryTypeCount = 2;
893 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
894 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
895 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
896 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
897 .heapIndex = 0,
898 };
899 pMemoryProperties->memoryTypes[1] = (VkMemoryType) {
900 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
901 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
902 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
903 .heapIndex = 0,
904 };
905 }
906
907 pMemoryProperties->memoryHeapCount = 1;
908 pMemoryProperties->memoryHeaps[0] = (VkMemoryHeap) {
909 .size = physical_device->heap_size,
910 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
911 };
912 }
913
914 void anv_GetPhysicalDeviceMemoryProperties2KHR(
915 VkPhysicalDevice physicalDevice,
916 VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties)
917 {
918 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
919 &pMemoryProperties->memoryProperties);
920
921 vk_foreach_struct(ext, pMemoryProperties->pNext) {
922 switch (ext->sType) {
923 default:
924 anv_debug_ignored_stype(ext->sType);
925 break;
926 }
927 }
928 }
929
930 PFN_vkVoidFunction anv_GetInstanceProcAddr(
931 VkInstance instance,
932 const char* pName)
933 {
934 return anv_lookup_entrypoint(NULL, pName);
935 }
936
937 /* With version 1+ of the loader interface the ICD should expose
938 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
939 */
940 PUBLIC
941 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
942 VkInstance instance,
943 const char* pName);
944
945 PUBLIC
946 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
947 VkInstance instance,
948 const char* pName)
949 {
950 return anv_GetInstanceProcAddr(instance, pName);
951 }
952
953 PFN_vkVoidFunction anv_GetDeviceProcAddr(
954 VkDevice _device,
955 const char* pName)
956 {
957 ANV_FROM_HANDLE(anv_device, device, _device);
958 return anv_lookup_entrypoint(&device->info, pName);
959 }
960
961 static void
962 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
963 {
964 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
965 queue->device = device;
966 queue->pool = &device->surface_state_pool;
967 }
968
969 static void
970 anv_queue_finish(struct anv_queue *queue)
971 {
972 }
973
974 static struct anv_state
975 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
976 {
977 struct anv_state state;
978
979 state = anv_state_pool_alloc(pool, size, align);
980 memcpy(state.map, p, size);
981
982 anv_state_flush(pool->block_pool->device, state);
983
984 return state;
985 }
986
987 struct gen8_border_color {
988 union {
989 float float32[4];
990 uint32_t uint32[4];
991 };
992 /* Pad out to 64 bytes */
993 uint32_t _pad[12];
994 };
995
996 static void
997 anv_device_init_border_colors(struct anv_device *device)
998 {
999 static const struct gen8_border_color border_colors[] = {
1000 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
1001 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
1002 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
1003 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
1004 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
1005 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
1006 };
1007
1008 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
1009 sizeof(border_colors), 64,
1010 border_colors);
1011 }
1012
1013 VkResult anv_CreateDevice(
1014 VkPhysicalDevice physicalDevice,
1015 const VkDeviceCreateInfo* pCreateInfo,
1016 const VkAllocationCallbacks* pAllocator,
1017 VkDevice* pDevice)
1018 {
1019 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
1020 VkResult result;
1021 struct anv_device *device;
1022
1023 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
1024
1025 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1026 bool found = false;
1027 for (uint32_t j = 0; j < ARRAY_SIZE(device_extensions); j++) {
1028 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1029 device_extensions[j].extensionName) == 0) {
1030 found = true;
1031 break;
1032 }
1033 }
1034 if (!found)
1035 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1036 }
1037
1038 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1039 sizeof(*device), 8,
1040 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1041 if (!device)
1042 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1043
1044 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1045 device->instance = physical_device->instance;
1046 device->chipset_id = physical_device->chipset_id;
1047 device->lost = false;
1048
1049 if (pAllocator)
1050 device->alloc = *pAllocator;
1051 else
1052 device->alloc = physical_device->instance->alloc;
1053
1054 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1055 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1056 if (device->fd == -1) {
1057 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1058 goto fail_device;
1059 }
1060
1061 device->context_id = anv_gem_create_context(device);
1062 if (device->context_id == -1) {
1063 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1064 goto fail_fd;
1065 }
1066
1067 device->info = physical_device->info;
1068 device->isl_dev = physical_device->isl_dev;
1069
1070 /* On Broadwell and later, we can use batch chaining to more efficiently
1071 * implement growing command buffers. Prior to Haswell, the kernel
1072 * command parser gets in the way and we have to fall back to growing
1073 * the batch.
1074 */
1075 device->can_chain_batches = device->info.gen >= 8;
1076
1077 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1078 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1079
1080 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1081 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1082 goto fail_context_id;
1083 }
1084
1085 pthread_condattr_t condattr;
1086 if (pthread_condattr_init(&condattr) != 0) {
1087 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1088 goto fail_mutex;
1089 }
1090 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1091 pthread_condattr_destroy(&condattr);
1092 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1093 goto fail_mutex;
1094 }
1095 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1096 pthread_condattr_destroy(&condattr);
1097 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1098 goto fail_mutex;
1099 }
1100 pthread_condattr_destroy(&condattr);
1101
1102 anv_bo_pool_init(&device->batch_bo_pool, device);
1103
1104 result = anv_bo_cache_init(&device->bo_cache);
1105 if (result != VK_SUCCESS)
1106 goto fail_batch_bo_pool;
1107
1108 result = anv_block_pool_init(&device->dynamic_state_block_pool, device,
1109 16384);
1110 if (result != VK_SUCCESS)
1111 goto fail_bo_cache;
1112
1113 anv_state_pool_init(&device->dynamic_state_pool,
1114 &device->dynamic_state_block_pool);
1115
1116 result = anv_block_pool_init(&device->instruction_block_pool, device,
1117 1024 * 1024);
1118 if (result != VK_SUCCESS)
1119 goto fail_dynamic_state_pool;
1120
1121 anv_state_pool_init(&device->instruction_state_pool,
1122 &device->instruction_block_pool);
1123
1124 result = anv_block_pool_init(&device->surface_state_block_pool, device,
1125 4096);
1126 if (result != VK_SUCCESS)
1127 goto fail_instruction_state_pool;
1128
1129 anv_state_pool_init(&device->surface_state_pool,
1130 &device->surface_state_block_pool);
1131
1132 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1133 if (result != VK_SUCCESS)
1134 goto fail_surface_state_pool;
1135
1136 anv_scratch_pool_init(device, &device->scratch_pool);
1137
1138 anv_queue_init(device, &device->queue);
1139
1140 switch (device->info.gen) {
1141 case 7:
1142 if (!device->info.is_haswell)
1143 result = gen7_init_device_state(device);
1144 else
1145 result = gen75_init_device_state(device);
1146 break;
1147 case 8:
1148 result = gen8_init_device_state(device);
1149 break;
1150 case 9:
1151 result = gen9_init_device_state(device);
1152 break;
1153 default:
1154 /* Shouldn't get here as we don't create physical devices for any other
1155 * gens. */
1156 unreachable("unhandled gen");
1157 }
1158 if (result != VK_SUCCESS)
1159 goto fail_workaround_bo;
1160
1161 anv_device_init_blorp(device);
1162
1163 anv_device_init_border_colors(device);
1164
1165 *pDevice = anv_device_to_handle(device);
1166
1167 return VK_SUCCESS;
1168
1169 fail_workaround_bo:
1170 anv_queue_finish(&device->queue);
1171 anv_scratch_pool_finish(device, &device->scratch_pool);
1172 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1173 anv_gem_close(device, device->workaround_bo.gem_handle);
1174 fail_surface_state_pool:
1175 anv_state_pool_finish(&device->surface_state_pool);
1176 anv_block_pool_finish(&device->surface_state_block_pool);
1177 fail_instruction_state_pool:
1178 anv_state_pool_finish(&device->instruction_state_pool);
1179 anv_block_pool_finish(&device->instruction_block_pool);
1180 fail_dynamic_state_pool:
1181 anv_state_pool_finish(&device->dynamic_state_pool);
1182 anv_block_pool_finish(&device->dynamic_state_block_pool);
1183 fail_bo_cache:
1184 anv_bo_cache_finish(&device->bo_cache);
1185 fail_batch_bo_pool:
1186 anv_bo_pool_finish(&device->batch_bo_pool);
1187 pthread_cond_destroy(&device->queue_submit);
1188 fail_mutex:
1189 pthread_mutex_destroy(&device->mutex);
1190 fail_context_id:
1191 anv_gem_destroy_context(device, device->context_id);
1192 fail_fd:
1193 close(device->fd);
1194 fail_device:
1195 vk_free(&device->alloc, device);
1196
1197 return result;
1198 }
1199
1200 void anv_DestroyDevice(
1201 VkDevice _device,
1202 const VkAllocationCallbacks* pAllocator)
1203 {
1204 ANV_FROM_HANDLE(anv_device, device, _device);
1205
1206 if (!device)
1207 return;
1208
1209 anv_device_finish_blorp(device);
1210
1211 anv_queue_finish(&device->queue);
1212
1213 #ifdef HAVE_VALGRIND
1214 /* We only need to free these to prevent valgrind errors. The backing
1215 * BO will go away in a couple of lines so we don't actually leak.
1216 */
1217 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1218 #endif
1219
1220 anv_scratch_pool_finish(device, &device->scratch_pool);
1221
1222 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1223 anv_gem_close(device, device->workaround_bo.gem_handle);
1224
1225 anv_state_pool_finish(&device->surface_state_pool);
1226 anv_block_pool_finish(&device->surface_state_block_pool);
1227 anv_state_pool_finish(&device->instruction_state_pool);
1228 anv_block_pool_finish(&device->instruction_block_pool);
1229 anv_state_pool_finish(&device->dynamic_state_pool);
1230 anv_block_pool_finish(&device->dynamic_state_block_pool);
1231
1232 anv_bo_cache_finish(&device->bo_cache);
1233
1234 anv_bo_pool_finish(&device->batch_bo_pool);
1235
1236 pthread_cond_destroy(&device->queue_submit);
1237 pthread_mutex_destroy(&device->mutex);
1238
1239 anv_gem_destroy_context(device, device->context_id);
1240
1241 close(device->fd);
1242
1243 vk_free(&device->alloc, device);
1244 }
1245
1246 VkResult anv_EnumerateInstanceExtensionProperties(
1247 const char* pLayerName,
1248 uint32_t* pPropertyCount,
1249 VkExtensionProperties* pProperties)
1250 {
1251 if (pProperties == NULL) {
1252 *pPropertyCount = ARRAY_SIZE(global_extensions);
1253 return VK_SUCCESS;
1254 }
1255
1256 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(global_extensions));
1257 typed_memcpy(pProperties, global_extensions, *pPropertyCount);
1258
1259 if (*pPropertyCount < ARRAY_SIZE(global_extensions))
1260 return VK_INCOMPLETE;
1261
1262 return VK_SUCCESS;
1263 }
1264
1265 VkResult anv_EnumerateDeviceExtensionProperties(
1266 VkPhysicalDevice physicalDevice,
1267 const char* pLayerName,
1268 uint32_t* pPropertyCount,
1269 VkExtensionProperties* pProperties)
1270 {
1271 if (pProperties == NULL) {
1272 *pPropertyCount = ARRAY_SIZE(device_extensions);
1273 return VK_SUCCESS;
1274 }
1275
1276 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(device_extensions));
1277 typed_memcpy(pProperties, device_extensions, *pPropertyCount);
1278
1279 if (*pPropertyCount < ARRAY_SIZE(device_extensions))
1280 return VK_INCOMPLETE;
1281
1282 return VK_SUCCESS;
1283 }
1284
1285 VkResult anv_EnumerateInstanceLayerProperties(
1286 uint32_t* pPropertyCount,
1287 VkLayerProperties* pProperties)
1288 {
1289 if (pProperties == NULL) {
1290 *pPropertyCount = 0;
1291 return VK_SUCCESS;
1292 }
1293
1294 /* None supported at this time */
1295 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1296 }
1297
1298 VkResult anv_EnumerateDeviceLayerProperties(
1299 VkPhysicalDevice physicalDevice,
1300 uint32_t* pPropertyCount,
1301 VkLayerProperties* pProperties)
1302 {
1303 if (pProperties == NULL) {
1304 *pPropertyCount = 0;
1305 return VK_SUCCESS;
1306 }
1307
1308 /* None supported at this time */
1309 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1310 }
1311
1312 void anv_GetDeviceQueue(
1313 VkDevice _device,
1314 uint32_t queueNodeIndex,
1315 uint32_t queueIndex,
1316 VkQueue* pQueue)
1317 {
1318 ANV_FROM_HANDLE(anv_device, device, _device);
1319
1320 assert(queueIndex == 0);
1321
1322 *pQueue = anv_queue_to_handle(&device->queue);
1323 }
1324
1325 VkResult
1326 anv_device_query_status(struct anv_device *device)
1327 {
1328 /* This isn't likely as most of the callers of this function already check
1329 * for it. However, it doesn't hurt to check and it potentially lets us
1330 * avoid an ioctl.
1331 */
1332 if (unlikely(device->lost))
1333 return VK_ERROR_DEVICE_LOST;
1334
1335 uint32_t active, pending;
1336 int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
1337 if (ret == -1) {
1338 /* We don't know the real error. */
1339 device->lost = true;
1340 return vk_errorf(VK_ERROR_DEVICE_LOST, "get_reset_stats failed: %m");
1341 }
1342
1343 if (active) {
1344 device->lost = true;
1345 return vk_errorf(VK_ERROR_DEVICE_LOST,
1346 "GPU hung on one of our command buffers");
1347 } else if (pending) {
1348 device->lost = true;
1349 return vk_errorf(VK_ERROR_DEVICE_LOST,
1350 "GPU hung with commands in-flight");
1351 }
1352
1353 return VK_SUCCESS;
1354 }
1355
1356 VkResult
1357 anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
1358 {
1359 /* Note: This only returns whether or not the BO is in use by an i915 GPU.
1360 * Other usages of the BO (such as on different hardware) will not be
1361 * flagged as "busy" by this ioctl. Use with care.
1362 */
1363 int ret = anv_gem_busy(device, bo->gem_handle);
1364 if (ret == 1) {
1365 return VK_NOT_READY;
1366 } else if (ret == -1) {
1367 /* We don't know the real error. */
1368 device->lost = true;
1369 return vk_errorf(VK_ERROR_DEVICE_LOST, "gem wait failed: %m");
1370 }
1371
1372 /* Query for device status after the busy call. If the BO we're checking
1373 * got caught in a GPU hang we don't want to return VK_SUCCESS to the
1374 * client because it clearly doesn't have valid data. Yes, this most
1375 * likely means an ioctl, but we just did an ioctl to query the busy status
1376 * so it's no great loss.
1377 */
1378 return anv_device_query_status(device);
1379 }
1380
1381 VkResult
1382 anv_device_wait(struct anv_device *device, struct anv_bo *bo,
1383 int64_t timeout)
1384 {
1385 int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
1386 if (ret == -1 && errno == ETIME) {
1387 return VK_TIMEOUT;
1388 } else if (ret == -1) {
1389 /* We don't know the real error. */
1390 device->lost = true;
1391 return vk_errorf(VK_ERROR_DEVICE_LOST, "gem wait failed: %m");
1392 }
1393
1394 /* Query for device status after the wait. If the BO we're waiting on got
1395 * caught in a GPU hang we don't want to return VK_SUCCESS to the client
1396 * because it clearly doesn't have valid data. Yes, this most likely means
1397 * an ioctl, but we just did an ioctl to wait so it's no great loss.
1398 */
1399 return anv_device_query_status(device);
1400 }
1401
1402 VkResult anv_DeviceWaitIdle(
1403 VkDevice _device)
1404 {
1405 ANV_FROM_HANDLE(anv_device, device, _device);
1406 if (unlikely(device->lost))
1407 return VK_ERROR_DEVICE_LOST;
1408
1409 struct anv_batch batch;
1410
1411 uint32_t cmds[8];
1412 batch.start = batch.next = cmds;
1413 batch.end = (void *) cmds + sizeof(cmds);
1414
1415 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1416 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1417
1418 return anv_device_submit_simple_batch(device, &batch);
1419 }
1420
1421 VkResult
1422 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
1423 {
1424 uint32_t gem_handle = anv_gem_create(device, size);
1425 if (!gem_handle)
1426 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1427
1428 anv_bo_init(bo, gem_handle, size);
1429
1430 if (device->instance->physicalDevice.supports_48bit_addresses)
1431 bo->flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1432
1433 if (device->instance->physicalDevice.has_exec_async)
1434 bo->flags |= EXEC_OBJECT_ASYNC;
1435
1436 return VK_SUCCESS;
1437 }
1438
1439 VkResult anv_AllocateMemory(
1440 VkDevice _device,
1441 const VkMemoryAllocateInfo* pAllocateInfo,
1442 const VkAllocationCallbacks* pAllocator,
1443 VkDeviceMemory* pMem)
1444 {
1445 ANV_FROM_HANDLE(anv_device, device, _device);
1446 struct anv_device_memory *mem;
1447 VkResult result = VK_SUCCESS;
1448
1449 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1450
1451 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
1452 assert(pAllocateInfo->allocationSize > 0);
1453
1454 /* We support exactly one memory heap. */
1455 assert(pAllocateInfo->memoryTypeIndex == 0 ||
1456 (!device->info.has_llc && pAllocateInfo->memoryTypeIndex < 2));
1457
1458 /* The kernel relocation API has a limitation of a 32-bit delta value
1459 * applied to the address before it is written which, in spite of it being
1460 * unsigned, is treated as signed . Because of the way that this maps to
1461 * the Vulkan API, we cannot handle an offset into a buffer that does not
1462 * fit into a signed 32 bits. The only mechanism we have for dealing with
1463 * this at the moment is to limit all VkDeviceMemory objects to a maximum
1464 * of 2GB each. The Vulkan spec allows us to do this:
1465 *
1466 * "Some platforms may have a limit on the maximum size of a single
1467 * allocation. For example, certain systems may fail to create
1468 * allocations with a size greater than or equal to 4GB. Such a limit is
1469 * implementation-dependent, and if such a failure occurs then the error
1470 * VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
1471 *
1472 * We don't use vk_error here because it's not an error so much as an
1473 * indication to the application that the allocation is too large.
1474 */
1475 if (pAllocateInfo->allocationSize > (1ull << 31))
1476 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1477
1478 /* FINISHME: Fail if allocation request exceeds heap size. */
1479
1480 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1481 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1482 if (mem == NULL)
1483 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1484
1485 mem->type_index = pAllocateInfo->memoryTypeIndex;
1486 mem->map = NULL;
1487 mem->map_size = 0;
1488
1489 const VkImportMemoryFdInfoKHX *fd_info =
1490 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHX);
1491
1492 /* The Vulkan spec permits handleType to be 0, in which case the struct is
1493 * ignored.
1494 */
1495 if (fd_info && fd_info->handleType) {
1496 /* At the moment, we only support the OPAQUE_FD memory type which is
1497 * just a GEM buffer.
1498 */
1499 assert(fd_info->handleType ==
1500 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHX);
1501
1502 result = anv_bo_cache_import(device, &device->bo_cache,
1503 fd_info->fd, pAllocateInfo->allocationSize,
1504 &mem->bo);
1505 if (result != VK_SUCCESS)
1506 goto fail;
1507 } else {
1508 result = anv_bo_cache_alloc(device, &device->bo_cache,
1509 pAllocateInfo->allocationSize,
1510 &mem->bo);
1511 if (result != VK_SUCCESS)
1512 goto fail;
1513 }
1514
1515 *pMem = anv_device_memory_to_handle(mem);
1516
1517 return VK_SUCCESS;
1518
1519 fail:
1520 vk_free2(&device->alloc, pAllocator, mem);
1521
1522 return result;
1523 }
1524
1525 VkResult anv_GetMemoryFdKHX(
1526 VkDevice device_h,
1527 VkDeviceMemory memory_h,
1528 VkExternalMemoryHandleTypeFlagBitsKHX handleType,
1529 int* pFd)
1530 {
1531 ANV_FROM_HANDLE(anv_device, dev, device_h);
1532 ANV_FROM_HANDLE(anv_device_memory, mem, memory_h);
1533
1534 /* We support only one handle type. */
1535 assert(handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHX);
1536
1537 return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
1538 }
1539
1540 VkResult anv_GetMemoryFdPropertiesKHX(
1541 VkDevice device_h,
1542 VkExternalMemoryHandleTypeFlagBitsKHX handleType,
1543 int fd,
1544 VkMemoryFdPropertiesKHX* pMemoryFdProperties)
1545 {
1546 /* The valid usage section for this function says:
1547 *
1548 * "handleType must not be one of the handle types defined as opaque."
1549 *
1550 * Since we only handle opaque handles for now, there are no FD properties.
1551 */
1552 return VK_ERROR_INVALID_EXTERNAL_HANDLE_KHX;
1553 }
1554
1555 void anv_FreeMemory(
1556 VkDevice _device,
1557 VkDeviceMemory _mem,
1558 const VkAllocationCallbacks* pAllocator)
1559 {
1560 ANV_FROM_HANDLE(anv_device, device, _device);
1561 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
1562
1563 if (mem == NULL)
1564 return;
1565
1566 if (mem->map)
1567 anv_UnmapMemory(_device, _mem);
1568
1569 anv_bo_cache_release(device, &device->bo_cache, mem->bo);
1570
1571 vk_free2(&device->alloc, pAllocator, mem);
1572 }
1573
1574 VkResult anv_MapMemory(
1575 VkDevice _device,
1576 VkDeviceMemory _memory,
1577 VkDeviceSize offset,
1578 VkDeviceSize size,
1579 VkMemoryMapFlags flags,
1580 void** ppData)
1581 {
1582 ANV_FROM_HANDLE(anv_device, device, _device);
1583 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1584
1585 if (mem == NULL) {
1586 *ppData = NULL;
1587 return VK_SUCCESS;
1588 }
1589
1590 if (size == VK_WHOLE_SIZE)
1591 size = mem->bo->size - offset;
1592
1593 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
1594 *
1595 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
1596 * assert(size != 0);
1597 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
1598 * equal to the size of the memory minus offset
1599 */
1600 assert(size > 0);
1601 assert(offset + size <= mem->bo->size);
1602
1603 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
1604 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
1605 * at a time is valid. We could just mmap up front and return an offset
1606 * pointer here, but that may exhaust virtual memory on 32 bit
1607 * userspace. */
1608
1609 uint32_t gem_flags = 0;
1610 if (!device->info.has_llc && mem->type_index == 0)
1611 gem_flags |= I915_MMAP_WC;
1612
1613 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
1614 uint64_t map_offset = offset & ~4095ull;
1615 assert(offset >= map_offset);
1616 uint64_t map_size = (offset + size) - map_offset;
1617
1618 /* Let's map whole pages */
1619 map_size = align_u64(map_size, 4096);
1620
1621 void *map = anv_gem_mmap(device, mem->bo->gem_handle,
1622 map_offset, map_size, gem_flags);
1623 if (map == MAP_FAILED)
1624 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1625
1626 mem->map = map;
1627 mem->map_size = map_size;
1628
1629 *ppData = mem->map + (offset - map_offset);
1630
1631 return VK_SUCCESS;
1632 }
1633
1634 void anv_UnmapMemory(
1635 VkDevice _device,
1636 VkDeviceMemory _memory)
1637 {
1638 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1639
1640 if (mem == NULL)
1641 return;
1642
1643 anv_gem_munmap(mem->map, mem->map_size);
1644
1645 mem->map = NULL;
1646 mem->map_size = 0;
1647 }
1648
1649 static void
1650 clflush_mapped_ranges(struct anv_device *device,
1651 uint32_t count,
1652 const VkMappedMemoryRange *ranges)
1653 {
1654 for (uint32_t i = 0; i < count; i++) {
1655 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
1656 if (ranges[i].offset >= mem->map_size)
1657 continue;
1658
1659 anv_clflush_range(mem->map + ranges[i].offset,
1660 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
1661 }
1662 }
1663
1664 VkResult anv_FlushMappedMemoryRanges(
1665 VkDevice _device,
1666 uint32_t memoryRangeCount,
1667 const VkMappedMemoryRange* pMemoryRanges)
1668 {
1669 ANV_FROM_HANDLE(anv_device, device, _device);
1670
1671 if (device->info.has_llc)
1672 return VK_SUCCESS;
1673
1674 /* Make sure the writes we're flushing have landed. */
1675 __builtin_ia32_mfence();
1676
1677 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1678
1679 return VK_SUCCESS;
1680 }
1681
1682 VkResult anv_InvalidateMappedMemoryRanges(
1683 VkDevice _device,
1684 uint32_t memoryRangeCount,
1685 const VkMappedMemoryRange* pMemoryRanges)
1686 {
1687 ANV_FROM_HANDLE(anv_device, device, _device);
1688
1689 if (device->info.has_llc)
1690 return VK_SUCCESS;
1691
1692 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1693
1694 /* Make sure no reads get moved up above the invalidate. */
1695 __builtin_ia32_mfence();
1696
1697 return VK_SUCCESS;
1698 }
1699
1700 void anv_GetBufferMemoryRequirements(
1701 VkDevice _device,
1702 VkBuffer _buffer,
1703 VkMemoryRequirements* pMemoryRequirements)
1704 {
1705 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1706 ANV_FROM_HANDLE(anv_device, device, _device);
1707
1708 /* The Vulkan spec (git aaed022) says:
1709 *
1710 * memoryTypeBits is a bitfield and contains one bit set for every
1711 * supported memory type for the resource. The bit `1<<i` is set if and
1712 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1713 * structure for the physical device is supported.
1714 *
1715 * We support exactly one memory type on LLC, two on non-LLC.
1716 */
1717 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1718
1719 pMemoryRequirements->size = buffer->size;
1720 pMemoryRequirements->alignment = 16;
1721 }
1722
1723 void anv_GetImageMemoryRequirements(
1724 VkDevice _device,
1725 VkImage _image,
1726 VkMemoryRequirements* pMemoryRequirements)
1727 {
1728 ANV_FROM_HANDLE(anv_image, image, _image);
1729 ANV_FROM_HANDLE(anv_device, device, _device);
1730
1731 /* The Vulkan spec (git aaed022) says:
1732 *
1733 * memoryTypeBits is a bitfield and contains one bit set for every
1734 * supported memory type for the resource. The bit `1<<i` is set if and
1735 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1736 * structure for the physical device is supported.
1737 *
1738 * We support exactly one memory type on LLC, two on non-LLC.
1739 */
1740 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1741
1742 pMemoryRequirements->size = image->size;
1743 pMemoryRequirements->alignment = image->alignment;
1744 }
1745
1746 void anv_GetImageSparseMemoryRequirements(
1747 VkDevice device,
1748 VkImage image,
1749 uint32_t* pSparseMemoryRequirementCount,
1750 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
1751 {
1752 *pSparseMemoryRequirementCount = 0;
1753 }
1754
1755 void anv_GetDeviceMemoryCommitment(
1756 VkDevice device,
1757 VkDeviceMemory memory,
1758 VkDeviceSize* pCommittedMemoryInBytes)
1759 {
1760 *pCommittedMemoryInBytes = 0;
1761 }
1762
1763 VkResult anv_BindBufferMemory(
1764 VkDevice device,
1765 VkBuffer _buffer,
1766 VkDeviceMemory _memory,
1767 VkDeviceSize memoryOffset)
1768 {
1769 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1770 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1771
1772 if (mem) {
1773 buffer->bo = mem->bo;
1774 buffer->offset = memoryOffset;
1775 } else {
1776 buffer->bo = NULL;
1777 buffer->offset = 0;
1778 }
1779
1780 return VK_SUCCESS;
1781 }
1782
1783 VkResult anv_QueueBindSparse(
1784 VkQueue _queue,
1785 uint32_t bindInfoCount,
1786 const VkBindSparseInfo* pBindInfo,
1787 VkFence fence)
1788 {
1789 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1790 if (unlikely(queue->device->lost))
1791 return VK_ERROR_DEVICE_LOST;
1792
1793 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1794 }
1795
1796 // Event functions
1797
1798 VkResult anv_CreateEvent(
1799 VkDevice _device,
1800 const VkEventCreateInfo* pCreateInfo,
1801 const VkAllocationCallbacks* pAllocator,
1802 VkEvent* pEvent)
1803 {
1804 ANV_FROM_HANDLE(anv_device, device, _device);
1805 struct anv_state state;
1806 struct anv_event *event;
1807
1808 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
1809
1810 state = anv_state_pool_alloc(&device->dynamic_state_pool,
1811 sizeof(*event), 8);
1812 event = state.map;
1813 event->state = state;
1814 event->semaphore = VK_EVENT_RESET;
1815
1816 if (!device->info.has_llc) {
1817 /* Make sure the writes we're flushing have landed. */
1818 __builtin_ia32_mfence();
1819 __builtin_ia32_clflush(event);
1820 }
1821
1822 *pEvent = anv_event_to_handle(event);
1823
1824 return VK_SUCCESS;
1825 }
1826
1827 void anv_DestroyEvent(
1828 VkDevice _device,
1829 VkEvent _event,
1830 const VkAllocationCallbacks* pAllocator)
1831 {
1832 ANV_FROM_HANDLE(anv_device, device, _device);
1833 ANV_FROM_HANDLE(anv_event, event, _event);
1834
1835 if (!event)
1836 return;
1837
1838 anv_state_pool_free(&device->dynamic_state_pool, event->state);
1839 }
1840
1841 VkResult anv_GetEventStatus(
1842 VkDevice _device,
1843 VkEvent _event)
1844 {
1845 ANV_FROM_HANDLE(anv_device, device, _device);
1846 ANV_FROM_HANDLE(anv_event, event, _event);
1847
1848 if (unlikely(device->lost))
1849 return VK_ERROR_DEVICE_LOST;
1850
1851 if (!device->info.has_llc) {
1852 /* Invalidate read cache before reading event written by GPU. */
1853 __builtin_ia32_clflush(event);
1854 __builtin_ia32_mfence();
1855
1856 }
1857
1858 return event->semaphore;
1859 }
1860
1861 VkResult anv_SetEvent(
1862 VkDevice _device,
1863 VkEvent _event)
1864 {
1865 ANV_FROM_HANDLE(anv_device, device, _device);
1866 ANV_FROM_HANDLE(anv_event, event, _event);
1867
1868 event->semaphore = VK_EVENT_SET;
1869
1870 if (!device->info.has_llc) {
1871 /* Make sure the writes we're flushing have landed. */
1872 __builtin_ia32_mfence();
1873 __builtin_ia32_clflush(event);
1874 }
1875
1876 return VK_SUCCESS;
1877 }
1878
1879 VkResult anv_ResetEvent(
1880 VkDevice _device,
1881 VkEvent _event)
1882 {
1883 ANV_FROM_HANDLE(anv_device, device, _device);
1884 ANV_FROM_HANDLE(anv_event, event, _event);
1885
1886 event->semaphore = VK_EVENT_RESET;
1887
1888 if (!device->info.has_llc) {
1889 /* Make sure the writes we're flushing have landed. */
1890 __builtin_ia32_mfence();
1891 __builtin_ia32_clflush(event);
1892 }
1893
1894 return VK_SUCCESS;
1895 }
1896
1897 // Buffer functions
1898
1899 VkResult anv_CreateBuffer(
1900 VkDevice _device,
1901 const VkBufferCreateInfo* pCreateInfo,
1902 const VkAllocationCallbacks* pAllocator,
1903 VkBuffer* pBuffer)
1904 {
1905 ANV_FROM_HANDLE(anv_device, device, _device);
1906 struct anv_buffer *buffer;
1907
1908 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
1909
1910 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
1911 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1912 if (buffer == NULL)
1913 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1914
1915 buffer->size = pCreateInfo->size;
1916 buffer->usage = pCreateInfo->usage;
1917 buffer->bo = NULL;
1918 buffer->offset = 0;
1919
1920 *pBuffer = anv_buffer_to_handle(buffer);
1921
1922 return VK_SUCCESS;
1923 }
1924
1925 void anv_DestroyBuffer(
1926 VkDevice _device,
1927 VkBuffer _buffer,
1928 const VkAllocationCallbacks* pAllocator)
1929 {
1930 ANV_FROM_HANDLE(anv_device, device, _device);
1931 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1932
1933 if (!buffer)
1934 return;
1935
1936 vk_free2(&device->alloc, pAllocator, buffer);
1937 }
1938
1939 void
1940 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
1941 enum isl_format format,
1942 uint32_t offset, uint32_t range, uint32_t stride)
1943 {
1944 isl_buffer_fill_state(&device->isl_dev, state.map,
1945 .address = offset,
1946 .mocs = device->default_mocs,
1947 .size = range,
1948 .format = format,
1949 .stride = stride);
1950
1951 anv_state_flush(device, state);
1952 }
1953
1954 void anv_DestroySampler(
1955 VkDevice _device,
1956 VkSampler _sampler,
1957 const VkAllocationCallbacks* pAllocator)
1958 {
1959 ANV_FROM_HANDLE(anv_device, device, _device);
1960 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
1961
1962 if (!sampler)
1963 return;
1964
1965 vk_free2(&device->alloc, pAllocator, sampler);
1966 }
1967
1968 VkResult anv_CreateFramebuffer(
1969 VkDevice _device,
1970 const VkFramebufferCreateInfo* pCreateInfo,
1971 const VkAllocationCallbacks* pAllocator,
1972 VkFramebuffer* pFramebuffer)
1973 {
1974 ANV_FROM_HANDLE(anv_device, device, _device);
1975 struct anv_framebuffer *framebuffer;
1976
1977 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
1978
1979 size_t size = sizeof(*framebuffer) +
1980 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
1981 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
1982 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1983 if (framebuffer == NULL)
1984 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1985
1986 framebuffer->attachment_count = pCreateInfo->attachmentCount;
1987 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
1988 VkImageView _iview = pCreateInfo->pAttachments[i];
1989 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
1990 }
1991
1992 framebuffer->width = pCreateInfo->width;
1993 framebuffer->height = pCreateInfo->height;
1994 framebuffer->layers = pCreateInfo->layers;
1995
1996 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
1997
1998 return VK_SUCCESS;
1999 }
2000
2001 void anv_DestroyFramebuffer(
2002 VkDevice _device,
2003 VkFramebuffer _fb,
2004 const VkAllocationCallbacks* pAllocator)
2005 {
2006 ANV_FROM_HANDLE(anv_device, device, _device);
2007 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2008
2009 if (!fb)
2010 return;
2011
2012 vk_free2(&device->alloc, pAllocator, fb);
2013 }
2014
2015 /* vk_icd.h does not declare this function, so we declare it here to
2016 * suppress Wmissing-prototypes.
2017 */
2018 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2019 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2020
2021 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2022 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2023 {
2024 /* For the full details on loader interface versioning, see
2025 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2026 * What follows is a condensed summary, to help you navigate the large and
2027 * confusing official doc.
2028 *
2029 * - Loader interface v0 is incompatible with later versions. We don't
2030 * support it.
2031 *
2032 * - In loader interface v1:
2033 * - The first ICD entrypoint called by the loader is
2034 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2035 * entrypoint.
2036 * - The ICD must statically expose no other Vulkan symbol unless it is
2037 * linked with -Bsymbolic.
2038 * - Each dispatchable Vulkan handle created by the ICD must be
2039 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2040 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2041 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2042 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2043 * such loader-managed surfaces.
2044 *
2045 * - Loader interface v2 differs from v1 in:
2046 * - The first ICD entrypoint called by the loader is
2047 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2048 * statically expose this entrypoint.
2049 *
2050 * - Loader interface v3 differs from v2 in:
2051 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2052 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2053 * because the loader no longer does so.
2054 */
2055 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2056 return VK_SUCCESS;
2057 }