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