anv: Limit VkDeviceMemory objects to 2GB
[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 /* The kernel relocation API has a limitation of a 32-bit delta value
1543 * applied to the address before it is written which, in spite of it being
1544 * unsigned, is treated as signed . Because of the way that this maps to
1545 * the Vulkan API, we cannot handle an offset into a buffer that does not
1546 * fit into a signed 32 bits. The only mechanism we have for dealing with
1547 * this at the moment is to limit all VkDeviceMemory objects to a maximum
1548 * of 2GB each. The Vulkan spec allows us to do this:
1549 *
1550 * "Some platforms may have a limit on the maximum size of a single
1551 * allocation. For example, certain systems may fail to create
1552 * allocations with a size greater than or equal to 4GB. Such a limit is
1553 * implementation-dependent, and if such a failure occurs then the error
1554 * VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
1555 *
1556 * We don't use vk_error here because it's not an error so much as an
1557 * indication to the application that the allocation is too large.
1558 */
1559 if (pAllocateInfo->allocationSize > (1ull << 31))
1560 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1561
1562 /* FINISHME: Fail if allocation request exceeds heap size. */
1563
1564 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1565 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1566 if (mem == NULL)
1567 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1568
1569 /* The kernel is going to give us whole pages anyway */
1570 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
1571
1572 result = anv_bo_init_new(&mem->bo, device, alloc_size);
1573 if (result != VK_SUCCESS)
1574 goto fail;
1575
1576 mem->type_index = pAllocateInfo->memoryTypeIndex;
1577
1578 mem->map = NULL;
1579 mem->map_size = 0;
1580
1581 *pMem = anv_device_memory_to_handle(mem);
1582
1583 return VK_SUCCESS;
1584
1585 fail:
1586 vk_free2(&device->alloc, pAllocator, mem);
1587
1588 return result;
1589 }
1590
1591 void anv_FreeMemory(
1592 VkDevice _device,
1593 VkDeviceMemory _mem,
1594 const VkAllocationCallbacks* pAllocator)
1595 {
1596 ANV_FROM_HANDLE(anv_device, device, _device);
1597 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
1598
1599 if (mem == NULL)
1600 return;
1601
1602 if (mem->map)
1603 anv_UnmapMemory(_device, _mem);
1604
1605 if (mem->bo.map)
1606 anv_gem_munmap(mem->bo.map, mem->bo.size);
1607
1608 if (mem->bo.gem_handle != 0)
1609 anv_gem_close(device, mem->bo.gem_handle);
1610
1611 vk_free2(&device->alloc, pAllocator, mem);
1612 }
1613
1614 VkResult anv_MapMemory(
1615 VkDevice _device,
1616 VkDeviceMemory _memory,
1617 VkDeviceSize offset,
1618 VkDeviceSize size,
1619 VkMemoryMapFlags flags,
1620 void** ppData)
1621 {
1622 ANV_FROM_HANDLE(anv_device, device, _device);
1623 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1624
1625 if (mem == NULL) {
1626 *ppData = NULL;
1627 return VK_SUCCESS;
1628 }
1629
1630 if (size == VK_WHOLE_SIZE)
1631 size = mem->bo.size - offset;
1632
1633 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
1634 *
1635 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
1636 * assert(size != 0);
1637 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
1638 * equal to the size of the memory minus offset
1639 */
1640 assert(size > 0);
1641 assert(offset + size <= mem->bo.size);
1642
1643 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
1644 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
1645 * at a time is valid. We could just mmap up front and return an offset
1646 * pointer here, but that may exhaust virtual memory on 32 bit
1647 * userspace. */
1648
1649 uint32_t gem_flags = 0;
1650 if (!device->info.has_llc && mem->type_index == 0)
1651 gem_flags |= I915_MMAP_WC;
1652
1653 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
1654 uint64_t map_offset = offset & ~4095ull;
1655 assert(offset >= map_offset);
1656 uint64_t map_size = (offset + size) - map_offset;
1657
1658 /* Let's map whole pages */
1659 map_size = align_u64(map_size, 4096);
1660
1661 void *map = anv_gem_mmap(device, mem->bo.gem_handle,
1662 map_offset, map_size, gem_flags);
1663 if (map == MAP_FAILED)
1664 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1665
1666 mem->map = map;
1667 mem->map_size = map_size;
1668
1669 *ppData = mem->map + (offset - map_offset);
1670
1671 return VK_SUCCESS;
1672 }
1673
1674 void anv_UnmapMemory(
1675 VkDevice _device,
1676 VkDeviceMemory _memory)
1677 {
1678 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1679
1680 if (mem == NULL)
1681 return;
1682
1683 anv_gem_munmap(mem->map, mem->map_size);
1684
1685 mem->map = NULL;
1686 mem->map_size = 0;
1687 }
1688
1689 static void
1690 clflush_mapped_ranges(struct anv_device *device,
1691 uint32_t count,
1692 const VkMappedMemoryRange *ranges)
1693 {
1694 for (uint32_t i = 0; i < count; i++) {
1695 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
1696 if (ranges[i].offset >= mem->map_size)
1697 continue;
1698
1699 anv_clflush_range(mem->map + ranges[i].offset,
1700 MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
1701 }
1702 }
1703
1704 VkResult anv_FlushMappedMemoryRanges(
1705 VkDevice _device,
1706 uint32_t memoryRangeCount,
1707 const VkMappedMemoryRange* pMemoryRanges)
1708 {
1709 ANV_FROM_HANDLE(anv_device, device, _device);
1710
1711 if (device->info.has_llc)
1712 return VK_SUCCESS;
1713
1714 /* Make sure the writes we're flushing have landed. */
1715 __builtin_ia32_mfence();
1716
1717 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1718
1719 return VK_SUCCESS;
1720 }
1721
1722 VkResult anv_InvalidateMappedMemoryRanges(
1723 VkDevice _device,
1724 uint32_t memoryRangeCount,
1725 const VkMappedMemoryRange* pMemoryRanges)
1726 {
1727 ANV_FROM_HANDLE(anv_device, device, _device);
1728
1729 if (device->info.has_llc)
1730 return VK_SUCCESS;
1731
1732 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1733
1734 /* Make sure no reads get moved up above the invalidate. */
1735 __builtin_ia32_mfence();
1736
1737 return VK_SUCCESS;
1738 }
1739
1740 void anv_GetBufferMemoryRequirements(
1741 VkDevice _device,
1742 VkBuffer _buffer,
1743 VkMemoryRequirements* pMemoryRequirements)
1744 {
1745 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1746 ANV_FROM_HANDLE(anv_device, device, _device);
1747
1748 /* The Vulkan spec (git aaed022) says:
1749 *
1750 * memoryTypeBits is a bitfield and contains one bit set for every
1751 * supported memory type for the resource. The bit `1<<i` is set if and
1752 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1753 * structure for the physical device is supported.
1754 *
1755 * We support exactly one memory type on LLC, two on non-LLC.
1756 */
1757 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1758
1759 pMemoryRequirements->size = buffer->size;
1760 pMemoryRequirements->alignment = 16;
1761 }
1762
1763 void anv_GetImageMemoryRequirements(
1764 VkDevice _device,
1765 VkImage _image,
1766 VkMemoryRequirements* pMemoryRequirements)
1767 {
1768 ANV_FROM_HANDLE(anv_image, image, _image);
1769 ANV_FROM_HANDLE(anv_device, device, _device);
1770
1771 /* The Vulkan spec (git aaed022) says:
1772 *
1773 * memoryTypeBits is a bitfield and contains one bit set for every
1774 * supported memory type for the resource. The bit `1<<i` is set if and
1775 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1776 * structure for the physical device is supported.
1777 *
1778 * We support exactly one memory type on LLC, two on non-LLC.
1779 */
1780 pMemoryRequirements->memoryTypeBits = device->info.has_llc ? 1 : 3;
1781
1782 pMemoryRequirements->size = image->size;
1783 pMemoryRequirements->alignment = image->alignment;
1784 }
1785
1786 void anv_GetImageSparseMemoryRequirements(
1787 VkDevice device,
1788 VkImage image,
1789 uint32_t* pSparseMemoryRequirementCount,
1790 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
1791 {
1792 *pSparseMemoryRequirementCount = 0;
1793 }
1794
1795 void anv_GetDeviceMemoryCommitment(
1796 VkDevice device,
1797 VkDeviceMemory memory,
1798 VkDeviceSize* pCommittedMemoryInBytes)
1799 {
1800 *pCommittedMemoryInBytes = 0;
1801 }
1802
1803 VkResult anv_BindBufferMemory(
1804 VkDevice device,
1805 VkBuffer _buffer,
1806 VkDeviceMemory _memory,
1807 VkDeviceSize memoryOffset)
1808 {
1809 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1810 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1811
1812 if (mem) {
1813 buffer->bo = &mem->bo;
1814 buffer->offset = memoryOffset;
1815 } else {
1816 buffer->bo = NULL;
1817 buffer->offset = 0;
1818 }
1819
1820 return VK_SUCCESS;
1821 }
1822
1823 VkResult anv_QueueBindSparse(
1824 VkQueue _queue,
1825 uint32_t bindInfoCount,
1826 const VkBindSparseInfo* pBindInfo,
1827 VkFence fence)
1828 {
1829 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1830 if (unlikely(queue->device->lost))
1831 return VK_ERROR_DEVICE_LOST;
1832
1833 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
1834 }
1835
1836 VkResult anv_CreateFence(
1837 VkDevice _device,
1838 const VkFenceCreateInfo* pCreateInfo,
1839 const VkAllocationCallbacks* pAllocator,
1840 VkFence* pFence)
1841 {
1842 ANV_FROM_HANDLE(anv_device, device, _device);
1843 struct anv_bo fence_bo;
1844 struct anv_fence *fence;
1845 struct anv_batch batch;
1846 VkResult result;
1847
1848 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FENCE_CREATE_INFO);
1849
1850 result = anv_bo_pool_alloc(&device->batch_bo_pool, &fence_bo, 4096);
1851 if (result != VK_SUCCESS)
1852 return result;
1853
1854 /* Fences are small. Just store the CPU data structure in the BO. */
1855 fence = fence_bo.map;
1856 fence->bo = fence_bo;
1857
1858 /* Place the batch after the CPU data but on its own cache line. */
1859 const uint32_t batch_offset = align_u32(sizeof(*fence), CACHELINE_SIZE);
1860 batch.next = batch.start = fence->bo.map + batch_offset;
1861 batch.end = fence->bo.map + fence->bo.size;
1862 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1863 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1864
1865 if (!device->info.has_llc) {
1866 assert(((uintptr_t) batch.start & CACHELINE_MASK) == 0);
1867 assert(batch.next - batch.start <= CACHELINE_SIZE);
1868 __builtin_ia32_mfence();
1869 __builtin_ia32_clflush(batch.start);
1870 }
1871
1872 fence->exec2_objects[0].handle = fence->bo.gem_handle;
1873 fence->exec2_objects[0].relocation_count = 0;
1874 fence->exec2_objects[0].relocs_ptr = 0;
1875 fence->exec2_objects[0].alignment = 0;
1876 fence->exec2_objects[0].offset = fence->bo.offset;
1877 fence->exec2_objects[0].flags = 0;
1878 fence->exec2_objects[0].rsvd1 = 0;
1879 fence->exec2_objects[0].rsvd2 = 0;
1880
1881 fence->execbuf.buffers_ptr = (uintptr_t) fence->exec2_objects;
1882 fence->execbuf.buffer_count = 1;
1883 fence->execbuf.batch_start_offset = batch.start - fence->bo.map;
1884 fence->execbuf.batch_len = batch.next - batch.start;
1885 fence->execbuf.cliprects_ptr = 0;
1886 fence->execbuf.num_cliprects = 0;
1887 fence->execbuf.DR1 = 0;
1888 fence->execbuf.DR4 = 0;
1889
1890 fence->execbuf.flags =
1891 I915_EXEC_HANDLE_LUT | I915_EXEC_NO_RELOC | I915_EXEC_RENDER;
1892 fence->execbuf.rsvd1 = device->context_id;
1893 fence->execbuf.rsvd2 = 0;
1894
1895 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
1896 fence->state = ANV_FENCE_STATE_SIGNALED;
1897 } else {
1898 fence->state = ANV_FENCE_STATE_RESET;
1899 }
1900
1901 *pFence = anv_fence_to_handle(fence);
1902
1903 return VK_SUCCESS;
1904 }
1905
1906 void anv_DestroyFence(
1907 VkDevice _device,
1908 VkFence _fence,
1909 const VkAllocationCallbacks* pAllocator)
1910 {
1911 ANV_FROM_HANDLE(anv_device, device, _device);
1912 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1913
1914 if (!fence)
1915 return;
1916
1917 assert(fence->bo.map == fence);
1918 anv_bo_pool_free(&device->batch_bo_pool, &fence->bo);
1919 }
1920
1921 VkResult anv_ResetFences(
1922 VkDevice _device,
1923 uint32_t fenceCount,
1924 const VkFence* pFences)
1925 {
1926 for (uint32_t i = 0; i < fenceCount; i++) {
1927 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
1928 fence->state = ANV_FENCE_STATE_RESET;
1929 }
1930
1931 return VK_SUCCESS;
1932 }
1933
1934 VkResult anv_GetFenceStatus(
1935 VkDevice _device,
1936 VkFence _fence)
1937 {
1938 ANV_FROM_HANDLE(anv_device, device, _device);
1939 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1940
1941 if (unlikely(device->lost))
1942 return VK_ERROR_DEVICE_LOST;
1943
1944 switch (fence->state) {
1945 case ANV_FENCE_STATE_RESET:
1946 /* If it hasn't even been sent off to the GPU yet, it's not ready */
1947 return VK_NOT_READY;
1948
1949 case ANV_FENCE_STATE_SIGNALED:
1950 /* It's been signaled, return success */
1951 return VK_SUCCESS;
1952
1953 case ANV_FENCE_STATE_SUBMITTED: {
1954 VkResult result = anv_device_bo_busy(device, &fence->bo);
1955 if (result == VK_SUCCESS) {
1956 fence->state = ANV_FENCE_STATE_SIGNALED;
1957 return VK_SUCCESS;
1958 } else {
1959 return result;
1960 }
1961 }
1962 default:
1963 unreachable("Invalid fence status");
1964 }
1965 }
1966
1967 #define NSEC_PER_SEC 1000000000
1968 #define INT_TYPE_MAX(type) ((1ull << (sizeof(type) * 8 - 1)) - 1)
1969
1970 VkResult anv_WaitForFences(
1971 VkDevice _device,
1972 uint32_t fenceCount,
1973 const VkFence* pFences,
1974 VkBool32 waitAll,
1975 uint64_t _timeout)
1976 {
1977 ANV_FROM_HANDLE(anv_device, device, _device);
1978 int ret;
1979
1980 if (unlikely(device->lost))
1981 return VK_ERROR_DEVICE_LOST;
1982
1983 /* DRM_IOCTL_I915_GEM_WAIT uses a signed 64 bit timeout and is supposed
1984 * to block indefinitely timeouts <= 0. Unfortunately, this was broken
1985 * for a couple of kernel releases. Since there's no way to know
1986 * whether or not the kernel we're using is one of the broken ones, the
1987 * best we can do is to clamp the timeout to INT64_MAX. This limits the
1988 * maximum timeout from 584 years to 292 years - likely not a big deal.
1989 */
1990 int64_t timeout = MIN2(_timeout, INT64_MAX);
1991
1992 VkResult result = VK_SUCCESS;
1993 uint32_t pending_fences = fenceCount;
1994 while (pending_fences) {
1995 pending_fences = 0;
1996 bool signaled_fences = false;
1997 for (uint32_t i = 0; i < fenceCount; i++) {
1998 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
1999 switch (fence->state) {
2000 case ANV_FENCE_STATE_RESET:
2001 /* This fence hasn't been submitted yet, we'll catch it the next
2002 * time around. Yes, this may mean we dead-loop but, short of
2003 * lots of locking and a condition variable, there's not much that
2004 * we can do about that.
2005 */
2006 pending_fences++;
2007 continue;
2008
2009 case ANV_FENCE_STATE_SIGNALED:
2010 /* This fence is not pending. If waitAll isn't set, we can return
2011 * early. Otherwise, we have to keep going.
2012 */
2013 if (!waitAll) {
2014 result = VK_SUCCESS;
2015 goto done;
2016 }
2017 continue;
2018
2019 case ANV_FENCE_STATE_SUBMITTED:
2020 /* These are the fences we really care about. Go ahead and wait
2021 * on it until we hit a timeout.
2022 */
2023 result = anv_device_wait(device, &fence->bo, timeout);
2024 switch (result) {
2025 case VK_SUCCESS:
2026 fence->state = ANV_FENCE_STATE_SIGNALED;
2027 signaled_fences = true;
2028 if (!waitAll)
2029 goto done;
2030 break;
2031
2032 case VK_TIMEOUT:
2033 goto done;
2034
2035 default:
2036 return result;
2037 }
2038 }
2039 }
2040
2041 if (pending_fences && !signaled_fences) {
2042 /* If we've hit this then someone decided to vkWaitForFences before
2043 * they've actually submitted any of them to a queue. This is a
2044 * fairly pessimal case, so it's ok to lock here and use a standard
2045 * pthreads condition variable.
2046 */
2047 pthread_mutex_lock(&device->mutex);
2048
2049 /* It's possible that some of the fences have changed state since the
2050 * last time we checked. Now that we have the lock, check for
2051 * pending fences again and don't wait if it's changed.
2052 */
2053 uint32_t now_pending_fences = 0;
2054 for (uint32_t i = 0; i < fenceCount; i++) {
2055 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
2056 if (fence->state == ANV_FENCE_STATE_RESET)
2057 now_pending_fences++;
2058 }
2059 assert(now_pending_fences <= pending_fences);
2060
2061 if (now_pending_fences == pending_fences) {
2062 struct timespec before;
2063 clock_gettime(CLOCK_MONOTONIC, &before);
2064
2065 uint32_t abs_nsec = before.tv_nsec + timeout % NSEC_PER_SEC;
2066 uint64_t abs_sec = before.tv_sec + (abs_nsec / NSEC_PER_SEC) +
2067 (timeout / NSEC_PER_SEC);
2068 abs_nsec %= NSEC_PER_SEC;
2069
2070 /* Avoid roll-over in tv_sec on 32-bit systems if the user
2071 * provided timeout is UINT64_MAX
2072 */
2073 struct timespec abstime;
2074 abstime.tv_nsec = abs_nsec;
2075 abstime.tv_sec = MIN2(abs_sec, INT_TYPE_MAX(abstime.tv_sec));
2076
2077 ret = pthread_cond_timedwait(&device->queue_submit,
2078 &device->mutex, &abstime);
2079 assert(ret != EINVAL);
2080
2081 struct timespec after;
2082 clock_gettime(CLOCK_MONOTONIC, &after);
2083 uint64_t time_elapsed =
2084 ((uint64_t)after.tv_sec * NSEC_PER_SEC + after.tv_nsec) -
2085 ((uint64_t)before.tv_sec * NSEC_PER_SEC + before.tv_nsec);
2086
2087 if (time_elapsed >= timeout) {
2088 pthread_mutex_unlock(&device->mutex);
2089 result = VK_TIMEOUT;
2090 goto done;
2091 }
2092
2093 timeout -= time_elapsed;
2094 }
2095
2096 pthread_mutex_unlock(&device->mutex);
2097 }
2098 }
2099
2100 done:
2101 if (unlikely(device->lost))
2102 return VK_ERROR_DEVICE_LOST;
2103
2104 return result;
2105 }
2106
2107 // Queue semaphore functions
2108
2109 VkResult anv_CreateSemaphore(
2110 VkDevice device,
2111 const VkSemaphoreCreateInfo* pCreateInfo,
2112 const VkAllocationCallbacks* pAllocator,
2113 VkSemaphore* pSemaphore)
2114 {
2115 /* The DRM execbuffer ioctl always execute in-oder, even between different
2116 * rings. As such, there's nothing to do for the user space semaphore.
2117 */
2118
2119 *pSemaphore = (VkSemaphore)1;
2120
2121 return VK_SUCCESS;
2122 }
2123
2124 void anv_DestroySemaphore(
2125 VkDevice device,
2126 VkSemaphore semaphore,
2127 const VkAllocationCallbacks* pAllocator)
2128 {
2129 }
2130
2131 // Event functions
2132
2133 VkResult anv_CreateEvent(
2134 VkDevice _device,
2135 const VkEventCreateInfo* pCreateInfo,
2136 const VkAllocationCallbacks* pAllocator,
2137 VkEvent* pEvent)
2138 {
2139 ANV_FROM_HANDLE(anv_device, device, _device);
2140 struct anv_state state;
2141 struct anv_event *event;
2142
2143 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
2144
2145 state = anv_state_pool_alloc(&device->dynamic_state_pool,
2146 sizeof(*event), 8);
2147 event = state.map;
2148 event->state = state;
2149 event->semaphore = VK_EVENT_RESET;
2150
2151 if (!device->info.has_llc) {
2152 /* Make sure the writes we're flushing have landed. */
2153 __builtin_ia32_mfence();
2154 __builtin_ia32_clflush(event);
2155 }
2156
2157 *pEvent = anv_event_to_handle(event);
2158
2159 return VK_SUCCESS;
2160 }
2161
2162 void anv_DestroyEvent(
2163 VkDevice _device,
2164 VkEvent _event,
2165 const VkAllocationCallbacks* pAllocator)
2166 {
2167 ANV_FROM_HANDLE(anv_device, device, _device);
2168 ANV_FROM_HANDLE(anv_event, event, _event);
2169
2170 if (!event)
2171 return;
2172
2173 anv_state_pool_free(&device->dynamic_state_pool, event->state);
2174 }
2175
2176 VkResult anv_GetEventStatus(
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 if (unlikely(device->lost))
2184 return VK_ERROR_DEVICE_LOST;
2185
2186 if (!device->info.has_llc) {
2187 /* Invalidate read cache before reading event written by GPU. */
2188 __builtin_ia32_clflush(event);
2189 __builtin_ia32_mfence();
2190
2191 }
2192
2193 return event->semaphore;
2194 }
2195
2196 VkResult anv_SetEvent(
2197 VkDevice _device,
2198 VkEvent _event)
2199 {
2200 ANV_FROM_HANDLE(anv_device, device, _device);
2201 ANV_FROM_HANDLE(anv_event, event, _event);
2202
2203 event->semaphore = VK_EVENT_SET;
2204
2205 if (!device->info.has_llc) {
2206 /* Make sure the writes we're flushing have landed. */
2207 __builtin_ia32_mfence();
2208 __builtin_ia32_clflush(event);
2209 }
2210
2211 return VK_SUCCESS;
2212 }
2213
2214 VkResult anv_ResetEvent(
2215 VkDevice _device,
2216 VkEvent _event)
2217 {
2218 ANV_FROM_HANDLE(anv_device, device, _device);
2219 ANV_FROM_HANDLE(anv_event, event, _event);
2220
2221 event->semaphore = VK_EVENT_RESET;
2222
2223 if (!device->info.has_llc) {
2224 /* Make sure the writes we're flushing have landed. */
2225 __builtin_ia32_mfence();
2226 __builtin_ia32_clflush(event);
2227 }
2228
2229 return VK_SUCCESS;
2230 }
2231
2232 // Buffer functions
2233
2234 VkResult anv_CreateBuffer(
2235 VkDevice _device,
2236 const VkBufferCreateInfo* pCreateInfo,
2237 const VkAllocationCallbacks* pAllocator,
2238 VkBuffer* pBuffer)
2239 {
2240 ANV_FROM_HANDLE(anv_device, device, _device);
2241 struct anv_buffer *buffer;
2242
2243 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2244
2245 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2246 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2247 if (buffer == NULL)
2248 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2249
2250 buffer->size = pCreateInfo->size;
2251 buffer->usage = pCreateInfo->usage;
2252 buffer->bo = NULL;
2253 buffer->offset = 0;
2254
2255 *pBuffer = anv_buffer_to_handle(buffer);
2256
2257 return VK_SUCCESS;
2258 }
2259
2260 void anv_DestroyBuffer(
2261 VkDevice _device,
2262 VkBuffer _buffer,
2263 const VkAllocationCallbacks* pAllocator)
2264 {
2265 ANV_FROM_HANDLE(anv_device, device, _device);
2266 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
2267
2268 if (!buffer)
2269 return;
2270
2271 vk_free2(&device->alloc, pAllocator, buffer);
2272 }
2273
2274 void
2275 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
2276 enum isl_format format,
2277 uint32_t offset, uint32_t range, uint32_t stride)
2278 {
2279 isl_buffer_fill_state(&device->isl_dev, state.map,
2280 .address = offset,
2281 .mocs = device->default_mocs,
2282 .size = range,
2283 .format = format,
2284 .stride = stride);
2285
2286 anv_state_flush(device, state);
2287 }
2288
2289 void anv_DestroySampler(
2290 VkDevice _device,
2291 VkSampler _sampler,
2292 const VkAllocationCallbacks* pAllocator)
2293 {
2294 ANV_FROM_HANDLE(anv_device, device, _device);
2295 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
2296
2297 if (!sampler)
2298 return;
2299
2300 vk_free2(&device->alloc, pAllocator, sampler);
2301 }
2302
2303 VkResult anv_CreateFramebuffer(
2304 VkDevice _device,
2305 const VkFramebufferCreateInfo* pCreateInfo,
2306 const VkAllocationCallbacks* pAllocator,
2307 VkFramebuffer* pFramebuffer)
2308 {
2309 ANV_FROM_HANDLE(anv_device, device, _device);
2310 struct anv_framebuffer *framebuffer;
2311
2312 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
2313
2314 size_t size = sizeof(*framebuffer) +
2315 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
2316 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
2317 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2318 if (framebuffer == NULL)
2319 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2320
2321 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2322 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2323 VkImageView _iview = pCreateInfo->pAttachments[i];
2324 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2325 }
2326
2327 framebuffer->width = pCreateInfo->width;
2328 framebuffer->height = pCreateInfo->height;
2329 framebuffer->layers = pCreateInfo->layers;
2330
2331 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2332
2333 return VK_SUCCESS;
2334 }
2335
2336 void anv_DestroyFramebuffer(
2337 VkDevice _device,
2338 VkFramebuffer _fb,
2339 const VkAllocationCallbacks* pAllocator)
2340 {
2341 ANV_FROM_HANDLE(anv_device, device, _device);
2342 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2343
2344 if (!fb)
2345 return;
2346
2347 vk_free2(&device->alloc, pAllocator, fb);
2348 }
2349
2350 /* vk_icd.h does not declare this function, so we declare it here to
2351 * suppress Wmissing-prototypes.
2352 */
2353 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2354 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
2355
2356 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
2357 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
2358 {
2359 /* For the full details on loader interface versioning, see
2360 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
2361 * What follows is a condensed summary, to help you navigate the large and
2362 * confusing official doc.
2363 *
2364 * - Loader interface v0 is incompatible with later versions. We don't
2365 * support it.
2366 *
2367 * - In loader interface v1:
2368 * - The first ICD entrypoint called by the loader is
2369 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
2370 * entrypoint.
2371 * - The ICD must statically expose no other Vulkan symbol unless it is
2372 * linked with -Bsymbolic.
2373 * - Each dispatchable Vulkan handle created by the ICD must be
2374 * a pointer to a struct whose first member is VK_LOADER_DATA. The
2375 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
2376 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
2377 * vkDestroySurfaceKHR(). The ICD must be capable of working with
2378 * such loader-managed surfaces.
2379 *
2380 * - Loader interface v2 differs from v1 in:
2381 * - The first ICD entrypoint called by the loader is
2382 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
2383 * statically expose this entrypoint.
2384 *
2385 * - Loader interface v3 differs from v2 in:
2386 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
2387 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
2388 * because the loader no longer does so.
2389 */
2390 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
2391 return VK_SUCCESS;
2392 }