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