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