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