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