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