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