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