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