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