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