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