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