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