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