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