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