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