anv: Set EXEC_OBJECT_ASYNC when available
[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 "util/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 bool
101 anv_device_get_cache_uuid(void *uuid, uint16_t pci_id)
102 {
103 const struct build_id_note *note = build_id_find_nhdr("libvulkan_intel.so");
104 if (!note)
105 return false;
106
107 unsigned build_id_len = build_id_length(note);
108 if (build_id_len < 20) /* It should be a SHA-1 */
109 return false;
110
111 struct mesa_sha1 sha1_ctx;
112 uint8_t sha1[20];
113 STATIC_ASSERT(VK_UUID_SIZE <= sizeof(sha1));
114
115 _mesa_sha1_init(&sha1_ctx);
116 _mesa_sha1_update(&sha1_ctx, build_id_data(note), build_id_len);
117 _mesa_sha1_update(&sha1_ctx, &pci_id, sizeof(pci_id));
118 _mesa_sha1_final(&sha1_ctx, sha1);
119
120 memcpy(uuid, sha1, VK_UUID_SIZE);
121 return true;
122 }
123
124 static VkResult
125 anv_physical_device_init(struct anv_physical_device *device,
126 struct anv_instance *instance,
127 const char *path)
128 {
129 VkResult result;
130 int fd;
131
132 fd = open(path, O_RDWR | O_CLOEXEC);
133 if (fd < 0)
134 return vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
135
136 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
137 device->instance = instance;
138
139 assert(strlen(path) < ARRAY_SIZE(device->path));
140 strncpy(device->path, path, ARRAY_SIZE(device->path));
141
142 device->chipset_id = anv_gem_get_param(fd, I915_PARAM_CHIPSET_ID);
143 if (!device->chipset_id) {
144 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
145 goto fail;
146 }
147
148 device->name = gen_get_device_name(device->chipset_id);
149 if (!gen_get_device_info(device->chipset_id, &device->info)) {
150 result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
151 goto fail;
152 }
153
154 if (device->info.is_haswell) {
155 fprintf(stderr, "WARNING: Haswell Vulkan support is incomplete\n");
156 } else if (device->info.gen == 7 && !device->info.is_baytrail) {
157 fprintf(stderr, "WARNING: Ivy Bridge Vulkan support is incomplete\n");
158 } else if (device->info.gen == 7 && device->info.is_baytrail) {
159 fprintf(stderr, "WARNING: Bay Trail Vulkan support is incomplete\n");
160 } else if (device->info.gen >= 8) {
161 /* Broadwell, Cherryview, Skylake, Broxton, Kabylake is as fully
162 * supported as anything */
163 } else {
164 result = vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
165 "Vulkan not yet supported on %s", device->name);
166 goto fail;
167 }
168
169 device->cmd_parser_version = -1;
170 if (device->info.gen == 7) {
171 device->cmd_parser_version =
172 anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
173 if (device->cmd_parser_version == -1) {
174 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
175 "failed to get command parser version");
176 goto fail;
177 }
178 }
179
180 if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
181 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
182 "kernel missing gem wait");
183 goto fail;
184 }
185
186 if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
187 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
188 "kernel missing execbuf2");
189 goto fail;
190 }
191
192 if (!device->info.has_llc &&
193 anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
194 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
195 "kernel missing wc mmap");
196 goto fail;
197 }
198
199 device->supports_48bit_addresses = anv_gem_supports_48b_addresses(fd);
200
201 result = anv_compute_heap_size(fd, &device->heap_size);
202 if (result != VK_SUCCESS)
203 goto fail;
204
205 device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
206
207 if (!anv_device_get_cache_uuid(device->uuid, device->chipset_id)) {
208 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
209 "cannot generate UUID");
210 goto fail;
211 }
212 bool swizzled = anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
213
214 /* GENs prior to 8 do not support EU/Subslice info */
215 if (device->info.gen >= 8) {
216 device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
217 device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
218
219 /* Without this information, we cannot get the right Braswell
220 * brandstrings, and we have to use conservative numbers for GPGPU on
221 * many platforms, but otherwise, things will just work.
222 */
223 if (device->subslice_total < 1 || device->eu_total < 1) {
224 fprintf(stderr, "WARNING: Kernel 4.1 required to properly"
225 " query GPU properties.\n");
226 }
227 } else if (device->info.gen == 7) {
228 device->subslice_total = 1 << (device->info.gt - 1);
229 }
230
231 if (device->info.is_cherryview &&
232 device->subslice_total > 0 && device->eu_total > 0) {
233 /* Logical CS threads = EUs per subslice * 7 threads per EU */
234 uint32_t max_cs_threads = device->eu_total / device->subslice_total * 7;
235
236 /* Fuse configurations may give more threads than expected, never less. */
237 if (max_cs_threads > device->info.max_cs_threads)
238 device->info.max_cs_threads = max_cs_threads;
239 }
240
241 brw_process_intel_debug_variable();
242
243 device->compiler = brw_compiler_create(NULL, &device->info);
244 if (device->compiler == NULL) {
245 result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
246 goto fail;
247 }
248 device->compiler->shader_debug_log = compiler_debug_log;
249 device->compiler->shader_perf_log = compiler_perf_log;
250
251 result = anv_init_wsi(device);
252 if (result != VK_SUCCESS) {
253 ralloc_free(device->compiler);
254 goto fail;
255 }
256
257 isl_device_init(&device->isl_dev, &device->info, swizzled);
258
259 device->local_fd = fd;
260 return VK_SUCCESS;
261
262 fail:
263 close(fd);
264 return result;
265 }
266
267 static void
268 anv_physical_device_finish(struct anv_physical_device *device)
269 {
270 anv_finish_wsi(device);
271 ralloc_free(device->compiler);
272 close(device->local_fd);
273 }
274
275 static const VkExtensionProperties global_extensions[] = {
276 {
277 .extensionName = VK_KHR_SURFACE_EXTENSION_NAME,
278 .specVersion = 25,
279 },
280 #ifdef VK_USE_PLATFORM_XCB_KHR
281 {
282 .extensionName = VK_KHR_XCB_SURFACE_EXTENSION_NAME,
283 .specVersion = 6,
284 },
285 #endif
286 #ifdef VK_USE_PLATFORM_XLIB_KHR
287 {
288 .extensionName = VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
289 .specVersion = 6,
290 },
291 #endif
292 #ifdef VK_USE_PLATFORM_WAYLAND_KHR
293 {
294 .extensionName = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME,
295 .specVersion = 5,
296 },
297 #endif
298 {
299 .extensionName = VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
300 .specVersion = 1,
301 },
302 };
303
304 static const VkExtensionProperties device_extensions[] = {
305 {
306 .extensionName = VK_KHR_SWAPCHAIN_EXTENSION_NAME,
307 .specVersion = 68,
308 },
309 {
310 .extensionName = VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME,
311 .specVersion = 1,
312 },
313 {
314 .extensionName = VK_KHR_MAINTENANCE1_EXTENSION_NAME,
315 .specVersion = 1,
316 },
317 {
318 .extensionName = VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME,
319 .specVersion = 1,
320 },
321 {
322 .extensionName = VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME,
323 .specVersion = 1,
324 },
325 {
326 .extensionName = VK_KHR_DESCRIPTOR_UPDATE_TEMPLATE_EXTENSION_NAME,
327 .specVersion = 1,
328 },
329 {
330 .extensionName = VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME,
331 .specVersion = 1,
332 },
333 };
334
335 static void *
336 default_alloc_func(void *pUserData, size_t size, size_t align,
337 VkSystemAllocationScope allocationScope)
338 {
339 return malloc(size);
340 }
341
342 static void *
343 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
344 size_t align, VkSystemAllocationScope allocationScope)
345 {
346 return realloc(pOriginal, size);
347 }
348
349 static void
350 default_free_func(void *pUserData, void *pMemory)
351 {
352 free(pMemory);
353 }
354
355 static const VkAllocationCallbacks default_alloc = {
356 .pUserData = NULL,
357 .pfnAllocation = default_alloc_func,
358 .pfnReallocation = default_realloc_func,
359 .pfnFree = default_free_func,
360 };
361
362 VkResult anv_CreateInstance(
363 const VkInstanceCreateInfo* pCreateInfo,
364 const VkAllocationCallbacks* pAllocator,
365 VkInstance* pInstance)
366 {
367 struct anv_instance *instance;
368
369 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
370
371 uint32_t client_version;
372 if (pCreateInfo->pApplicationInfo &&
373 pCreateInfo->pApplicationInfo->apiVersion != 0) {
374 client_version = pCreateInfo->pApplicationInfo->apiVersion;
375 } else {
376 client_version = VK_MAKE_VERSION(1, 0, 0);
377 }
378
379 if (VK_MAKE_VERSION(1, 0, 0) > client_version ||
380 client_version > VK_MAKE_VERSION(1, 0, 0xfff)) {
381 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
382 "Client requested version %d.%d.%d",
383 VK_VERSION_MAJOR(client_version),
384 VK_VERSION_MINOR(client_version),
385 VK_VERSION_PATCH(client_version));
386 }
387
388 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
389 bool found = false;
390 for (uint32_t j = 0; j < ARRAY_SIZE(global_extensions); j++) {
391 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
392 global_extensions[j].extensionName) == 0) {
393 found = true;
394 break;
395 }
396 }
397 if (!found)
398 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
399 }
400
401 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
402 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
403 if (!instance)
404 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
405
406 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
407
408 if (pAllocator)
409 instance->alloc = *pAllocator;
410 else
411 instance->alloc = default_alloc;
412
413 instance->apiVersion = client_version;
414 instance->physicalDeviceCount = -1;
415
416 _mesa_locale_init();
417
418 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
419
420 *pInstance = anv_instance_to_handle(instance);
421
422 return VK_SUCCESS;
423 }
424
425 void anv_DestroyInstance(
426 VkInstance _instance,
427 const VkAllocationCallbacks* pAllocator)
428 {
429 ANV_FROM_HANDLE(anv_instance, instance, _instance);
430
431 if (!instance)
432 return;
433
434 if (instance->physicalDeviceCount > 0) {
435 /* We support at most one physical device. */
436 assert(instance->physicalDeviceCount == 1);
437 anv_physical_device_finish(&instance->physicalDevice);
438 }
439
440 VG(VALGRIND_DESTROY_MEMPOOL(instance));
441
442 _mesa_locale_fini();
443
444 vk_free(&instance->alloc, instance);
445 }
446
447 static VkResult
448 anv_enumerate_devices(struct anv_instance *instance)
449 {
450 /* TODO: Check for more devices ? */
451 drmDevicePtr devices[8];
452 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
453 int max_devices;
454
455 instance->physicalDeviceCount = 0;
456
457 max_devices = drmGetDevices2(0, devices, sizeof(devices));
458 if (max_devices < 1)
459 return VK_ERROR_INCOMPATIBLE_DRIVER;
460
461 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
462 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
463 devices[i]->bustype == DRM_BUS_PCI &&
464 devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
465
466 result = anv_physical_device_init(&instance->physicalDevice,
467 instance,
468 devices[i]->nodes[DRM_NODE_RENDER]);
469 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
470 break;
471 }
472 }
473
474 if (result == VK_SUCCESS)
475 instance->physicalDeviceCount = 1;
476
477 return result;
478 }
479
480
481 VkResult anv_EnumeratePhysicalDevices(
482 VkInstance _instance,
483 uint32_t* pPhysicalDeviceCount,
484 VkPhysicalDevice* pPhysicalDevices)
485 {
486 ANV_FROM_HANDLE(anv_instance, instance, _instance);
487 VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
488 VkResult result;
489
490 if (instance->physicalDeviceCount < 0) {
491 result = anv_enumerate_devices(instance);
492 if (result != VK_SUCCESS &&
493 result != VK_ERROR_INCOMPATIBLE_DRIVER)
494 return result;
495 }
496
497 if (instance->physicalDeviceCount > 0) {
498 assert(instance->physicalDeviceCount == 1);
499 vk_outarray_append(&out, i) {
500 *i = anv_physical_device_to_handle(&instance->physicalDevice);
501 }
502 }
503
504 return vk_outarray_status(&out);
505 }
506
507 void anv_GetPhysicalDeviceFeatures(
508 VkPhysicalDevice physicalDevice,
509 VkPhysicalDeviceFeatures* pFeatures)
510 {
511 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
512
513 *pFeatures = (VkPhysicalDeviceFeatures) {
514 .robustBufferAccess = true,
515 .fullDrawIndexUint32 = true,
516 .imageCubeArray = true,
517 .independentBlend = true,
518 .geometryShader = true,
519 .tessellationShader = true,
520 .sampleRateShading = true,
521 .dualSrcBlend = true,
522 .logicOp = true,
523 .multiDrawIndirect = false,
524 .drawIndirectFirstInstance = true,
525 .depthClamp = true,
526 .depthBiasClamp = true,
527 .fillModeNonSolid = true,
528 .depthBounds = false,
529 .wideLines = true,
530 .largePoints = true,
531 .alphaToOne = true,
532 .multiViewport = true,
533 .samplerAnisotropy = true,
534 .textureCompressionETC2 = pdevice->info.gen >= 8 ||
535 pdevice->info.is_baytrail,
536 .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
537 .textureCompressionBC = true,
538 .occlusionQueryPrecise = true,
539 .pipelineStatisticsQuery = true,
540 .fragmentStoresAndAtomics = true,
541 .shaderTessellationAndGeometryPointSize = true,
542 .shaderImageGatherExtended = true,
543 .shaderStorageImageExtendedFormats = true,
544 .shaderStorageImageMultisample = false,
545 .shaderStorageImageReadWithoutFormat = false,
546 .shaderStorageImageWriteWithoutFormat = true,
547 .shaderUniformBufferArrayDynamicIndexing = true,
548 .shaderSampledImageArrayDynamicIndexing = true,
549 .shaderStorageBufferArrayDynamicIndexing = true,
550 .shaderStorageImageArrayDynamicIndexing = true,
551 .shaderClipDistance = true,
552 .shaderCullDistance = true,
553 .shaderFloat64 = pdevice->info.gen >= 8,
554 .shaderInt64 = pdevice->info.gen >= 8,
555 .shaderInt16 = false,
556 .shaderResourceMinLod = false,
557 .variableMultisampleRate = false,
558 .inheritedQueries = true,
559 };
560
561 /* We can't do image stores in vec4 shaders */
562 pFeatures->vertexPipelineStoresAndAtomics =
563 pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
564 pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
565 }
566
567 void anv_GetPhysicalDeviceFeatures2KHR(
568 VkPhysicalDevice physicalDevice,
569 VkPhysicalDeviceFeatures2KHR* pFeatures)
570 {
571 anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
572
573 vk_foreach_struct(ext, pFeatures->pNext) {
574 switch (ext->sType) {
575 default:
576 anv_debug_ignored_stype(ext->sType);
577 break;
578 }
579 }
580 }
581
582 void anv_GetPhysicalDeviceProperties(
583 VkPhysicalDevice physicalDevice,
584 VkPhysicalDeviceProperties* pProperties)
585 {
586 ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
587 const struct gen_device_info *devinfo = &pdevice->info;
588
589 /* See assertions made when programming the buffer surface state. */
590 const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
591 (1ul << 30) : (1ul << 27);
592
593 VkSampleCountFlags sample_counts =
594 isl_device_get_sample_counts(&pdevice->isl_dev);
595
596 VkPhysicalDeviceLimits limits = {
597 .maxImageDimension1D = (1 << 14),
598 .maxImageDimension2D = (1 << 14),
599 .maxImageDimension3D = (1 << 11),
600 .maxImageDimensionCube = (1 << 14),
601 .maxImageArrayLayers = (1 << 11),
602 .maxTexelBufferElements = 128 * 1024 * 1024,
603 .maxUniformBufferRange = (1ul << 27),
604 .maxStorageBufferRange = max_raw_buffer_sz,
605 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
606 .maxMemoryAllocationCount = UINT32_MAX,
607 .maxSamplerAllocationCount = 64 * 1024,
608 .bufferImageGranularity = 64, /* A cache line */
609 .sparseAddressSpaceSize = 0,
610 .maxBoundDescriptorSets = MAX_SETS,
611 .maxPerStageDescriptorSamplers = 64,
612 .maxPerStageDescriptorUniformBuffers = 64,
613 .maxPerStageDescriptorStorageBuffers = 64,
614 .maxPerStageDescriptorSampledImages = 64,
615 .maxPerStageDescriptorStorageImages = 64,
616 .maxPerStageDescriptorInputAttachments = 64,
617 .maxPerStageResources = 128,
618 .maxDescriptorSetSamplers = 256,
619 .maxDescriptorSetUniformBuffers = 256,
620 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
621 .maxDescriptorSetStorageBuffers = 256,
622 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
623 .maxDescriptorSetSampledImages = 256,
624 .maxDescriptorSetStorageImages = 256,
625 .maxDescriptorSetInputAttachments = 256,
626 .maxVertexInputAttributes = MAX_VBS,
627 .maxVertexInputBindings = MAX_VBS,
628 .maxVertexInputAttributeOffset = 2047,
629 .maxVertexInputBindingStride = 2048,
630 .maxVertexOutputComponents = 128,
631 .maxTessellationGenerationLevel = 64,
632 .maxTessellationPatchSize = 32,
633 .maxTessellationControlPerVertexInputComponents = 128,
634 .maxTessellationControlPerVertexOutputComponents = 128,
635 .maxTessellationControlPerPatchOutputComponents = 128,
636 .maxTessellationControlTotalOutputComponents = 2048,
637 .maxTessellationEvaluationInputComponents = 128,
638 .maxTessellationEvaluationOutputComponents = 128,
639 .maxGeometryShaderInvocations = 32,
640 .maxGeometryInputComponents = 64,
641 .maxGeometryOutputComponents = 128,
642 .maxGeometryOutputVertices = 256,
643 .maxGeometryTotalOutputComponents = 1024,
644 .maxFragmentInputComponents = 128,
645 .maxFragmentOutputAttachments = 8,
646 .maxFragmentDualSrcAttachments = 1,
647 .maxFragmentCombinedOutputResources = 8,
648 .maxComputeSharedMemorySize = 32768,
649 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
650 .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
651 .maxComputeWorkGroupSize = {
652 16 * devinfo->max_cs_threads,
653 16 * devinfo->max_cs_threads,
654 16 * devinfo->max_cs_threads,
655 },
656 .subPixelPrecisionBits = 4 /* FIXME */,
657 .subTexelPrecisionBits = 4 /* FIXME */,
658 .mipmapPrecisionBits = 4 /* FIXME */,
659 .maxDrawIndexedIndexValue = UINT32_MAX,
660 .maxDrawIndirectCount = UINT32_MAX,
661 .maxSamplerLodBias = 16,
662 .maxSamplerAnisotropy = 16,
663 .maxViewports = MAX_VIEWPORTS,
664 .maxViewportDimensions = { (1 << 14), (1 << 14) },
665 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
666 .viewportSubPixelBits = 13, /* We take a float? */
667 .minMemoryMapAlignment = 4096, /* A page */
668 .minTexelBufferOffsetAlignment = 1,
669 .minUniformBufferOffsetAlignment = 16,
670 .minStorageBufferOffsetAlignment = 4,
671 .minTexelOffset = -8,
672 .maxTexelOffset = 7,
673 .minTexelGatherOffset = -32,
674 .maxTexelGatherOffset = 31,
675 .minInterpolationOffset = -0.5,
676 .maxInterpolationOffset = 0.4375,
677 .subPixelInterpolationOffsetBits = 4,
678 .maxFramebufferWidth = (1 << 14),
679 .maxFramebufferHeight = (1 << 14),
680 .maxFramebufferLayers = (1 << 11),
681 .framebufferColorSampleCounts = sample_counts,
682 .framebufferDepthSampleCounts = sample_counts,
683 .framebufferStencilSampleCounts = sample_counts,
684 .framebufferNoAttachmentsSampleCounts = sample_counts,
685 .maxColorAttachments = MAX_RTS,
686 .sampledImageColorSampleCounts = sample_counts,
687 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
688 .sampledImageDepthSampleCounts = sample_counts,
689 .sampledImageStencilSampleCounts = sample_counts,
690 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
691 .maxSampleMaskWords = 1,
692 .timestampComputeAndGraphics = false,
693 .timestampPeriod = devinfo->timebase_scale,
694 .maxClipDistances = 8,
695 .maxCullDistances = 8,
696 .maxCombinedClipAndCullDistances = 8,
697 .discreteQueuePriorities = 1,
698 .pointSizeRange = { 0.125, 255.875 },
699 .lineWidthRange = { 0.0, 7.9921875 },
700 .pointSizeGranularity = (1.0 / 8.0),
701 .lineWidthGranularity = (1.0 / 128.0),
702 .strictLines = false, /* FINISHME */
703 .standardSampleLocations = true,
704 .optimalBufferCopyOffsetAlignment = 128,
705 .optimalBufferCopyRowPitchAlignment = 128,
706 .nonCoherentAtomSize = 64,
707 };
708
709 *pProperties = (VkPhysicalDeviceProperties) {
710 .apiVersion = VK_MAKE_VERSION(1, 0, 42),
711 .driverVersion = 1,
712 .vendorID = 0x8086,
713 .deviceID = pdevice->chipset_id,
714 .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
715 .limits = limits,
716 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
717 };
718
719 strcpy(pProperties->deviceName, pdevice->name);
720 memcpy(pProperties->pipelineCacheUUID, pdevice->uuid, VK_UUID_SIZE);
721 }
722
723 void anv_GetPhysicalDeviceProperties2KHR(
724 VkPhysicalDevice physicalDevice,
725 VkPhysicalDeviceProperties2KHR* pProperties)
726 {
727 anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
728
729 vk_foreach_struct(ext, pProperties->pNext) {
730 switch (ext->sType) {
731 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
732 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
733 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
734
735 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
736 break;
737 }
738
739 default:
740 anv_debug_ignored_stype(ext->sType);
741 break;
742 }
743 }
744 }
745
746 /* We support exactly one queue family. */
747 static const VkQueueFamilyProperties
748 anv_queue_family_properties = {
749 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
750 VK_QUEUE_COMPUTE_BIT |
751 VK_QUEUE_TRANSFER_BIT,
752 .queueCount = 1,
753 .timestampValidBits = 36, /* XXX: Real value here */
754 .minImageTransferGranularity = { 1, 1, 1 },
755 };
756
757 void anv_GetPhysicalDeviceQueueFamilyProperties(
758 VkPhysicalDevice physicalDevice,
759 uint32_t* pCount,
760 VkQueueFamilyProperties* pQueueFamilyProperties)
761 {
762 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
763
764 vk_outarray_append(&out, p) {
765 *p = anv_queue_family_properties;
766 }
767 }
768
769 void anv_GetPhysicalDeviceQueueFamilyProperties2KHR(
770 VkPhysicalDevice physicalDevice,
771 uint32_t* pQueueFamilyPropertyCount,
772 VkQueueFamilyProperties2KHR* pQueueFamilyProperties)
773 {
774
775 VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
776
777 vk_outarray_append(&out, p) {
778 p->queueFamilyProperties = anv_queue_family_properties;
779
780 vk_foreach_struct(s, p->pNext) {
781 anv_debug_ignored_stype(s->sType);
782 }
783 }
784 }
785
786 void anv_GetPhysicalDeviceMemoryProperties(
787 VkPhysicalDevice physicalDevice,
788 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
789 {
790 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
791
792 if (physical_device->info.has_llc) {
793 /* Big core GPUs share LLC with the CPU and thus one memory type can be
794 * both cached and coherent at the same time.
795 */
796 pMemoryProperties->memoryTypeCount = 1;
797 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
798 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
799 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
800 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
801 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
802 .heapIndex = 0,
803 };
804 } else {
805 /* The spec requires that we expose a host-visible, coherent memory
806 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
807 * to give the application a choice between cached, but not coherent and
808 * coherent but uncached (WC though).
809 */
810 pMemoryProperties->memoryTypeCount = 2;
811 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
812 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
813 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
814 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
815 .heapIndex = 0,
816 };
817 pMemoryProperties->memoryTypes[1] = (VkMemoryType) {
818 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
819 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
820 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
821 .heapIndex = 0,
822 };
823 }
824
825 pMemoryProperties->memoryHeapCount = 1;
826 pMemoryProperties->memoryHeaps[0] = (VkMemoryHeap) {
827 .size = physical_device->heap_size,
828 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
829 };
830 }
831
832 void anv_GetPhysicalDeviceMemoryProperties2KHR(
833 VkPhysicalDevice physicalDevice,
834 VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties)
835 {
836 anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
837 &pMemoryProperties->memoryProperties);
838
839 vk_foreach_struct(ext, pMemoryProperties->pNext) {
840 switch (ext->sType) {
841 default:
842 anv_debug_ignored_stype(ext->sType);
843 break;
844 }
845 }
846 }
847
848 PFN_vkVoidFunction anv_GetInstanceProcAddr(
849 VkInstance instance,
850 const char* pName)
851 {
852 return anv_lookup_entrypoint(NULL, pName);
853 }
854
855 /* With version 1+ of the loader interface the ICD should expose
856 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
857 */
858 PUBLIC
859 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
860 VkInstance instance,
861 const char* pName);
862
863 PUBLIC
864 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
865 VkInstance instance,
866 const char* pName)
867 {
868 return anv_GetInstanceProcAddr(instance, pName);
869 }
870
871 PFN_vkVoidFunction anv_GetDeviceProcAddr(
872 VkDevice _device,
873 const char* pName)
874 {
875 ANV_FROM_HANDLE(anv_device, device, _device);
876 return anv_lookup_entrypoint(&device->info, pName);
877 }
878
879 static void
880 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
881 {
882 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
883 queue->device = device;
884 queue->pool = &device->surface_state_pool;
885 }
886
887 static void
888 anv_queue_finish(struct anv_queue *queue)
889 {
890 }
891
892 static struct anv_state
893 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
894 {
895 struct anv_state state;
896
897 state = anv_state_pool_alloc(pool, size, align);
898 memcpy(state.map, p, size);
899
900 anv_state_flush(pool->block_pool->device, state);
901
902 return state;
903 }
904
905 struct gen8_border_color {
906 union {
907 float float32[4];
908 uint32_t uint32[4];
909 };
910 /* Pad out to 64 bytes */
911 uint32_t _pad[12];
912 };
913
914 static void
915 anv_device_init_border_colors(struct anv_device *device)
916 {
917 static const struct gen8_border_color border_colors[] = {
918 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
919 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
920 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
921 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
922 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
923 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
924 };
925
926 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
927 sizeof(border_colors), 64,
928 border_colors);
929 }
930
931 VkResult
932 anv_device_submit_simple_batch(struct anv_device *device,
933 struct anv_batch *batch)
934 {
935 struct drm_i915_gem_execbuffer2 execbuf;
936 struct drm_i915_gem_exec_object2 exec2_objects[1];
937 struct anv_bo bo, *exec_bos[1];
938 VkResult result = VK_SUCCESS;
939 uint32_t size;
940
941 /* Kernel driver requires 8 byte aligned batch length */
942 size = align_u32(batch->next - batch->start, 8);
943 result = anv_bo_pool_alloc(&device->batch_bo_pool, &bo, size);
944 if (result != VK_SUCCESS)
945 return result;
946
947 memcpy(bo.map, batch->start, size);
948 if (!device->info.has_llc)
949 anv_flush_range(bo.map, size);
950
951 exec_bos[0] = &bo;
952 exec2_objects[0].handle = bo.gem_handle;
953 exec2_objects[0].relocation_count = 0;
954 exec2_objects[0].relocs_ptr = 0;
955 exec2_objects[0].alignment = 0;
956 exec2_objects[0].offset = bo.offset;
957 exec2_objects[0].flags = 0;
958 exec2_objects[0].rsvd1 = 0;
959 exec2_objects[0].rsvd2 = 0;
960
961 execbuf.buffers_ptr = (uintptr_t) exec2_objects;
962 execbuf.buffer_count = 1;
963 execbuf.batch_start_offset = 0;
964 execbuf.batch_len = size;
965 execbuf.cliprects_ptr = 0;
966 execbuf.num_cliprects = 0;
967 execbuf.DR1 = 0;
968 execbuf.DR4 = 0;
969
970 execbuf.flags =
971 I915_EXEC_HANDLE_LUT | I915_EXEC_NO_RELOC | I915_EXEC_RENDER;
972 execbuf.rsvd1 = device->context_id;
973 execbuf.rsvd2 = 0;
974
975 result = anv_device_execbuf(device, &execbuf, exec_bos);
976 if (result != VK_SUCCESS)
977 goto fail;
978
979 result = anv_device_wait(device, &bo, INT64_MAX);
980
981 fail:
982 anv_bo_pool_free(&device->batch_bo_pool, &bo);
983
984 return result;
985 }
986
987 VkResult anv_CreateDevice(
988 VkPhysicalDevice physicalDevice,
989 const VkDeviceCreateInfo* pCreateInfo,
990 const VkAllocationCallbacks* pAllocator,
991 VkDevice* pDevice)
992 {
993 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
994 VkResult result;
995 struct anv_device *device;
996
997 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
998
999 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1000 bool found = false;
1001 for (uint32_t j = 0; j < ARRAY_SIZE(device_extensions); j++) {
1002 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
1003 device_extensions[j].extensionName) == 0) {
1004 found = true;
1005 break;
1006 }
1007 }
1008 if (!found)
1009 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
1010 }
1011
1012 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
1013 sizeof(*device), 8,
1014 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1015 if (!device)
1016 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1017
1018 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1019 device->instance = physical_device->instance;
1020 device->chipset_id = physical_device->chipset_id;
1021 device->lost = false;
1022
1023 if (pAllocator)
1024 device->alloc = *pAllocator;
1025 else
1026 device->alloc = physical_device->instance->alloc;
1027
1028 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
1029 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
1030 if (device->fd == -1) {
1031 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1032 goto fail_device;
1033 }
1034
1035 device->context_id = anv_gem_create_context(device);
1036 if (device->context_id == -1) {
1037 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1038 goto fail_fd;
1039 }
1040
1041 device->info = physical_device->info;
1042 device->isl_dev = physical_device->isl_dev;
1043
1044 /* On Broadwell and later, we can use batch chaining to more efficiently
1045 * implement growing command buffers. Prior to Haswell, the kernel
1046 * command parser gets in the way and we have to fall back to growing
1047 * the batch.
1048 */
1049 device->can_chain_batches = device->info.gen >= 8;
1050
1051 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1052 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1053
1054 if (pthread_mutex_init(&device->mutex, NULL) != 0) {
1055 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1056 goto fail_context_id;
1057 }
1058
1059 pthread_condattr_t condattr;
1060 if (pthread_condattr_init(&condattr) != 0) {
1061 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1062 goto fail_mutex;
1063 }
1064 if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
1065 pthread_condattr_destroy(&condattr);
1066 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1067 goto fail_mutex;
1068 }
1069 if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
1070 pthread_condattr_destroy(&condattr);
1071 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
1072 goto fail_mutex;
1073 }
1074 pthread_condattr_destroy(&condattr);
1075
1076 anv_bo_pool_init(&device->batch_bo_pool, device);
1077
1078 result = anv_block_pool_init(&device->dynamic_state_block_pool, device,
1079 16384);
1080 if (result != VK_SUCCESS)
1081 goto fail_batch_bo_pool;
1082
1083 anv_state_pool_init(&device->dynamic_state_pool,
1084 &device->dynamic_state_block_pool);
1085
1086 result = anv_block_pool_init(&device->instruction_block_pool, device,
1087 1024 * 1024);
1088 if (result != VK_SUCCESS)
1089 goto fail_dynamic_state_pool;
1090
1091 anv_state_pool_init(&device->instruction_state_pool,
1092 &device->instruction_block_pool);
1093
1094 result = anv_block_pool_init(&device->surface_state_block_pool, device,
1095 4096);
1096 if (result != VK_SUCCESS)
1097 goto fail_instruction_state_pool;
1098
1099 anv_state_pool_init(&device->surface_state_pool,
1100 &device->surface_state_block_pool);
1101
1102 result = anv_bo_init_new(&device->workaround_bo, device, 1024);
1103 if (result != VK_SUCCESS)
1104 goto fail_surface_state_pool;
1105
1106 anv_scratch_pool_init(device, &device->scratch_pool);
1107
1108 anv_queue_init(device, &device->queue);
1109
1110 switch (device->info.gen) {
1111 case 7:
1112 if (!device->info.is_haswell)
1113 result = gen7_init_device_state(device);
1114 else
1115 result = gen75_init_device_state(device);
1116 break;
1117 case 8:
1118 result = gen8_init_device_state(device);
1119 break;
1120 case 9:
1121 result = gen9_init_device_state(device);
1122 break;
1123 default:
1124 /* Shouldn't get here as we don't create physical devices for any other
1125 * gens. */
1126 unreachable("unhandled gen");
1127 }
1128 if (result != VK_SUCCESS)
1129 goto fail_workaround_bo;
1130
1131 anv_device_init_blorp(device);
1132
1133 anv_device_init_border_colors(device);
1134
1135 *pDevice = anv_device_to_handle(device);
1136
1137 return VK_SUCCESS;
1138
1139 fail_workaround_bo:
1140 anv_queue_finish(&device->queue);
1141 anv_scratch_pool_finish(device, &device->scratch_pool);
1142 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1143 anv_gem_close(device, device->workaround_bo.gem_handle);
1144 fail_surface_state_pool:
1145 anv_state_pool_finish(&device->surface_state_pool);
1146 anv_block_pool_finish(&device->surface_state_block_pool);
1147 fail_instruction_state_pool:
1148 anv_state_pool_finish(&device->instruction_state_pool);
1149 anv_block_pool_finish(&device->instruction_block_pool);
1150 fail_dynamic_state_pool:
1151 anv_state_pool_finish(&device->dynamic_state_pool);
1152 anv_block_pool_finish(&device->dynamic_state_block_pool);
1153 fail_batch_bo_pool:
1154 anv_bo_pool_finish(&device->batch_bo_pool);
1155 pthread_cond_destroy(&device->queue_submit);
1156 fail_mutex:
1157 pthread_mutex_destroy(&device->mutex);
1158 fail_context_id:
1159 anv_gem_destroy_context(device, device->context_id);
1160 fail_fd:
1161 close(device->fd);
1162 fail_device:
1163 vk_free(&device->alloc, device);
1164
1165 return result;
1166 }
1167
1168 void anv_DestroyDevice(
1169 VkDevice _device,
1170 const VkAllocationCallbacks* pAllocator)
1171 {
1172 ANV_FROM_HANDLE(anv_device, device, _device);
1173
1174 if (!device)
1175 return;
1176
1177 anv_device_finish_blorp(device);
1178
1179 anv_queue_finish(&device->queue);
1180
1181 #ifdef HAVE_VALGRIND
1182 /* We only need to free these to prevent valgrind errors. The backing
1183 * BO will go away in a couple of lines so we don't actually leak.
1184 */
1185 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1186 #endif
1187
1188 anv_scratch_pool_finish(device, &device->scratch_pool);
1189
1190 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1191 anv_gem_close(device, device->workaround_bo.gem_handle);
1192
1193 anv_state_pool_finish(&device->surface_state_pool);
1194 anv_block_pool_finish(&device->surface_state_block_pool);
1195 anv_state_pool_finish(&device->instruction_state_pool);
1196 anv_block_pool_finish(&device->instruction_block_pool);
1197 anv_state_pool_finish(&device->dynamic_state_pool);
1198 anv_block_pool_finish(&device->dynamic_state_block_pool);
1199
1200 anv_bo_pool_finish(&device->batch_bo_pool);
1201
1202 pthread_cond_destroy(&device->queue_submit);
1203 pthread_mutex_destroy(&device->mutex);
1204
1205 anv_gem_destroy_context(device, device->context_id);
1206
1207 close(device->fd);
1208
1209 vk_free(&device->alloc, device);
1210 }
1211
1212 VkResult anv_EnumerateInstanceExtensionProperties(
1213 const char* pLayerName,
1214 uint32_t* pPropertyCount,
1215 VkExtensionProperties* pProperties)
1216 {
1217 if (pProperties == NULL) {
1218 *pPropertyCount = ARRAY_SIZE(global_extensions);
1219 return VK_SUCCESS;
1220 }
1221
1222 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(global_extensions));
1223 typed_memcpy(pProperties, global_extensions, *pPropertyCount);
1224
1225 if (*pPropertyCount < ARRAY_SIZE(global_extensions))
1226 return VK_INCOMPLETE;
1227
1228 return VK_SUCCESS;
1229 }
1230
1231 VkResult anv_EnumerateDeviceExtensionProperties(
1232 VkPhysicalDevice physicalDevice,
1233 const char* pLayerName,
1234 uint32_t* pPropertyCount,
1235 VkExtensionProperties* pProperties)
1236 {
1237 if (pProperties == NULL) {
1238 *pPropertyCount = ARRAY_SIZE(device_extensions);
1239 return VK_SUCCESS;
1240 }
1241
1242 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(device_extensions));
1243 typed_memcpy(pProperties, device_extensions, *pPropertyCount);
1244
1245 if (*pPropertyCount < ARRAY_SIZE(device_extensions))
1246 return VK_INCOMPLETE;
1247
1248 return VK_SUCCESS;
1249 }
1250
1251 VkResult anv_EnumerateInstanceLayerProperties(
1252 uint32_t* pPropertyCount,
1253 VkLayerProperties* pProperties)
1254 {
1255 if (pProperties == NULL) {
1256 *pPropertyCount = 0;
1257 return VK_SUCCESS;
1258 }
1259
1260 /* None supported at this time */
1261 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1262 }
1263
1264 VkResult anv_EnumerateDeviceLayerProperties(
1265 VkPhysicalDevice physicalDevice,
1266 uint32_t* pPropertyCount,
1267 VkLayerProperties* pProperties)
1268 {
1269 if (pProperties == NULL) {
1270 *pPropertyCount = 0;
1271 return VK_SUCCESS;
1272 }
1273
1274 /* None supported at this time */
1275 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1276 }
1277
1278 void anv_GetDeviceQueue(
1279 VkDevice _device,
1280 uint32_t queueNodeIndex,
1281 uint32_t queueIndex,
1282 VkQueue* pQueue)
1283 {
1284 ANV_FROM_HANDLE(anv_device, device, _device);
1285
1286 assert(queueIndex == 0);
1287
1288 *pQueue = anv_queue_to_handle(&device->queue);
1289 }
1290
1291 VkResult
1292 anv_device_execbuf(struct anv_device *device,
1293 struct drm_i915_gem_execbuffer2 *execbuf,
1294 struct anv_bo **execbuf_bos)
1295 {
1296 int ret = anv_gem_execbuffer(device, execbuf);
1297 if (ret != 0) {
1298 /* We don't know the real error. */
1299 device->lost = true;
1300 return vk_errorf(VK_ERROR_DEVICE_LOST, "execbuf2 failed: %m");
1301 }
1302
1303 struct drm_i915_gem_exec_object2 *objects =
1304 (void *)(uintptr_t)execbuf->buffers_ptr;
1305 for (uint32_t k = 0; k < execbuf->buffer_count; k++)
1306 execbuf_bos[k]->offset = objects[k].offset;
1307
1308 return VK_SUCCESS;
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_QueueSubmit(
1389 VkQueue _queue,
1390 uint32_t submitCount,
1391 const VkSubmitInfo* pSubmits,
1392 VkFence _fence)
1393 {
1394 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1395 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1396 struct anv_device *device = queue->device;
1397
1398 /* Query for device status prior to submitting. Technically, we don't need
1399 * to do this. However, if we have a client that's submitting piles of
1400 * garbage, we would rather break as early as possible to keep the GPU
1401 * hanging contained. If we don't check here, we'll either be waiting for
1402 * the kernel to kick us or we'll have to wait until the client waits on a
1403 * fence before we actually know whether or not we've hung.
1404 */
1405 VkResult result = anv_device_query_status(device);
1406 if (result != VK_SUCCESS)
1407 return result;
1408
1409 /* We lock around QueueSubmit for three main reasons:
1410 *
1411 * 1) When a block pool is resized, we create a new gem handle with a
1412 * different size and, in the case of surface states, possibly a
1413 * different center offset but we re-use the same anv_bo struct when
1414 * we do so. If this happens in the middle of setting up an execbuf,
1415 * we could end up with our list of BOs out of sync with our list of
1416 * gem handles.
1417 *
1418 * 2) The algorithm we use for building the list of unique buffers isn't
1419 * thread-safe. While the client is supposed to syncronize around
1420 * QueueSubmit, this would be extremely difficult to debug if it ever
1421 * came up in the wild due to a broken app. It's better to play it
1422 * safe and just lock around QueueSubmit.
1423 *
1424 * 3) The anv_cmd_buffer_execbuf function may perform relocations in
1425 * userspace. Due to the fact that the surface state buffer is shared
1426 * between batches, we can't afford to have that happen from multiple
1427 * threads at the same time. Even though the user is supposed to
1428 * ensure this doesn't happen, we play it safe as in (2) above.
1429 *
1430 * Since the only other things that ever take the device lock such as block
1431 * pool resize only rarely happen, this will almost never be contended so
1432 * taking a lock isn't really an expensive operation in this case.
1433 */
1434 pthread_mutex_lock(&device->mutex);
1435
1436 for (uint32_t i = 0; i < submitCount; i++) {
1437 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
1438 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer,
1439 pSubmits[i].pCommandBuffers[j]);
1440 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1441 assert(!anv_batch_has_error(&cmd_buffer->batch));
1442
1443 result = anv_cmd_buffer_execbuf(device, cmd_buffer);
1444 if (result != VK_SUCCESS)
1445 goto out;
1446 }
1447 }
1448
1449 if (fence) {
1450 struct anv_bo *fence_bo = &fence->bo;
1451 result = anv_device_execbuf(device, &fence->execbuf, &fence_bo);
1452 if (result != VK_SUCCESS)
1453 goto out;
1454
1455 /* Update the fence and wake up any waiters */
1456 assert(fence->state == ANV_FENCE_STATE_RESET);
1457 fence->state = ANV_FENCE_STATE_SUBMITTED;
1458 pthread_cond_broadcast(&device->queue_submit);
1459 }
1460
1461 out:
1462 if (result != VK_SUCCESS) {
1463 /* In the case that something has gone wrong we may end up with an
1464 * inconsistent state from which it may not be trivial to recover.
1465 * For example, we might have computed address relocations and
1466 * any future attempt to re-submit this job will need to know about
1467 * this and avoid computing relocation addresses again.
1468 *
1469 * To avoid this sort of issues, we assume that if something was
1470 * wrong during submission we must already be in a really bad situation
1471 * anyway (such us being out of memory) and return
1472 * VK_ERROR_DEVICE_LOST to ensure that clients do not attempt to
1473 * submit the same job again to this device.
1474 */
1475 result = VK_ERROR_DEVICE_LOST;
1476 device->lost = true;
1477
1478 /* If we return VK_ERROR_DEVICE LOST here, we need to ensure that
1479 * vkWaitForFences() and vkGetFenceStatus() return a valid result
1480 * (VK_SUCCESS or VK_ERROR_DEVICE_LOST) in a finite amount of time.
1481 * Setting the fence status to SIGNALED ensures this will happen in
1482 * any case.
1483 */
1484 if (fence)
1485 fence->state = ANV_FENCE_STATE_SIGNALED;
1486 }
1487
1488 pthread_mutex_unlock(&device->mutex);
1489
1490 return result;
1491 }
1492
1493 VkResult anv_QueueWaitIdle(
1494 VkQueue _queue)
1495 {
1496 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1497
1498 return anv_DeviceWaitIdle(anv_device_to_handle(queue->device));
1499 }
1500
1501 VkResult anv_DeviceWaitIdle(
1502 VkDevice _device)
1503 {
1504 ANV_FROM_HANDLE(anv_device, device, _device);
1505 if (unlikely(device->lost))
1506 return VK_ERROR_DEVICE_LOST;
1507
1508 struct anv_batch batch;
1509
1510 uint32_t cmds[8];
1511 batch.start = batch.next = cmds;
1512 batch.end = (void *) cmds + sizeof(cmds);
1513
1514 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1515 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1516
1517 return anv_device_submit_simple_batch(device, &batch);
1518 }
1519
1520 VkResult
1521 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
1522 {
1523 uint32_t gem_handle = anv_gem_create(device, size);
1524 if (!gem_handle)
1525 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1526
1527 anv_bo_init(bo, gem_handle, size);
1528
1529 if (device->instance->physicalDevice.supports_48bit_addresses)
1530 bo->flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
1531
1532 if (device->instance->physicalDevice.has_exec_async)
1533 bo->flags |= EXEC_OBJECT_ASYNC;
1534
1535 return VK_SUCCESS;
1536 }
1537
1538 VkResult anv_AllocateMemory(
1539 VkDevice _device,
1540 const VkMemoryAllocateInfo* pAllocateInfo,
1541 const VkAllocationCallbacks* pAllocator,
1542 VkDeviceMemory* pMem)
1543 {
1544 ANV_FROM_HANDLE(anv_device, device, _device);
1545 struct anv_device_memory *mem;
1546 VkResult result;
1547
1548 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1549
1550 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
1551 assert(pAllocateInfo->allocationSize > 0);
1552
1553 /* We support exactly one memory heap. */
1554 assert(pAllocateInfo->memoryTypeIndex == 0 ||
1555 (!device->info.has_llc && pAllocateInfo->memoryTypeIndex < 2));
1556
1557 /* The kernel relocation API has a limitation of a 32-bit delta value
1558 * applied to the address before it is written which, in spite of it being
1559 * unsigned, is treated as signed . Because of the way that this maps to
1560 * the Vulkan API, we cannot handle an offset into a buffer that does not
1561 * fit into a signed 32 bits. The only mechanism we have for dealing with
1562 * this at the moment is to limit all VkDeviceMemory objects to a maximum
1563 * of 2GB each. The Vulkan spec allows us to do this:
1564 *
1565 * "Some platforms may have a limit on the maximum size of a single
1566 * allocation. For example, certain systems may fail to create
1567 * allocations with a size greater than or equal to 4GB. Such a limit is
1568 * implementation-dependent, and if such a failure occurs then the error
1569 * VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
1570 *
1571 * We don't use vk_error here because it's not an error so much as an
1572 * indication to the application that the allocation is too large.
1573 */
1574 if (pAllocateInfo->allocationSize > (1ull << 31))
1575 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1576
1577 /* FINISHME: Fail if allocation request exceeds heap size. */
1578
1579 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1580 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1581 if (mem == NULL)
1582 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1583
1584 /* The kernel is going to give us whole pages anyway */
1585 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
1586
1587 result = anv_bo_init_new(&mem->bo, device, alloc_size);
1588 if (result != VK_SUCCESS)
1589 goto fail;
1590
1591 mem->type_index = pAllocateInfo->memoryTypeIndex;
1592
1593 mem->map = NULL;
1594 mem->map_size = 0;
1595
1596 *pMem = anv_device_memory_to_handle(mem);
1597
1598 return VK_SUCCESS;
1599
1600 fail:
1601 vk_free2(&device->alloc, pAllocator, mem);
1602
1603 return result;
1604 }
1605
1606 void anv_FreeMemory(
1607 VkDevice _device,
1608 VkDeviceMemory _mem,
1609 const VkAllocationCallbacks* pAllocator)
1610 {
1611 ANV_FROM_HANDLE(anv_device, device, _device);
1612 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
1613
1614 if (mem == NULL)
1615 return;
1616
1617 if (mem->map)
1618 anv_UnmapMemory(_device, _mem);
1619
1620 if (mem->bo.map)
1621 anv_gem_munmap(mem->bo.map, mem->bo.size);
1622
1623 if (mem->bo.gem_handle != 0)
1624 anv_gem_close(device, mem->bo.gem_handle);
1625
1626 vk_free2(&device->alloc, pAllocator, mem);
1627 }
1628
1629 VkResult anv_MapMemory(
1630 VkDevice _device,
1631 VkDeviceMemory _memory,
1632 VkDeviceSize offset,
1633 VkDeviceSize size,
1634 VkMemoryMapFlags flags,
1635 void** ppData)
1636 {
1637 ANV_FROM_HANDLE(anv_device, device, _device);
1638 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1639
1640 if (mem == NULL) {
1641 *ppData = NULL;
1642 return VK_SUCCESS;
1643 }
1644
1645 if (size == VK_WHOLE_SIZE)
1646 size = mem->bo.size - offset;
1647
1648 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
1649 *
1650 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
1651 * assert(size != 0);
1652 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
1653 * equal to the size of the memory minus offset
1654 */
1655 assert(size > 0);
1656 assert(offset + size <= mem->bo.size);
1657
1658 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
1659 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
1660 * at a time is valid. We could just mmap up front and return an offset
1661 * pointer here, but that may exhaust virtual memory on 32 bit
1662 * userspace. */
1663
1664 uint32_t gem_flags = 0;
1665 if (!device->info.has_llc && mem->type_index == 0)
1666 gem_flags |= I915_MMAP_WC;
1667
1668 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
1669 uint64_t map_offset = offset & ~4095ull;
1670 assert(offset >= map_offset);
1671 uint64_t map_size = (offset + size) - map_offset;
1672
1673 /* Let's map whole pages */
1674 map_size = align_u64(map_size, 4096);
1675
1676 void *map = anv_gem_mmap(device, mem->bo.gem_handle,
1677 map_offset, map_size, gem_flags);
1678 if (map == MAP_FAILED)
1679 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1680
1681 mem->map = map;
1682 mem->map_size = map_size;
1683
1684 *ppData = mem->map + (offset - map_offset);
1685
1686 return VK_SUCCESS;
1687 }
1688
1689 void anv_UnmapMemory(
1690 VkDevice _device,
1691 VkDeviceMemory _memory)
1692 {
1693 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1694
1695 if (mem == NULL)
1696 return;
1697
1698 anv_gem_munmap(mem->map, mem->map_size);
1699
1700 mem->map = NULL;
1701 mem->map_size = 0;
1702 }
1703
1704 static void
1705 clflush_mapped_ranges(struct anv_device *device,
1706 uint32_t count,
1707 const VkMappedMemoryRange *ranges)
1708 {
1709 for (uint32_t i = 0; i < count; i++) {
1710 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
1711 if (ranges[i].offset >= mem->map_size)
1712 continue;
1713
1714 anv_clflush_range(mem->map + ranges[i].offset,
1715 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
1716 }
1717 }
1718
1719 VkResult anv_FlushMappedMemoryRanges(
1720 VkDevice _device,
1721 uint32_t memoryRangeCount,
1722 const VkMappedMemoryRange* pMemoryRanges)
1723 {
1724 ANV_FROM_HANDLE(anv_device, device, _device);
1725
1726 if (device->info.has_llc)
1727 return VK_SUCCESS;
1728
1729 /* Make sure the writes we're flushing have landed. */
1730 __builtin_ia32_mfence();
1731
1732 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1733
1734 return VK_SUCCESS;
1735 }
1736
1737 VkResult anv_InvalidateMappedMemoryRanges(
1738 VkDevice _device,
1739 uint32_t memoryRangeCount,
1740 const VkMappedMemoryRange* pMemoryRanges)
1741 {
1742 ANV_FROM_HANDLE(anv_device, device, _device);
1743
1744 if (device->info.has_llc)
1745 return VK_SUCCESS;
1746
1747 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1748
1749 /* Make sure no reads get moved up above the invalidate. */
1750 __builtin_ia32_mfence();
1751
1752 return VK_SUCCESS;
1753 }
1754
1755 void anv_GetBufferMemoryRequirements(
1756 VkDevice _device,
1757 VkBuffer _buffer,
1758 VkMemoryRequirements* pMemoryRequirements)
1759 {
1760 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1761 ANV_FROM_HANDLE(anv_device, device, _device);
1762
1763 /* The Vulkan spec (git aaed022) says:
1764 *
1765 * memoryTypeBits is a bitfield and contains one bit set for every
1766 * supported memory type for the resource. The bit `1<<i` is set if and
1767 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1768 * structure for the physical device is supported.
1769 *
1770 * We support exactly one memory type on LLC, two on non-LLC.
1771 */
1772 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1773
1774 pMemoryRequirements->size = buffer->size;
1775 pMemoryRequirements->alignment = 16;
1776 }
1777
1778 void anv_GetImageMemoryRequirements(
1779 VkDevice _device,
1780 VkImage _image,
1781 VkMemoryRequirements* pMemoryRequirements)
1782 {
1783 ANV_FROM_HANDLE(anv_image, image, _image);
1784 ANV_FROM_HANDLE(anv_device, device, _device);
1785
1786 /* The Vulkan spec (git aaed022) says:
1787 *
1788 * memoryTypeBits is a bitfield and contains one bit set for every
1789 * supported memory type for the resource. The bit `1<<i` is set if and
1790 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1791 * structure for the physical device is supported.
1792 *
1793 * We support exactly one memory type on LLC, two on non-LLC.
1794 */
1795 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1796
1797 pMemoryRequirements->size = image->size;
1798 pMemoryRequirements->alignment = image->alignment;
1799 }
1800
1801 void anv_GetImageSparseMemoryRequirements(
1802 VkDevice device,
1803 VkImage image,
1804 uint32_t* pSparseMemoryRequirementCount,
1805 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
1806 {
1807 *pSparseMemoryRequirementCount = 0;
1808 }
1809
1810 void anv_GetDeviceMemoryCommitment(
1811 VkDevice device,
1812 VkDeviceMemory memory,
1813 VkDeviceSize* pCommittedMemoryInBytes)
1814 {
1815 *pCommittedMemoryInBytes = 0;
1816 }
1817
1818 VkResult anv_BindBufferMemory(
1819 VkDevice device,
1820 VkBuffer _buffer,
1821 VkDeviceMemory _memory,
1822 VkDeviceSize memoryOffset)
1823 {
1824 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1825 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1826
1827 if (mem) {
1828 buffer->bo = &mem->bo;
1829 buffer->offset = memoryOffset;
1830 } else {
1831 buffer->bo = NULL;
1832 buffer->offset = 0;
1833 }
1834
1835 return VK_SUCCESS;
1836 }
1837
1838 VkResult anv_QueueBindSparse(
1839 VkQueue _queue,
1840 uint32_t bindInfoCount,
1841 const VkBindSparseInfo* pBindInfo,
1842 VkFence fence)
1843 {
1844 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1845 if (unlikely(queue->device->lost))
1846 return VK_ERROR_DEVICE_LOST;
1847
1848 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1849 }
1850
1851 VkResult anv_CreateFence(
1852 VkDevice _device,
1853 const VkFenceCreateInfo* pCreateInfo,
1854 const VkAllocationCallbacks* pAllocator,
1855 VkFence* pFence)
1856 {
1857 ANV_FROM_HANDLE(anv_device, device, _device);
1858 struct anv_bo fence_bo;
1859 struct anv_fence *fence;
1860 struct anv_batch batch;
1861 VkResult result;
1862
1863 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FENCE_CREATE_INFO);
1864
1865 result = anv_bo_pool_alloc(&device->batch_bo_pool, &fence_bo, 4096);
1866 if (result != VK_SUCCESS)
1867 return result;
1868
1869 /* Fences are small. Just store the CPU data structure in the BO. */
1870 fence = fence_bo.map;
1871 fence->bo = fence_bo;
1872
1873 /* Place the batch after the CPU data but on its own cache line. */
1874 const uint32_t batch_offset = align_u32(sizeof(*fence), CACHELINE_SIZE);
1875 batch.next = batch.start = fence->bo.map + batch_offset;
1876 batch.end = fence->bo.map + fence->bo.size;
1877 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1878 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1879
1880 if (!device->info.has_llc) {
1881 assert(((uintptr_t) batch.start & CACHELINE_MASK) == 0);
1882 assert(batch.next - batch.start <= CACHELINE_SIZE);
1883 __builtin_ia32_mfence();
1884 __builtin_ia32_clflush(batch.start);
1885 }
1886
1887 fence->exec2_objects[0].handle = fence->bo.gem_handle;
1888 fence->exec2_objects[0].relocation_count = 0;
1889 fence->exec2_objects[0].relocs_ptr = 0;
1890 fence->exec2_objects[0].alignment = 0;
1891 fence->exec2_objects[0].offset = fence->bo.offset;
1892 fence->exec2_objects[0].flags = 0;
1893 fence->exec2_objects[0].rsvd1 = 0;
1894 fence->exec2_objects[0].rsvd2 = 0;
1895
1896 fence->execbuf.buffers_ptr = (uintptr_t) fence->exec2_objects;
1897 fence->execbuf.buffer_count = 1;
1898 fence->execbuf.batch_start_offset = batch.start - fence->bo.map;
1899 fence->execbuf.batch_len = batch.next - batch.start;
1900 fence->execbuf.cliprects_ptr = 0;
1901 fence->execbuf.num_cliprects = 0;
1902 fence->execbuf.DR1 = 0;
1903 fence->execbuf.DR4 = 0;
1904
1905 fence->execbuf.flags =
1906 I915_EXEC_HANDLE_LUT | I915_EXEC_NO_RELOC | I915_EXEC_RENDER;
1907 fence->execbuf.rsvd1 = device->context_id;
1908 fence->execbuf.rsvd2 = 0;
1909
1910 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
1911 fence->state = ANV_FENCE_STATE_SIGNALED;
1912 } else {
1913 fence->state = ANV_FENCE_STATE_RESET;
1914 }
1915
1916 *pFence = anv_fence_to_handle(fence);
1917
1918 return VK_SUCCESS;
1919 }
1920
1921 void anv_DestroyFence(
1922 VkDevice _device,
1923 VkFence _fence,
1924 const VkAllocationCallbacks* pAllocator)
1925 {
1926 ANV_FROM_HANDLE(anv_device, device, _device);
1927 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1928
1929 if (!fence)
1930 return;
1931
1932 assert(fence->bo.map == fence);
1933 anv_bo_pool_free(&device->batch_bo_pool, &fence->bo);
1934 }
1935
1936 VkResult anv_ResetFences(
1937 VkDevice _device,
1938 uint32_t fenceCount,
1939 const VkFence* pFences)
1940 {
1941 for (uint32_t i = 0; i < fenceCount; i++) {
1942 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
1943 fence->state = ANV_FENCE_STATE_RESET;
1944 }
1945
1946 return VK_SUCCESS;
1947 }
1948
1949 VkResult anv_GetFenceStatus(
1950 VkDevice _device,
1951 VkFence _fence)
1952 {
1953 ANV_FROM_HANDLE(anv_device, device, _device);
1954 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1955
1956 if (unlikely(device->lost))
1957 return VK_ERROR_DEVICE_LOST;
1958
1959 switch (fence->state) {
1960 case ANV_FENCE_STATE_RESET:
1961 /* If it hasn't even been sent off to the GPU yet, it's not ready */
1962 return VK_NOT_READY;
1963
1964 case ANV_FENCE_STATE_SIGNALED:
1965 /* It's been signaled, return success */
1966 return VK_SUCCESS;
1967
1968 case ANV_FENCE_STATE_SUBMITTED: {
1969 VkResult result = anv_device_bo_busy(device, &fence->bo);
1970 if (result == VK_SUCCESS) {
1971 fence->state = ANV_FENCE_STATE_SIGNALED;
1972 return VK_SUCCESS;
1973 } else {
1974 return result;
1975 }
1976 }
1977 default:
1978 unreachable("Invalid fence status");
1979 }
1980 }
1981
1982 #define NSEC_PER_SEC 1000000000
1983 #define INT_TYPE_MAX(type) ((1ull << (sizeof(type) * 8 - 1)) - 1)
1984
1985 VkResult anv_WaitForFences(
1986 VkDevice _device,
1987 uint32_t fenceCount,
1988 const VkFence* pFences,
1989 VkBool32 waitAll,
1990 uint64_t _timeout)
1991 {
1992 ANV_FROM_HANDLE(anv_device, device, _device);
1993 int ret;
1994
1995 if (unlikely(device->lost))
1996 return VK_ERROR_DEVICE_LOST;
1997
1998 /* DRM_IOCTL_I915_GEM_WAIT uses a signed 64 bit timeout and is supposed
1999 * to block indefinitely timeouts <= 0. Unfortunately, this was broken
2000 * for a couple of kernel releases. Since there's no way to know
2001 * whether or not the kernel we're using is one of the broken ones, the
2002 * best we can do is to clamp the timeout to INT64_MAX. This limits the
2003 * maximum timeout from 584 years to 292 years - likely not a big deal.
2004 */
2005 int64_t timeout = MIN2(_timeout, INT64_MAX);
2006
2007 VkResult result = VK_SUCCESS;
2008 uint32_t pending_fences = fenceCount;
2009 while (pending_fences) {
2010 pending_fences = 0;
2011 bool signaled_fences = false;
2012 for (uint32_t i = 0; i < fenceCount; i++) {
2013 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
2014 switch (fence->state) {
2015 case ANV_FENCE_STATE_RESET:
2016 /* This fence hasn't been submitted yet, we'll catch it the next
2017 * time around. Yes, this may mean we dead-loop but, short of
2018 * lots of locking and a condition variable, there's not much that
2019 * we can do about that.
2020 */
2021 pending_fences++;
2022 continue;
2023
2024 case ANV_FENCE_STATE_SIGNALED:
2025 /* This fence is not pending. If waitAll isn't set, we can return
2026 * early. Otherwise, we have to keep going.
2027 */
2028 if (!waitAll) {
2029 result = VK_SUCCESS;
2030 goto done;
2031 }
2032 continue;
2033
2034 case ANV_FENCE_STATE_SUBMITTED:
2035 /* These are the fences we really care about. Go ahead and wait
2036 * on it until we hit a timeout.
2037 */
2038 result = anv_device_wait(device, &fence->bo, timeout);
2039 switch (result) {
2040 case VK_SUCCESS:
2041 fence->state = ANV_FENCE_STATE_SIGNALED;
2042 signaled_fences = true;
2043 if (!waitAll)
2044 goto done;
2045 break;
2046
2047 case VK_TIMEOUT:
2048 goto done;
2049
2050 default:
2051 return result;
2052 }
2053 }
2054 }
2055
2056 if (pending_fences && !signaled_fences) {
2057 /* If we've hit this then someone decided to vkWaitForFences before
2058 * they've actually submitted any of them to a queue. This is a
2059 * fairly pessimal case, so it's ok to lock here and use a standard
2060 * pthreads condition variable.
2061 */
2062 pthread_mutex_lock(&device->mutex);
2063
2064 /* It's possible that some of the fences have changed state since the
2065 * last time we checked. Now that we have the lock, check for
2066 * pending fences again and don't wait if it's changed.
2067 */
2068 uint32_t now_pending_fences = 0;
2069 for (uint32_t i = 0; i < fenceCount; i++) {
2070 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
2071 if (fence->state == ANV_FENCE_STATE_RESET)
2072 now_pending_fences++;
2073 }
2074 assert(now_pending_fences <= pending_fences);
2075
2076 if (now_pending_fences == pending_fences) {
2077 struct timespec before;
2078 clock_gettime(CLOCK_MONOTONIC, &before);
2079
2080 uint32_t abs_nsec = before.tv_nsec + timeout % NSEC_PER_SEC;
2081 uint64_t abs_sec = before.tv_sec + (abs_nsec / NSEC_PER_SEC) +
2082 (timeout / NSEC_PER_SEC);
2083 abs_nsec %= NSEC_PER_SEC;
2084
2085 /* Avoid roll-over in tv_sec on 32-bit systems if the user
2086 * provided timeout is UINT64_MAX
2087 */
2088 struct timespec abstime;
2089 abstime.tv_nsec = abs_nsec;
2090 abstime.tv_sec = MIN2(abs_sec, INT_TYPE_MAX(abstime.tv_sec));
2091
2092 ret = pthread_cond_timedwait(&device->queue_submit,
2093 &device->mutex, &abstime);
2094 assert(ret != EINVAL);
2095
2096 struct timespec after;
2097 clock_gettime(CLOCK_MONOTONIC, &after);
2098 uint64_t time_elapsed =
2099 ((uint64_t)after.tv_sec * NSEC_PER_SEC + after.tv_nsec) -
2100 ((uint64_t)before.tv_sec * NSEC_PER_SEC + before.tv_nsec);
2101
2102 if (time_elapsed >= timeout) {
2103 pthread_mutex_unlock(&device->mutex);
2104 result = VK_TIMEOUT;
2105 goto done;
2106 }
2107
2108 timeout -= time_elapsed;
2109 }
2110
2111 pthread_mutex_unlock(&device->mutex);
2112 }
2113 }
2114
2115 done:
2116 if (unlikely(device->lost))
2117 return VK_ERROR_DEVICE_LOST;
2118
2119 return result;
2120 }
2121
2122 // Queue semaphore functions
2123
2124 VkResult anv_CreateSemaphore(
2125 VkDevice device,
2126 const VkSemaphoreCreateInfo* pCreateInfo,
2127 const VkAllocationCallbacks* pAllocator,
2128 VkSemaphore* pSemaphore)
2129 {
2130 /* The DRM execbuffer ioctl always execute in-oder, even between different
2131 * rings. As such, there's nothing to do for the user space semaphore.
2132 */
2133
2134 *pSemaphore = (VkSemaphore)1;
2135
2136 return VK_SUCCESS;
2137 }
2138
2139 void anv_DestroySemaphore(
2140 VkDevice device,
2141 VkSemaphore semaphore,
2142 const VkAllocationCallbacks* pAllocator)
2143 {
2144 }
2145
2146 // Event functions
2147
2148 VkResult anv_CreateEvent(
2149 VkDevice _device,
2150 const VkEventCreateInfo* pCreateInfo,
2151 const VkAllocationCallbacks* pAllocator,
2152 VkEvent* pEvent)
2153 {
2154 ANV_FROM_HANDLE(anv_device, device, _device);
2155 struct anv_state state;
2156 struct anv_event *event;
2157
2158 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2159
2160 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2161 sizeof(*event), 8);
2162 event = state.map;
2163 event->state = state;
2164 event->semaphore = VK_EVENT_RESET;
2165
2166 if (!device->info.has_llc) {
2167 /* Make sure the writes we're flushing have landed. */
2168 __builtin_ia32_mfence();
2169 __builtin_ia32_clflush(event);
2170 }
2171
2172 *pEvent = anv_event_to_handle(event);
2173
2174 return VK_SUCCESS;
2175 }
2176
2177 void anv_DestroyEvent(
2178 VkDevice _device,
2179 VkEvent _event,
2180 const VkAllocationCallbacks* pAllocator)
2181 {
2182 ANV_FROM_HANDLE(anv_device, device, _device);
2183 ANV_FROM_HANDLE(anv_event, event, _event);
2184
2185 if (!event)
2186 return;
2187
2188 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2189 }
2190
2191 VkResult anv_GetEventStatus(
2192 VkDevice _device,
2193 VkEvent _event)
2194 {
2195 ANV_FROM_HANDLE(anv_device, device, _device);
2196 ANV_FROM_HANDLE(anv_event, event, _event);
2197
2198 if (unlikely(device->lost))
2199 return VK_ERROR_DEVICE_LOST;
2200
2201 if (!device->info.has_llc) {
2202 /* Invalidate read cache before reading event written by GPU. */
2203 __builtin_ia32_clflush(event);
2204 __builtin_ia32_mfence();
2205
2206 }
2207
2208 return event->semaphore;
2209 }
2210
2211 VkResult anv_SetEvent(
2212 VkDevice _device,
2213 VkEvent _event)
2214 {
2215 ANV_FROM_HANDLE(anv_device, device, _device);
2216 ANV_FROM_HANDLE(anv_event, event, _event);
2217
2218 event->semaphore = VK_EVENT_SET;
2219
2220 if (!device->info.has_llc) {
2221 /* Make sure the writes we're flushing have landed. */
2222 __builtin_ia32_mfence();
2223 __builtin_ia32_clflush(event);
2224 }
2225
2226 return VK_SUCCESS;
2227 }
2228
2229 VkResult anv_ResetEvent(
2230 VkDevice _device,
2231 VkEvent _event)
2232 {
2233 ANV_FROM_HANDLE(anv_device, device, _device);
2234 ANV_FROM_HANDLE(anv_event, event, _event);
2235
2236 event->semaphore = VK_EVENT_RESET;
2237
2238 if (!device->info.has_llc) {
2239 /* Make sure the writes we're flushing have landed. */
2240 __builtin_ia32_mfence();
2241 __builtin_ia32_clflush(event);
2242 }
2243
2244 return VK_SUCCESS;
2245 }
2246
2247 // Buffer functions
2248
2249 VkResult anv_CreateBuffer(
2250 VkDevice _device,
2251 const VkBufferCreateInfo* pCreateInfo,
2252 const VkAllocationCallbacks* pAllocator,
2253 VkBuffer* pBuffer)
2254 {
2255 ANV_FROM_HANDLE(anv_device, device, _device);
2256 struct anv_buffer *buffer;
2257
2258 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2259
2260 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2261 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2262 if (buffer == NULL)
2263 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2264
2265 buffer->size = pCreateInfo->size;
2266 buffer->usage = pCreateInfo->usage;
2267 buffer->bo = NULL;
2268 buffer->offset = 0;
2269
2270 *pBuffer = anv_buffer_to_handle(buffer);
2271
2272 return VK_SUCCESS;
2273 }
2274
2275 void anv_DestroyBuffer(
2276 VkDevice _device,
2277 VkBuffer _buffer,
2278 const VkAllocationCallbacks* pAllocator)
2279 {
2280 ANV_FROM_HANDLE(anv_device, device, _device);
2281 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2282
2283 if (!buffer)
2284 return;
2285
2286 vk_free2(&device->alloc, pAllocator, buffer);
2287 }
2288
2289 void
2290 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2291 enum isl_format format,
2292 uint32_t offset, uint32_t range, uint32_t stride)
2293 {
2294 isl_buffer_fill_state(&device->isl_dev, state.map,
2295 .address = offset,
2296 .mocs = device->default_mocs,
2297 .size = range,
2298 .format = format,
2299 .stride = stride);
2300
2301 anv_state_flush(device, state);
2302 }
2303
2304 void anv_DestroySampler(
2305 VkDevice _device,
2306 VkSampler _sampler,
2307 const VkAllocationCallbacks* pAllocator)
2308 {
2309 ANV_FROM_HANDLE(anv_device, device, _device);
2310 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2311
2312 if (!sampler)
2313 return;
2314
2315 vk_free2(&device->alloc, pAllocator, sampler);
2316 }
2317
2318 VkResult anv_CreateFramebuffer(
2319 VkDevice _device,
2320 const VkFramebufferCreateInfo* pCreateInfo,
2321 const VkAllocationCallbacks* pAllocator,
2322 VkFramebuffer* pFramebuffer)
2323 {
2324 ANV_FROM_HANDLE(anv_device, device, _device);
2325 struct anv_framebuffer *framebuffer;
2326
2327 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2328
2329 size_t size = sizeof(*framebuffer) +
2330 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2331 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2332 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2333 if (framebuffer == NULL)
2334 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2335
2336 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2337 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2338 VkImageView _iview = pCreateInfo->pAttachments[i];
2339 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2340 }
2341
2342 framebuffer->width = pCreateInfo->width;
2343 framebuffer->height = pCreateInfo->height;
2344 framebuffer->layers = pCreateInfo->layers;
2345
2346 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2347
2348 return VK_SUCCESS;
2349 }
2350
2351 void anv_DestroyFramebuffer(
2352 VkDevice _device,
2353 VkFramebuffer _fb,
2354 const VkAllocationCallbacks* pAllocator)
2355 {
2356 ANV_FROM_HANDLE(anv_device, device, _device);
2357 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2358
2359 if (!fb)
2360 return;
2361
2362 vk_free2(&device->alloc, pAllocator, fb);
2363 }
2364
2365 /* vk_icd.h does not declare this function, so we declare it here to
2366 * suppress Wmissing-prototypes.
2367 */
2368 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2369 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2370
2371 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2372 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2373 {
2374 /* For the full details on loader interface versioning, see
2375 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2376 * What follows is a condensed summary, to help you navigate the large and
2377 * confusing official doc.
2378 *
2379 * - Loader interface v0 is incompatible with later versions. We don't
2380 * support it.
2381 *
2382 * - In loader interface v1:
2383 * - The first ICD entrypoint called by the loader is
2384 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2385 * entrypoint.
2386 * - The ICD must statically expose no other Vulkan symbol unless it is
2387 * linked with -Bsymbolic.
2388 * - Each dispatchable Vulkan handle created by the ICD must be
2389 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2390 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2391 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2392 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2393 * such loader-managed surfaces.
2394 *
2395 * - Loader interface v2 differs from v1 in:
2396 * - The first ICD entrypoint called by the loader is
2397 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2398 * statically expose this entrypoint.
2399 *
2400 * - Loader interface v3 differs from v2 in:
2401 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2402 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2403 * because the loader no longer does so.
2404 */
2405 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2406 return VK_SUCCESS;
2407 }