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