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