anv: return count of queue families written
[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 assert(*pCount >= 1);
650
651 *pQueueFamilyProperties = (VkQueueFamilyProperties) {
652 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
653 VK_QUEUE_COMPUTE_BIT |
654 VK_QUEUE_TRANSFER_BIT,
655 .queueCount = 1,
656 .timestampValidBits = 36, /* XXX: Real value here */
657 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
658 };
659
660 *pCount = 1;
661 }
662
663 void anv_GetPhysicalDeviceMemoryProperties(
664 VkPhysicalDevice physicalDevice,
665 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
666 {
667 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
668 VkDeviceSize heap_size;
669
670 /* Reserve some wiggle room for the driver by exposing only 75% of the
671 * aperture to the heap.
672 */
673 heap_size = 3 * physical_device->aperture_size / 4;
674
675 if (physical_device->info.has_llc) {
676 /* Big core GPUs share LLC with the CPU and thus one memory type can be
677 * both cached and coherent at the same time.
678 */
679 pMemoryProperties->memoryTypeCount = 1;
680 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
681 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
682 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
683 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
684 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
685 .heapIndex = 0,
686 };
687 } else {
688 /* The spec requires that we expose a host-visible, coherent memory
689 * type, but Atom GPUs don't share LLC. Thus we offer two memory types
690 * to give the application a choice between cached, but not coherent and
691 * coherent but uncached (WC though).
692 */
693 pMemoryProperties->memoryTypeCount = 2;
694 pMemoryProperties->memoryTypes[0] = (VkMemoryType) {
695 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
696 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
697 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
698 .heapIndex = 0,
699 };
700 pMemoryProperties->memoryTypes[1] = (VkMemoryType) {
701 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
702 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
703 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
704 .heapIndex = 0,
705 };
706 }
707
708 pMemoryProperties->memoryHeapCount = 1;
709 pMemoryProperties->memoryHeaps[0] = (VkMemoryHeap) {
710 .size = heap_size,
711 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
712 };
713 }
714
715 PFN_vkVoidFunction anv_GetInstanceProcAddr(
716 VkInstance instance,
717 const char* pName)
718 {
719 return anv_lookup_entrypoint(NULL, pName);
720 }
721
722 /* With version 1+ of the loader interface the ICD should expose
723 * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
724 */
725 PUBLIC
726 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
727 VkInstance instance,
728 const char* pName);
729
730 PUBLIC
731 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
732 VkInstance instance,
733 const char* pName)
734 {
735 return anv_GetInstanceProcAddr(instance, pName);
736 }
737
738 PFN_vkVoidFunction anv_GetDeviceProcAddr(
739 VkDevice _device,
740 const char* pName)
741 {
742 ANV_FROM_HANDLE(anv_device, device, _device);
743 return anv_lookup_entrypoint(&device->info, pName);
744 }
745
746 static void
747 anv_queue_init(struct anv_device *device, struct anv_queue *queue)
748 {
749 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
750 queue->device = device;
751 queue->pool = &device->surface_state_pool;
752 }
753
754 static void
755 anv_queue_finish(struct anv_queue *queue)
756 {
757 }
758
759 static struct anv_state
760 anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
761 {
762 struct anv_state state;
763
764 state = anv_state_pool_alloc(pool, size, align);
765 memcpy(state.map, p, size);
766
767 if (!pool->block_pool->device->info.has_llc)
768 anv_state_clflush(state);
769
770 return state;
771 }
772
773 struct gen8_border_color {
774 union {
775 float float32[4];
776 uint32_t uint32[4];
777 };
778 /* Pad out to 64 bytes */
779 uint32_t _pad[12];
780 };
781
782 static void
783 anv_device_init_border_colors(struct anv_device *device)
784 {
785 static const struct gen8_border_color border_colors[] = {
786 [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
787 [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
788 [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
789 [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
790 [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
791 [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
792 };
793
794 device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
795 sizeof(border_colors), 64,
796 border_colors);
797 }
798
799 VkResult
800 anv_device_submit_simple_batch(struct anv_device *device,
801 struct anv_batch *batch)
802 {
803 struct drm_i915_gem_execbuffer2 execbuf;
804 struct drm_i915_gem_exec_object2 exec2_objects[1];
805 struct anv_bo bo, *exec_bos[1];
806 VkResult result = VK_SUCCESS;
807 uint32_t size;
808 int64_t timeout;
809 int ret;
810
811 /* Kernel driver requires 8 byte aligned batch length */
812 size = align_u32(batch->next - batch->start, 8);
813 result = anv_bo_pool_alloc(&device->batch_bo_pool, &bo, size);
814 if (result != VK_SUCCESS)
815 return result;
816
817 memcpy(bo.map, batch->start, size);
818 if (!device->info.has_llc)
819 anv_clflush_range(bo.map, size);
820
821 exec_bos[0] = &bo;
822 exec2_objects[0].handle = bo.gem_handle;
823 exec2_objects[0].relocation_count = 0;
824 exec2_objects[0].relocs_ptr = 0;
825 exec2_objects[0].alignment = 0;
826 exec2_objects[0].offset = bo.offset;
827 exec2_objects[0].flags = 0;
828 exec2_objects[0].rsvd1 = 0;
829 exec2_objects[0].rsvd2 = 0;
830
831 execbuf.buffers_ptr = (uintptr_t) exec2_objects;
832 execbuf.buffer_count = 1;
833 execbuf.batch_start_offset = 0;
834 execbuf.batch_len = size;
835 execbuf.cliprects_ptr = 0;
836 execbuf.num_cliprects = 0;
837 execbuf.DR1 = 0;
838 execbuf.DR4 = 0;
839
840 execbuf.flags =
841 I915_EXEC_HANDLE_LUT | I915_EXEC_NO_RELOC | I915_EXEC_RENDER;
842 execbuf.rsvd1 = device->context_id;
843 execbuf.rsvd2 = 0;
844
845 result = anv_device_execbuf(device, &execbuf, exec_bos);
846 if (result != VK_SUCCESS)
847 goto fail;
848
849 timeout = INT64_MAX;
850 ret = anv_gem_wait(device, bo.gem_handle, &timeout);
851 if (ret != 0) {
852 /* We don't know the real error. */
853 result = vk_errorf(VK_ERROR_DEVICE_LOST, "execbuf2 failed: %m");
854 goto fail;
855 }
856
857 fail:
858 anv_bo_pool_free(&device->batch_bo_pool, &bo);
859
860 return result;
861 }
862
863 VkResult anv_CreateDevice(
864 VkPhysicalDevice physicalDevice,
865 const VkDeviceCreateInfo* pCreateInfo,
866 const VkAllocationCallbacks* pAllocator,
867 VkDevice* pDevice)
868 {
869 ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
870 VkResult result;
871 struct anv_device *device;
872
873 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
874
875 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
876 bool found = false;
877 for (uint32_t j = 0; j < ARRAY_SIZE(device_extensions); j++) {
878 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
879 device_extensions[j].extensionName) == 0) {
880 found = true;
881 break;
882 }
883 }
884 if (!found)
885 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
886 }
887
888 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
889 sizeof(*device), 8,
890 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
891 if (!device)
892 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
893
894 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
895 device->instance = physical_device->instance;
896 device->chipset_id = physical_device->chipset_id;
897
898 if (pAllocator)
899 device->alloc = *pAllocator;
900 else
901 device->alloc = physical_device->instance->alloc;
902
903 /* XXX(chadv): Can we dup() physicalDevice->fd here? */
904 device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
905 if (device->fd == -1) {
906 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
907 goto fail_device;
908 }
909
910 device->context_id = anv_gem_create_context(device);
911 if (device->context_id == -1) {
912 result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
913 goto fail_fd;
914 }
915
916 device->info = physical_device->info;
917 device->isl_dev = physical_device->isl_dev;
918
919 /* On Broadwell and later, we can use batch chaining to more efficiently
920 * implement growing command buffers. Prior to Haswell, the kernel
921 * command parser gets in the way and we have to fall back to growing
922 * the batch.
923 */
924 device->can_chain_batches = device->info.gen >= 8;
925
926 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
927 pCreateInfo->pEnabledFeatures->robustBufferAccess;
928
929 pthread_mutex_init(&device->mutex, NULL);
930
931 pthread_condattr_t condattr;
932 pthread_condattr_init(&condattr);
933 pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC);
934 pthread_cond_init(&device->queue_submit, NULL);
935 pthread_condattr_destroy(&condattr);
936
937 anv_bo_pool_init(&device->batch_bo_pool, device);
938
939 anv_block_pool_init(&device->dynamic_state_block_pool, device, 16384);
940
941 anv_state_pool_init(&device->dynamic_state_pool,
942 &device->dynamic_state_block_pool);
943
944 anv_block_pool_init(&device->instruction_block_pool, device, 128 * 1024);
945 anv_state_pool_init(&device->instruction_state_pool,
946 &device->instruction_block_pool);
947
948 anv_block_pool_init(&device->surface_state_block_pool, device, 4096);
949
950 anv_state_pool_init(&device->surface_state_pool,
951 &device->surface_state_block_pool);
952
953 anv_bo_init_new(&device->workaround_bo, device, 1024);
954
955 anv_scratch_pool_init(device, &device->scratch_pool);
956
957 anv_queue_init(device, &device->queue);
958
959 switch (device->info.gen) {
960 case 7:
961 if (!device->info.is_haswell)
962 result = gen7_init_device_state(device);
963 else
964 result = gen75_init_device_state(device);
965 break;
966 case 8:
967 result = gen8_init_device_state(device);
968 break;
969 case 9:
970 result = gen9_init_device_state(device);
971 break;
972 default:
973 /* Shouldn't get here as we don't create physical devices for any other
974 * gens. */
975 unreachable("unhandled gen");
976 }
977 if (result != VK_SUCCESS)
978 goto fail_fd;
979
980 anv_device_init_blorp(device);
981
982 anv_device_init_border_colors(device);
983
984 *pDevice = anv_device_to_handle(device);
985
986 return VK_SUCCESS;
987
988 fail_fd:
989 close(device->fd);
990 fail_device:
991 vk_free(&device->alloc, device);
992
993 return result;
994 }
995
996 void anv_DestroyDevice(
997 VkDevice _device,
998 const VkAllocationCallbacks* pAllocator)
999 {
1000 ANV_FROM_HANDLE(anv_device, device, _device);
1001
1002 anv_device_finish_blorp(device);
1003
1004 anv_queue_finish(&device->queue);
1005
1006 #ifdef HAVE_VALGRIND
1007 /* We only need to free these to prevent valgrind errors. The backing
1008 * BO will go away in a couple of lines so we don't actually leak.
1009 */
1010 anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
1011 #endif
1012
1013 anv_scratch_pool_finish(device, &device->scratch_pool);
1014
1015 anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
1016 anv_gem_close(device, device->workaround_bo.gem_handle);
1017
1018 anv_state_pool_finish(&device->surface_state_pool);
1019 anv_block_pool_finish(&device->surface_state_block_pool);
1020 anv_state_pool_finish(&device->instruction_state_pool);
1021 anv_block_pool_finish(&device->instruction_block_pool);
1022 anv_state_pool_finish(&device->dynamic_state_pool);
1023 anv_block_pool_finish(&device->dynamic_state_block_pool);
1024
1025 anv_bo_pool_finish(&device->batch_bo_pool);
1026
1027 pthread_cond_destroy(&device->queue_submit);
1028 pthread_mutex_destroy(&device->mutex);
1029
1030 anv_gem_destroy_context(device, device->context_id);
1031
1032 close(device->fd);
1033
1034 vk_free(&device->alloc, device);
1035 }
1036
1037 VkResult anv_EnumerateInstanceExtensionProperties(
1038 const char* pLayerName,
1039 uint32_t* pPropertyCount,
1040 VkExtensionProperties* pProperties)
1041 {
1042 if (pProperties == NULL) {
1043 *pPropertyCount = ARRAY_SIZE(global_extensions);
1044 return VK_SUCCESS;
1045 }
1046
1047 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(global_extensions));
1048 typed_memcpy(pProperties, global_extensions, *pPropertyCount);
1049
1050 if (*pPropertyCount < ARRAY_SIZE(global_extensions))
1051 return VK_INCOMPLETE;
1052
1053 return VK_SUCCESS;
1054 }
1055
1056 VkResult anv_EnumerateDeviceExtensionProperties(
1057 VkPhysicalDevice physicalDevice,
1058 const char* pLayerName,
1059 uint32_t* pPropertyCount,
1060 VkExtensionProperties* pProperties)
1061 {
1062 if (pProperties == NULL) {
1063 *pPropertyCount = ARRAY_SIZE(device_extensions);
1064 return VK_SUCCESS;
1065 }
1066
1067 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(device_extensions));
1068 typed_memcpy(pProperties, device_extensions, *pPropertyCount);
1069
1070 if (*pPropertyCount < ARRAY_SIZE(device_extensions))
1071 return VK_INCOMPLETE;
1072
1073 return VK_SUCCESS;
1074 }
1075
1076 VkResult anv_EnumerateInstanceLayerProperties(
1077 uint32_t* pPropertyCount,
1078 VkLayerProperties* pProperties)
1079 {
1080 if (pProperties == NULL) {
1081 *pPropertyCount = 0;
1082 return VK_SUCCESS;
1083 }
1084
1085 /* None supported at this time */
1086 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1087 }
1088
1089 VkResult anv_EnumerateDeviceLayerProperties(
1090 VkPhysicalDevice physicalDevice,
1091 uint32_t* pPropertyCount,
1092 VkLayerProperties* pProperties)
1093 {
1094 if (pProperties == NULL) {
1095 *pPropertyCount = 0;
1096 return VK_SUCCESS;
1097 }
1098
1099 /* None supported at this time */
1100 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1101 }
1102
1103 void anv_GetDeviceQueue(
1104 VkDevice _device,
1105 uint32_t queueNodeIndex,
1106 uint32_t queueIndex,
1107 VkQueue* pQueue)
1108 {
1109 ANV_FROM_HANDLE(anv_device, device, _device);
1110
1111 assert(queueIndex == 0);
1112
1113 *pQueue = anv_queue_to_handle(&device->queue);
1114 }
1115
1116 VkResult
1117 anv_device_execbuf(struct anv_device *device,
1118 struct drm_i915_gem_execbuffer2 *execbuf,
1119 struct anv_bo **execbuf_bos)
1120 {
1121 int ret = anv_gem_execbuffer(device, execbuf);
1122 if (ret != 0) {
1123 /* We don't know the real error. */
1124 return vk_errorf(VK_ERROR_DEVICE_LOST, "execbuf2 failed: %m");
1125 }
1126
1127 struct drm_i915_gem_exec_object2 *objects =
1128 (void *)(uintptr_t)execbuf->buffers_ptr;
1129 for (uint32_t k = 0; k < execbuf->buffer_count; k++)
1130 execbuf_bos[k]->offset = objects[k].offset;
1131
1132 return VK_SUCCESS;
1133 }
1134
1135 VkResult anv_QueueSubmit(
1136 VkQueue _queue,
1137 uint32_t submitCount,
1138 const VkSubmitInfo* pSubmits,
1139 VkFence _fence)
1140 {
1141 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1142 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1143 struct anv_device *device = queue->device;
1144 VkResult result = VK_SUCCESS;
1145
1146 /* We lock around QueueSubmit for three main reasons:
1147 *
1148 * 1) When a block pool is resized, we create a new gem handle with a
1149 * different size and, in the case of surface states, possibly a
1150 * different center offset but we re-use the same anv_bo struct when
1151 * we do so. If this happens in the middle of setting up an execbuf,
1152 * we could end up with our list of BOs out of sync with our list of
1153 * gem handles.
1154 *
1155 * 2) The algorithm we use for building the list of unique buffers isn't
1156 * thread-safe. While the client is supposed to syncronize around
1157 * QueueSubmit, this would be extremely difficult to debug if it ever
1158 * came up in the wild due to a broken app. It's better to play it
1159 * safe and just lock around QueueSubmit.
1160 *
1161 * 3) The anv_cmd_buffer_execbuf function may perform relocations in
1162 * userspace. Due to the fact that the surface state buffer is shared
1163 * between batches, we can't afford to have that happen from multiple
1164 * threads at the same time. Even though the user is supposed to
1165 * ensure this doesn't happen, we play it safe as in (2) above.
1166 *
1167 * Since the only other things that ever take the device lock such as block
1168 * pool resize only rarely happen, this will almost never be contended so
1169 * taking a lock isn't really an expensive operation in this case.
1170 */
1171 pthread_mutex_lock(&device->mutex);
1172
1173 for (uint32_t i = 0; i < submitCount; i++) {
1174 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
1175 ANV_FROM_HANDLE(anv_cmd_buffer, cmd_buffer,
1176 pSubmits[i].pCommandBuffers[j]);
1177 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1178
1179 result = anv_cmd_buffer_execbuf(device, cmd_buffer);
1180 if (result != VK_SUCCESS)
1181 goto out;
1182 }
1183 }
1184
1185 if (fence) {
1186 struct anv_bo *fence_bo = &fence->bo;
1187 result = anv_device_execbuf(device, &fence->execbuf, &fence_bo);
1188 if (result != VK_SUCCESS)
1189 goto out;
1190
1191 /* Update the fence and wake up any waiters */
1192 assert(fence->state == ANV_FENCE_STATE_RESET);
1193 fence->state = ANV_FENCE_STATE_SUBMITTED;
1194 pthread_cond_broadcast(&device->queue_submit);
1195 }
1196
1197 out:
1198 pthread_mutex_unlock(&device->mutex);
1199
1200 return result;
1201 }
1202
1203 VkResult anv_QueueWaitIdle(
1204 VkQueue _queue)
1205 {
1206 ANV_FROM_HANDLE(anv_queue, queue, _queue);
1207
1208 return anv_DeviceWaitIdle(anv_device_to_handle(queue->device));
1209 }
1210
1211 VkResult anv_DeviceWaitIdle(
1212 VkDevice _device)
1213 {
1214 ANV_FROM_HANDLE(anv_device, device, _device);
1215 struct anv_batch batch;
1216
1217 uint32_t cmds[8];
1218 batch.start = batch.next = cmds;
1219 batch.end = (void *) cmds + sizeof(cmds);
1220
1221 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1222 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1223
1224 return anv_device_submit_simple_batch(device, &batch);
1225 }
1226
1227 VkResult
1228 anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
1229 {
1230 uint32_t gem_handle = anv_gem_create(device, size);
1231 if (!gem_handle)
1232 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
1233
1234 anv_bo_init(bo, gem_handle, size);
1235
1236 return VK_SUCCESS;
1237 }
1238
1239 VkResult anv_AllocateMemory(
1240 VkDevice _device,
1241 const VkMemoryAllocateInfo* pAllocateInfo,
1242 const VkAllocationCallbacks* pAllocator,
1243 VkDeviceMemory* pMem)
1244 {
1245 ANV_FROM_HANDLE(anv_device, device, _device);
1246 struct anv_device_memory *mem;
1247 VkResult result;
1248
1249 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
1250
1251 /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
1252 assert(pAllocateInfo->allocationSize > 0);
1253
1254 /* We support exactly one memory heap. */
1255 assert(pAllocateInfo->memoryTypeIndex == 0 ||
1256 (!device->info.has_llc && pAllocateInfo->memoryTypeIndex < 2));
1257
1258 /* FINISHME: Fail if allocation request exceeds heap size. */
1259
1260 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
1261 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1262 if (mem == NULL)
1263 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1264
1265 /* The kernel is going to give us whole pages anyway */
1266 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
1267
1268 result = anv_bo_init_new(&mem->bo, device, alloc_size);
1269 if (result != VK_SUCCESS)
1270 goto fail;
1271
1272 mem->type_index = pAllocateInfo->memoryTypeIndex;
1273
1274 mem->map = NULL;
1275 mem->map_size = 0;
1276
1277 *pMem = anv_device_memory_to_handle(mem);
1278
1279 return VK_SUCCESS;
1280
1281 fail:
1282 vk_free2(&device->alloc, pAllocator, mem);
1283
1284 return result;
1285 }
1286
1287 void anv_FreeMemory(
1288 VkDevice _device,
1289 VkDeviceMemory _mem,
1290 const VkAllocationCallbacks* pAllocator)
1291 {
1292 ANV_FROM_HANDLE(anv_device, device, _device);
1293 ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
1294
1295 if (mem == NULL)
1296 return;
1297
1298 if (mem->map)
1299 anv_UnmapMemory(_device, _mem);
1300
1301 if (mem->bo.map)
1302 anv_gem_munmap(mem->bo.map, mem->bo.size);
1303
1304 if (mem->bo.gem_handle != 0)
1305 anv_gem_close(device, mem->bo.gem_handle);
1306
1307 vk_free2(&device->alloc, pAllocator, mem);
1308 }
1309
1310 VkResult anv_MapMemory(
1311 VkDevice _device,
1312 VkDeviceMemory _memory,
1313 VkDeviceSize offset,
1314 VkDeviceSize size,
1315 VkMemoryMapFlags flags,
1316 void** ppData)
1317 {
1318 ANV_FROM_HANDLE(anv_device, device, _device);
1319 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1320
1321 if (mem == NULL) {
1322 *ppData = NULL;
1323 return VK_SUCCESS;
1324 }
1325
1326 if (size == VK_WHOLE_SIZE)
1327 size = mem->bo.size - offset;
1328
1329 /* From the Vulkan spec version 1.0.32 docs for MapMemory:
1330 *
1331 * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
1332 * assert(size != 0);
1333 * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
1334 * equal to the size of the memory minus offset
1335 */
1336 assert(size > 0);
1337 assert(offset + size <= mem->bo.size);
1338
1339 /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
1340 * takes a VkDeviceMemory pointer, it seems like only one map of the memory
1341 * at a time is valid. We could just mmap up front and return an offset
1342 * pointer here, but that may exhaust virtual memory on 32 bit
1343 * userspace. */
1344
1345 uint32_t gem_flags = 0;
1346 if (!device->info.has_llc && mem->type_index == 0)
1347 gem_flags |= I915_MMAP_WC;
1348
1349 /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
1350 uint64_t map_offset = offset & ~4095ull;
1351 assert(offset >= map_offset);
1352 uint64_t map_size = (offset + size) - map_offset;
1353
1354 /* Let's map whole pages */
1355 map_size = align_u64(map_size, 4096);
1356
1357 void *map = anv_gem_mmap(device, mem->bo.gem_handle,
1358 map_offset, map_size, gem_flags);
1359 if (map == MAP_FAILED)
1360 return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
1361
1362 mem->map = map;
1363 mem->map_size = map_size;
1364
1365 *ppData = mem->map + (offset - map_offset);
1366
1367 return VK_SUCCESS;
1368 }
1369
1370 void anv_UnmapMemory(
1371 VkDevice _device,
1372 VkDeviceMemory _memory)
1373 {
1374 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1375
1376 if (mem == NULL)
1377 return;
1378
1379 anv_gem_munmap(mem->map, mem->map_size);
1380
1381 mem->map = NULL;
1382 mem->map_size = 0;
1383 }
1384
1385 static void
1386 clflush_mapped_ranges(struct anv_device *device,
1387 uint32_t count,
1388 const VkMappedMemoryRange *ranges)
1389 {
1390 for (uint32_t i = 0; i < count; i++) {
1391 ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
1392 void *p = mem->map + (ranges[i].offset & ~CACHELINE_MASK);
1393 void *end;
1394
1395 if (ranges[i].offset + ranges[i].size > mem->map_size)
1396 end = mem->map + mem->map_size;
1397 else
1398 end = mem->map + ranges[i].offset + ranges[i].size;
1399
1400 while (p < end) {
1401 __builtin_ia32_clflush(p);
1402 p += CACHELINE_SIZE;
1403 }
1404 }
1405 }
1406
1407 VkResult anv_FlushMappedMemoryRanges(
1408 VkDevice _device,
1409 uint32_t memoryRangeCount,
1410 const VkMappedMemoryRange* pMemoryRanges)
1411 {
1412 ANV_FROM_HANDLE(anv_device, device, _device);
1413
1414 if (device->info.has_llc)
1415 return VK_SUCCESS;
1416
1417 /* Make sure the writes we're flushing have landed. */
1418 __builtin_ia32_mfence();
1419
1420 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1421
1422 return VK_SUCCESS;
1423 }
1424
1425 VkResult anv_InvalidateMappedMemoryRanges(
1426 VkDevice _device,
1427 uint32_t memoryRangeCount,
1428 const VkMappedMemoryRange* pMemoryRanges)
1429 {
1430 ANV_FROM_HANDLE(anv_device, device, _device);
1431
1432 if (device->info.has_llc)
1433 return VK_SUCCESS;
1434
1435 clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
1436
1437 /* Make sure no reads get moved up above the invalidate. */
1438 __builtin_ia32_mfence();
1439
1440 return VK_SUCCESS;
1441 }
1442
1443 void anv_GetBufferMemoryRequirements(
1444 VkDevice device,
1445 VkBuffer _buffer,
1446 VkMemoryRequirements* pMemoryRequirements)
1447 {
1448 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1449
1450 /* The Vulkan spec (git aaed022) says:
1451 *
1452 * memoryTypeBits is a bitfield and contains one bit set for every
1453 * supported memory type for the resource. The bit `1<<i` is set if and
1454 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1455 * structure for the physical device is supported.
1456 *
1457 * We support exactly one memory type.
1458 */
1459 pMemoryRequirements->memoryTypeBits = 1;
1460
1461 pMemoryRequirements->size = buffer->size;
1462 pMemoryRequirements->alignment = 16;
1463 }
1464
1465 void anv_GetImageMemoryRequirements(
1466 VkDevice device,
1467 VkImage _image,
1468 VkMemoryRequirements* pMemoryRequirements)
1469 {
1470 ANV_FROM_HANDLE(anv_image, image, _image);
1471
1472 /* The Vulkan spec (git aaed022) says:
1473 *
1474 * memoryTypeBits is a bitfield and contains one bit set for every
1475 * supported memory type for the resource. The bit `1<<i` is set if and
1476 * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
1477 * structure for the physical device is supported.
1478 *
1479 * We support exactly one memory type.
1480 */
1481 pMemoryRequirements->memoryTypeBits = 1;
1482
1483 pMemoryRequirements->size = image->size;
1484 pMemoryRequirements->alignment = image->alignment;
1485 }
1486
1487 void anv_GetImageSparseMemoryRequirements(
1488 VkDevice device,
1489 VkImage image,
1490 uint32_t* pSparseMemoryRequirementCount,
1491 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
1492 {
1493 stub();
1494 }
1495
1496 void anv_GetDeviceMemoryCommitment(
1497 VkDevice device,
1498 VkDeviceMemory memory,
1499 VkDeviceSize* pCommittedMemoryInBytes)
1500 {
1501 *pCommittedMemoryInBytes = 0;
1502 }
1503
1504 VkResult anv_BindBufferMemory(
1505 VkDevice device,
1506 VkBuffer _buffer,
1507 VkDeviceMemory _memory,
1508 VkDeviceSize memoryOffset)
1509 {
1510 ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
1511 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1512
1513 if (mem) {
1514 buffer->bo = &mem->bo;
1515 buffer->offset = memoryOffset;
1516 } else {
1517 buffer->bo = NULL;
1518 buffer->offset = 0;
1519 }
1520
1521 return VK_SUCCESS;
1522 }
1523
1524 VkResult anv_QueueBindSparse(
1525 VkQueue queue,
1526 uint32_t bindInfoCount,
1527 const VkBindSparseInfo* pBindInfo,
1528 VkFence fence)
1529 {
1530 stub_return(VK_ERROR_INCOMPATIBLE_DRIVER);
1531 }
1532
1533 VkResult anv_CreateFence(
1534 VkDevice _device,
1535 const VkFenceCreateInfo* pCreateInfo,
1536 const VkAllocationCallbacks* pAllocator,
1537 VkFence* pFence)
1538 {
1539 ANV_FROM_HANDLE(anv_device, device, _device);
1540 struct anv_bo fence_bo;
1541 struct anv_fence *fence;
1542 struct anv_batch batch;
1543 VkResult result;
1544
1545 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FENCE_CREATE_INFO);
1546
1547 result = anv_bo_pool_alloc(&device->batch_bo_pool, &fence_bo, 4096);
1548 if (result != VK_SUCCESS)
1549 return result;
1550
1551 /* Fences are small. Just store the CPU data structure in the BO. */
1552 fence = fence_bo.map;
1553 fence->bo = fence_bo;
1554
1555 /* Place the batch after the CPU data but on its own cache line. */
1556 const uint32_t batch_offset = align_u32(sizeof(*fence), CACHELINE_SIZE);
1557 batch.next = batch.start = fence->bo.map + batch_offset;
1558 batch.end = fence->bo.map + fence->bo.size;
1559 anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
1560 anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
1561
1562 if (!device->info.has_llc) {
1563 assert(((uintptr_t) batch.start & CACHELINE_MASK) == 0);
1564 assert(batch.next - batch.start <= CACHELINE_SIZE);
1565 __builtin_ia32_mfence();
1566 __builtin_ia32_clflush(batch.start);
1567 }
1568
1569 fence->exec2_objects[0].handle = fence->bo.gem_handle;
1570 fence->exec2_objects[0].relocation_count = 0;
1571 fence->exec2_objects[0].relocs_ptr = 0;
1572 fence->exec2_objects[0].alignment = 0;
1573 fence->exec2_objects[0].offset = fence->bo.offset;
1574 fence->exec2_objects[0].flags = 0;
1575 fence->exec2_objects[0].rsvd1 = 0;
1576 fence->exec2_objects[0].rsvd2 = 0;
1577
1578 fence->execbuf.buffers_ptr = (uintptr_t) fence->exec2_objects;
1579 fence->execbuf.buffer_count = 1;
1580 fence->execbuf.batch_start_offset = batch.start - fence->bo.map;
1581 fence->execbuf.batch_len = batch.next - batch.start;
1582 fence->execbuf.cliprects_ptr = 0;
1583 fence->execbuf.num_cliprects = 0;
1584 fence->execbuf.DR1 = 0;
1585 fence->execbuf.DR4 = 0;
1586
1587 fence->execbuf.flags =
1588 I915_EXEC_HANDLE_LUT | I915_EXEC_NO_RELOC | I915_EXEC_RENDER;
1589 fence->execbuf.rsvd1 = device->context_id;
1590 fence->execbuf.rsvd2 = 0;
1591
1592 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
1593 fence->state = ANV_FENCE_STATE_SIGNALED;
1594 } else {
1595 fence->state = ANV_FENCE_STATE_RESET;
1596 }
1597
1598 *pFence = anv_fence_to_handle(fence);
1599
1600 return VK_SUCCESS;
1601 }
1602
1603 void anv_DestroyFence(
1604 VkDevice _device,
1605 VkFence _fence,
1606 const VkAllocationCallbacks* pAllocator)
1607 {
1608 ANV_FROM_HANDLE(anv_device, device, _device);
1609 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1610
1611 if (!fence)
1612 return;
1613
1614 assert(fence->bo.map == fence);
1615 anv_bo_pool_free(&device->batch_bo_pool, &fence->bo);
1616 }
1617
1618 VkResult anv_ResetFences(
1619 VkDevice _device,
1620 uint32_t fenceCount,
1621 const VkFence* pFences)
1622 {
1623 for (uint32_t i = 0; i < fenceCount; i++) {
1624 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
1625 fence->state = ANV_FENCE_STATE_RESET;
1626 }
1627
1628 return VK_SUCCESS;
1629 }
1630
1631 VkResult anv_GetFenceStatus(
1632 VkDevice _device,
1633 VkFence _fence)
1634 {
1635 ANV_FROM_HANDLE(anv_device, device, _device);
1636 ANV_FROM_HANDLE(anv_fence, fence, _fence);
1637 int64_t t = 0;
1638 int ret;
1639
1640 switch (fence->state) {
1641 case ANV_FENCE_STATE_RESET:
1642 /* If it hasn't even been sent off to the GPU yet, it's not ready */
1643 return VK_NOT_READY;
1644
1645 case ANV_FENCE_STATE_SIGNALED:
1646 /* It's been signaled, return success */
1647 return VK_SUCCESS;
1648
1649 case ANV_FENCE_STATE_SUBMITTED:
1650 /* It's been submitted to the GPU but we don't know if it's done yet. */
1651 ret = anv_gem_wait(device, fence->bo.gem_handle, &t);
1652 if (ret == 0) {
1653 fence->state = ANV_FENCE_STATE_SIGNALED;
1654 return VK_SUCCESS;
1655 } else {
1656 return VK_NOT_READY;
1657 }
1658 default:
1659 unreachable("Invalid fence status");
1660 }
1661 }
1662
1663 #define NSEC_PER_SEC 1000000000
1664 #define INT_TYPE_MAX(type) ((1ull << (sizeof(type) * 8 - 1)) - 1)
1665
1666 VkResult anv_WaitForFences(
1667 VkDevice _device,
1668 uint32_t fenceCount,
1669 const VkFence* pFences,
1670 VkBool32 waitAll,
1671 uint64_t _timeout)
1672 {
1673 ANV_FROM_HANDLE(anv_device, device, _device);
1674 int ret;
1675
1676 /* DRM_IOCTL_I915_GEM_WAIT uses a signed 64 bit timeout and is supposed
1677 * to block indefinitely timeouts <= 0. Unfortunately, this was broken
1678 * for a couple of kernel releases. Since there's no way to know
1679 * whether or not the kernel we're using is one of the broken ones, the
1680 * best we can do is to clamp the timeout to INT64_MAX. This limits the
1681 * maximum timeout from 584 years to 292 years - likely not a big deal.
1682 */
1683 int64_t timeout = MIN2(_timeout, INT64_MAX);
1684
1685 uint32_t pending_fences = fenceCount;
1686 while (pending_fences) {
1687 pending_fences = 0;
1688 bool signaled_fences = false;
1689 for (uint32_t i = 0; i < fenceCount; i++) {
1690 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
1691 switch (fence->state) {
1692 case ANV_FENCE_STATE_RESET:
1693 /* This fence hasn't been submitted yet, we'll catch it the next
1694 * time around. Yes, this may mean we dead-loop but, short of
1695 * lots of locking and a condition variable, there's not much that
1696 * we can do about that.
1697 */
1698 pending_fences++;
1699 continue;
1700
1701 case ANV_FENCE_STATE_SIGNALED:
1702 /* This fence is not pending. If waitAll isn't set, we can return
1703 * early. Otherwise, we have to keep going.
1704 */
1705 if (!waitAll)
1706 return VK_SUCCESS;
1707 continue;
1708
1709 case ANV_FENCE_STATE_SUBMITTED:
1710 /* These are the fences we really care about. Go ahead and wait
1711 * on it until we hit a timeout.
1712 */
1713 ret = anv_gem_wait(device, fence->bo.gem_handle, &timeout);
1714 if (ret == -1 && errno == ETIME) {
1715 return VK_TIMEOUT;
1716 } else if (ret == -1) {
1717 /* We don't know the real error. */
1718 return vk_errorf(VK_ERROR_DEVICE_LOST, "gem wait failed: %m");
1719 } else {
1720 fence->state = ANV_FENCE_STATE_SIGNALED;
1721 signaled_fences = true;
1722 if (!waitAll)
1723 return VK_SUCCESS;
1724 continue;
1725 }
1726 }
1727 }
1728
1729 if (pending_fences && !signaled_fences) {
1730 /* If we've hit this then someone decided to vkWaitForFences before
1731 * they've actually submitted any of them to a queue. This is a
1732 * fairly pessimal case, so it's ok to lock here and use a standard
1733 * pthreads condition variable.
1734 */
1735 pthread_mutex_lock(&device->mutex);
1736
1737 /* It's possible that some of the fences have changed state since the
1738 * last time we checked. Now that we have the lock, check for
1739 * pending fences again and don't wait if it's changed.
1740 */
1741 uint32_t now_pending_fences = 0;
1742 for (uint32_t i = 0; i < fenceCount; i++) {
1743 ANV_FROM_HANDLE(anv_fence, fence, pFences[i]);
1744 if (fence->state == ANV_FENCE_STATE_RESET)
1745 now_pending_fences++;
1746 }
1747 assert(now_pending_fences <= pending_fences);
1748
1749 if (now_pending_fences == pending_fences) {
1750 struct timespec before;
1751 clock_gettime(CLOCK_MONOTONIC, &before);
1752
1753 uint32_t abs_nsec = before.tv_nsec + timeout % NSEC_PER_SEC;
1754 uint64_t abs_sec = before.tv_sec + (abs_nsec / NSEC_PER_SEC) +
1755 (timeout / NSEC_PER_SEC);
1756 abs_nsec %= NSEC_PER_SEC;
1757
1758 /* Avoid roll-over in tv_sec on 32-bit systems if the user
1759 * provided timeout is UINT64_MAX
1760 */
1761 struct timespec abstime;
1762 abstime.tv_nsec = abs_nsec;
1763 abstime.tv_sec = MIN2(abs_sec, INT_TYPE_MAX(abstime.tv_sec));
1764
1765 ret = pthread_cond_timedwait(&device->queue_submit,
1766 &device->mutex, &abstime);
1767 assert(ret != EINVAL);
1768
1769 struct timespec after;
1770 clock_gettime(CLOCK_MONOTONIC, &after);
1771 uint64_t time_elapsed =
1772 ((uint64_t)after.tv_sec * NSEC_PER_SEC + after.tv_nsec) -
1773 ((uint64_t)before.tv_sec * NSEC_PER_SEC + before.tv_nsec);
1774
1775 if (time_elapsed >= timeout) {
1776 pthread_mutex_unlock(&device->mutex);
1777 return VK_TIMEOUT;
1778 }
1779
1780 timeout -= time_elapsed;
1781 }
1782
1783 pthread_mutex_unlock(&device->mutex);
1784 }
1785 }
1786
1787 return VK_SUCCESS;
1788 }
1789
1790 // Queue semaphore functions
1791
1792 VkResult anv_CreateSemaphore(
1793 VkDevice device,
1794 const VkSemaphoreCreateInfo* pCreateInfo,
1795 const VkAllocationCallbacks* pAllocator,
1796 VkSemaphore* pSemaphore)
1797 {
1798 /* The DRM execbuffer ioctl always execute in-oder, even between different
1799 * rings. As such, there's nothing to do for the user space semaphore.
1800 */
1801
1802 *pSemaphore = (VkSemaphore)1;
1803
1804 return VK_SUCCESS;
1805 }
1806
1807 void anv_DestroySemaphore(
1808 VkDevice device,
1809 VkSemaphore semaphore,
1810 const VkAllocationCallbacks* pAllocator)
1811 {
1812 }
1813
1814 // Event functions
1815
1816 VkResult anv_CreateEvent(
1817 VkDevice _device,
1818 const VkEventCreateInfo* pCreateInfo,
1819 const VkAllocationCallbacks* pAllocator,
1820 VkEvent* pEvent)
1821 {
1822 ANV_FROM_HANDLE(anv_device, device, _device);
1823 struct anv_state state;
1824 struct anv_event *event;
1825
1826 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
1827
1828 state = anv_state_pool_alloc(&device->dynamic_state_pool,
1829 sizeof(*event), 8);
1830 event = state.map;
1831 event->state = state;
1832 event->semaphore = VK_EVENT_RESET;
1833
1834 if (!device->info.has_llc) {
1835 /* Make sure the writes we're flushing have landed. */
1836 __builtin_ia32_mfence();
1837 __builtin_ia32_clflush(event);
1838 }
1839
1840 *pEvent = anv_event_to_handle(event);
1841
1842 return VK_SUCCESS;
1843 }
1844
1845 void anv_DestroyEvent(
1846 VkDevice _device,
1847 VkEvent _event,
1848 const VkAllocationCallbacks* pAllocator)
1849 {
1850 ANV_FROM_HANDLE(anv_device, device, _device);
1851 ANV_FROM_HANDLE(anv_event, event, _event);
1852
1853 if (!event)
1854 return;
1855
1856 anv_state_pool_free(&device->dynamic_state_pool, event->state);
1857 }
1858
1859 VkResult anv_GetEventStatus(
1860 VkDevice _device,
1861 VkEvent _event)
1862 {
1863 ANV_FROM_HANDLE(anv_device, device, _device);
1864 ANV_FROM_HANDLE(anv_event, event, _event);
1865
1866 if (!device->info.has_llc) {
1867 /* Invalidate read cache before reading event written by GPU. */
1868 __builtin_ia32_clflush(event);
1869 __builtin_ia32_mfence();
1870
1871 }
1872
1873 return event->semaphore;
1874 }
1875
1876 VkResult anv_SetEvent(
1877 VkDevice _device,
1878 VkEvent _event)
1879 {
1880 ANV_FROM_HANDLE(anv_device, device, _device);
1881 ANV_FROM_HANDLE(anv_event, event, _event);
1882
1883 event->semaphore = VK_EVENT_SET;
1884
1885 if (!device->info.has_llc) {
1886 /* Make sure the writes we're flushing have landed. */
1887 __builtin_ia32_mfence();
1888 __builtin_ia32_clflush(event);
1889 }
1890
1891 return VK_SUCCESS;
1892 }
1893
1894 VkResult anv_ResetEvent(
1895 VkDevice _device,
1896 VkEvent _event)
1897 {
1898 ANV_FROM_HANDLE(anv_device, device, _device);
1899 ANV_FROM_HANDLE(anv_event, event, _event);
1900
1901 event->semaphore = VK_EVENT_RESET;
1902
1903 if (!device->info.has_llc) {
1904 /* Make sure the writes we're flushing have landed. */
1905 __builtin_ia32_mfence();
1906 __builtin_ia32_clflush(event);
1907 }
1908
1909 return VK_SUCCESS;
1910 }
1911
1912 // Buffer functions
1913
1914 VkResult anv_CreateBuffer(
1915 VkDevice _device,
1916 const VkBufferCreateInfo* pCreateInfo,
1917 const VkAllocationCallbacks* pAllocator,
1918 VkBuffer* pBuffer)
1919 {
1920 ANV_FROM_HANDLE(anv_device, device, _device);
1921 struct anv_buffer *buffer;
1922
1923 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
1924
1925 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
1926 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1927 if (buffer == NULL)
1928 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1929
1930 buffer->size = pCreateInfo->size;
1931 buffer->usage = pCreateInfo->usage;
1932 buffer->bo = NULL;
1933 buffer->offset = 0;
1934
1935 *pBuffer = anv_buffer_to_handle(buffer);
1936
1937 return VK_SUCCESS;
1938 }
1939
1940 void anv_DestroyBuffer(
1941 VkDevice _device,
1942 VkBuffer _buffer,
1943 const VkAllocationCallbacks* pAllocator)
1944 {
1945 ANV_FROM_HANDLE(anv_device, device, _device);
1946 ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
1947
1948 if (!buffer)
1949 return;
1950
1951 vk_free2(&device->alloc, pAllocator, buffer);
1952 }
1953
1954 void
1955 anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
1956 enum isl_format format,
1957 uint32_t offset, uint32_t range, uint32_t stride)
1958 {
1959 isl_buffer_fill_state(&device->isl_dev, state.map,
1960 .address = offset,
1961 .mocs = device->default_mocs,
1962 .size = range,
1963 .format = format,
1964 .stride = stride);
1965
1966 if (!device->info.has_llc)
1967 anv_state_clflush(state);
1968 }
1969
1970 void anv_DestroySampler(
1971 VkDevice _device,
1972 VkSampler _sampler,
1973 const VkAllocationCallbacks* pAllocator)
1974 {
1975 ANV_FROM_HANDLE(anv_device, device, _device);
1976 ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
1977
1978 if (!sampler)
1979 return;
1980
1981 vk_free2(&device->alloc, pAllocator, sampler);
1982 }
1983
1984 VkResult anv_CreateFramebuffer(
1985 VkDevice _device,
1986 const VkFramebufferCreateInfo* pCreateInfo,
1987 const VkAllocationCallbacks* pAllocator,
1988 VkFramebuffer* pFramebuffer)
1989 {
1990 ANV_FROM_HANDLE(anv_device, device, _device);
1991 struct anv_framebuffer *framebuffer;
1992
1993 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
1994
1995 size_t size = sizeof(*framebuffer) +
1996 sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
1997 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
1998 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1999 if (framebuffer == NULL)
2000 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2001
2002 framebuffer->attachment_count = pCreateInfo->attachmentCount;
2003 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
2004 VkImageView _iview = pCreateInfo->pAttachments[i];
2005 framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
2006 }
2007
2008 framebuffer->width = pCreateInfo->width;
2009 framebuffer->height = pCreateInfo->height;
2010 framebuffer->layers = pCreateInfo->layers;
2011
2012 *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
2013
2014 return VK_SUCCESS;
2015 }
2016
2017 void anv_DestroyFramebuffer(
2018 VkDevice _device,
2019 VkFramebuffer _fb,
2020 const VkAllocationCallbacks* pAllocator)
2021 {
2022 ANV_FROM_HANDLE(anv_device, device, _device);
2023 ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
2024
2025 if (!fb)
2026 return;
2027
2028 vk_free2(&device->alloc, pAllocator, fb);
2029 }