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