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