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