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