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