radv: handle fence allocation failing
[mesa.git] / src / amd / vulkan / radv_device.c
1 /*
2 * Copyright © 2016 Red Hat.
3 * Copyright © 2016 Bas Nieuwenhuizen
4 *
5 * based in part on anv driver which is:
6 * Copyright © 2015 Intel Corporation
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice (including the next
16 * paragraph) shall be included in all copies or substantial portions of the
17 * Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
24 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
25 * IN THE SOFTWARE.
26 */
27
28 #include <dlfcn.h>
29 #include <stdbool.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <fcntl.h>
33 #include <sys/stat.h>
34 #include "radv_private.h"
35 #include "util/strtod.h"
36
37 #include <xf86drm.h>
38 #include <amdgpu.h>
39 #include <amdgpu_drm.h>
40 #include "amdgpu_id.h"
41 #include "winsys/amdgpu/radv_amdgpu_winsys_public.h"
42 #include "ac_llvm_util.h"
43 #include "vk_format.h"
44 #include "sid.h"
45 #include "util/debug.h"
46 struct radv_dispatch_table dtable;
47
48 static int
49 radv_get_function_timestamp(void *ptr, uint32_t* timestamp)
50 {
51 Dl_info info;
52 struct stat st;
53 if (!dladdr(ptr, &info) || !info.dli_fname) {
54 return -1;
55 }
56 if (stat(info.dli_fname, &st)) {
57 return -1;
58 }
59 *timestamp = st.st_mtim.tv_sec;
60 return 0;
61 }
62
63 static int
64 radv_device_get_cache_uuid(enum radeon_family family, void *uuid)
65 {
66 uint32_t mesa_timestamp, llvm_timestamp;
67 uint16_t f = family;
68 memset(uuid, 0, VK_UUID_SIZE);
69 if (radv_get_function_timestamp(radv_device_get_cache_uuid, &mesa_timestamp) ||
70 radv_get_function_timestamp(LLVMInitializeAMDGPUTargetInfo, &llvm_timestamp))
71 return -1;
72
73 memcpy(uuid, &mesa_timestamp, 4);
74 memcpy((char*)uuid + 4, &llvm_timestamp, 4);
75 memcpy((char*)uuid + 8, &f, 2);
76 snprintf((char*)uuid + 10, VK_UUID_SIZE - 10, "radv");
77 return 0;
78 }
79
80 static VkResult
81 radv_physical_device_init(struct radv_physical_device *device,
82 struct radv_instance *instance,
83 const char *path)
84 {
85 VkResult result;
86 drmVersionPtr version;
87 int fd;
88
89 fd = open(path, O_RDWR | O_CLOEXEC);
90 if (fd < 0)
91 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
92 "failed to open %s: %m", path);
93
94 version = drmGetVersion(fd);
95 if (!version) {
96 close(fd);
97 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
98 "failed to get version %s: %m", path);
99 }
100
101 if (strcmp(version->name, "amdgpu")) {
102 drmFreeVersion(version);
103 close(fd);
104 return VK_ERROR_INCOMPATIBLE_DRIVER;
105 }
106 drmFreeVersion(version);
107
108 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
109 device->instance = instance;
110 assert(strlen(path) < ARRAY_SIZE(device->path));
111 strncpy(device->path, path, ARRAY_SIZE(device->path));
112
113 device->ws = radv_amdgpu_winsys_create(fd);
114 if (!device->ws) {
115 result = VK_ERROR_INCOMPATIBLE_DRIVER;
116 goto fail;
117 }
118 device->ws->query_info(device->ws, &device->rad_info);
119 result = radv_init_wsi(device);
120 if (result != VK_SUCCESS) {
121 device->ws->destroy(device->ws);
122 goto fail;
123 }
124
125 if (radv_device_get_cache_uuid(device->rad_info.family, device->uuid)) {
126 radv_finish_wsi(device);
127 device->ws->destroy(device->ws);
128 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
129 "cannot generate UUID");
130 goto fail;
131 }
132
133 fprintf(stderr, "WARNING: radv is not a conformant vulkan implementation, testing use only.\n");
134 device->name = device->rad_info.name;
135 close(fd);
136 return VK_SUCCESS;
137
138 fail:
139 close(fd);
140 return result;
141 }
142
143 static void
144 radv_physical_device_finish(struct radv_physical_device *device)
145 {
146 radv_finish_wsi(device);
147 device->ws->destroy(device->ws);
148 }
149
150 static const VkExtensionProperties global_extensions[] = {
151 {
152 .extensionName = VK_KHR_SURFACE_EXTENSION_NAME,
153 .specVersion = 25,
154 },
155 #ifdef VK_USE_PLATFORM_XCB_KHR
156 {
157 .extensionName = VK_KHR_XCB_SURFACE_EXTENSION_NAME,
158 .specVersion = 6,
159 },
160 #endif
161 #ifdef VK_USE_PLATFORM_XLIB_KHR
162 {
163 .extensionName = VK_KHR_XLIB_SURFACE_EXTENSION_NAME,
164 .specVersion = 6,
165 },
166 #endif
167 #ifdef VK_USE_PLATFORM_WAYLAND_KHR
168 {
169 .extensionName = VK_KHR_WAYLAND_SURFACE_EXTENSION_NAME,
170 .specVersion = 5,
171 },
172 #endif
173 };
174
175 static const VkExtensionProperties device_extensions[] = {
176 {
177 .extensionName = VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME,
178 .specVersion = 1,
179 },
180 {
181 .extensionName = VK_KHR_SWAPCHAIN_EXTENSION_NAME,
182 .specVersion = 68,
183 },
184 {
185 .extensionName = VK_AMD_DRAW_INDIRECT_COUNT_EXTENSION_NAME,
186 .specVersion = 1,
187 },
188 {
189 .extensionName = VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME,
190 .specVersion = 1,
191 },
192 };
193
194 static void *
195 default_alloc_func(void *pUserData, size_t size, size_t align,
196 VkSystemAllocationScope allocationScope)
197 {
198 return malloc(size);
199 }
200
201 static void *
202 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
203 size_t align, VkSystemAllocationScope allocationScope)
204 {
205 return realloc(pOriginal, size);
206 }
207
208 static void
209 default_free_func(void *pUserData, void *pMemory)
210 {
211 free(pMemory);
212 }
213
214 static const VkAllocationCallbacks default_alloc = {
215 .pUserData = NULL,
216 .pfnAllocation = default_alloc_func,
217 .pfnReallocation = default_realloc_func,
218 .pfnFree = default_free_func,
219 };
220
221 VkResult radv_CreateInstance(
222 const VkInstanceCreateInfo* pCreateInfo,
223 const VkAllocationCallbacks* pAllocator,
224 VkInstance* pInstance)
225 {
226 struct radv_instance *instance;
227
228 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
229
230 uint32_t client_version;
231 if (pCreateInfo->pApplicationInfo &&
232 pCreateInfo->pApplicationInfo->apiVersion != 0) {
233 client_version = pCreateInfo->pApplicationInfo->apiVersion;
234 } else {
235 client_version = VK_MAKE_VERSION(1, 0, 0);
236 }
237
238 if (VK_MAKE_VERSION(1, 0, 0) > client_version ||
239 client_version > VK_MAKE_VERSION(1, 0, 0xfff)) {
240 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
241 "Client requested version %d.%d.%d",
242 VK_VERSION_MAJOR(client_version),
243 VK_VERSION_MINOR(client_version),
244 VK_VERSION_PATCH(client_version));
245 }
246
247 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
248 bool found = false;
249 for (uint32_t j = 0; j < ARRAY_SIZE(global_extensions); j++) {
250 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
251 global_extensions[j].extensionName) == 0) {
252 found = true;
253 break;
254 }
255 }
256 if (!found)
257 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
258 }
259
260 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
261 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
262 if (!instance)
263 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
264
265 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
266
267 if (pAllocator)
268 instance->alloc = *pAllocator;
269 else
270 instance->alloc = default_alloc;
271
272 instance->apiVersion = client_version;
273 instance->physicalDeviceCount = -1;
274
275 _mesa_locale_init();
276
277 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
278
279 *pInstance = radv_instance_to_handle(instance);
280
281 return VK_SUCCESS;
282 }
283
284 void radv_DestroyInstance(
285 VkInstance _instance,
286 const VkAllocationCallbacks* pAllocator)
287 {
288 RADV_FROM_HANDLE(radv_instance, instance, _instance);
289
290 if (instance->physicalDeviceCount > 0) {
291 /* We support at most one physical device. */
292 assert(instance->physicalDeviceCount == 1);
293 radv_physical_device_finish(&instance->physicalDevice);
294 }
295
296 VG(VALGRIND_DESTROY_MEMPOOL(instance));
297
298 _mesa_locale_fini();
299
300 vk_free(&instance->alloc, instance);
301 }
302
303 VkResult radv_EnumeratePhysicalDevices(
304 VkInstance _instance,
305 uint32_t* pPhysicalDeviceCount,
306 VkPhysicalDevice* pPhysicalDevices)
307 {
308 RADV_FROM_HANDLE(radv_instance, instance, _instance);
309 VkResult result;
310
311 if (instance->physicalDeviceCount < 0) {
312 char path[20];
313 for (unsigned i = 0; i < 8; i++) {
314 snprintf(path, sizeof(path), "/dev/dri/renderD%d", 128 + i);
315 result = radv_physical_device_init(&instance->physicalDevice,
316 instance, path);
317 if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
318 break;
319 }
320
321 if (result == VK_ERROR_INCOMPATIBLE_DRIVER) {
322 instance->physicalDeviceCount = 0;
323 } else if (result == VK_SUCCESS) {
324 instance->physicalDeviceCount = 1;
325 } else {
326 return result;
327 }
328 }
329
330 /* pPhysicalDeviceCount is an out parameter if pPhysicalDevices is NULL;
331 * otherwise it's an inout parameter.
332 *
333 * The Vulkan spec (git aaed022) says:
334 *
335 * pPhysicalDeviceCount is a pointer to an unsigned integer variable
336 * that is initialized with the number of devices the application is
337 * prepared to receive handles to. pname:pPhysicalDevices is pointer to
338 * an array of at least this many VkPhysicalDevice handles [...].
339 *
340 * Upon success, if pPhysicalDevices is NULL, vkEnumeratePhysicalDevices
341 * overwrites the contents of the variable pointed to by
342 * pPhysicalDeviceCount with the number of physical devices in in the
343 * instance; otherwise, vkEnumeratePhysicalDevices overwrites
344 * pPhysicalDeviceCount with the number of physical handles written to
345 * pPhysicalDevices.
346 */
347 if (!pPhysicalDevices) {
348 *pPhysicalDeviceCount = instance->physicalDeviceCount;
349 } else if (*pPhysicalDeviceCount >= 1) {
350 pPhysicalDevices[0] = radv_physical_device_to_handle(&instance->physicalDevice);
351 *pPhysicalDeviceCount = 1;
352 } else if (*pPhysicalDeviceCount < instance->physicalDeviceCount) {
353 return VK_INCOMPLETE;
354 } else {
355 *pPhysicalDeviceCount = 0;
356 }
357
358 return VK_SUCCESS;
359 }
360
361 void radv_GetPhysicalDeviceFeatures(
362 VkPhysicalDevice physicalDevice,
363 VkPhysicalDeviceFeatures* pFeatures)
364 {
365 // RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
366
367 memset(pFeatures, 0, sizeof(*pFeatures));
368
369 *pFeatures = (VkPhysicalDeviceFeatures) {
370 .robustBufferAccess = true,
371 .fullDrawIndexUint32 = true,
372 .imageCubeArray = true,
373 .independentBlend = true,
374 .geometryShader = false,
375 .tessellationShader = false,
376 .sampleRateShading = false,
377 .dualSrcBlend = true,
378 .logicOp = true,
379 .multiDrawIndirect = true,
380 .drawIndirectFirstInstance = true,
381 .depthClamp = true,
382 .depthBiasClamp = true,
383 .fillModeNonSolid = true,
384 .depthBounds = true,
385 .wideLines = true,
386 .largePoints = true,
387 .alphaToOne = true,
388 .multiViewport = false,
389 .samplerAnisotropy = true,
390 .textureCompressionETC2 = false,
391 .textureCompressionASTC_LDR = false,
392 .textureCompressionBC = true,
393 .occlusionQueryPrecise = true,
394 .pipelineStatisticsQuery = false,
395 .vertexPipelineStoresAndAtomics = true,
396 .fragmentStoresAndAtomics = true,
397 .shaderTessellationAndGeometryPointSize = true,
398 .shaderImageGatherExtended = false,
399 .shaderStorageImageExtendedFormats = false,
400 .shaderStorageImageMultisample = false,
401 .shaderUniformBufferArrayDynamicIndexing = true,
402 .shaderSampledImageArrayDynamicIndexing = true,
403 .shaderStorageBufferArrayDynamicIndexing = true,
404 .shaderStorageImageArrayDynamicIndexing = true,
405 .shaderStorageImageReadWithoutFormat = false,
406 .shaderStorageImageWriteWithoutFormat = true,
407 .shaderClipDistance = true,
408 .shaderCullDistance = true,
409 .shaderFloat64 = false,
410 .shaderInt64 = false,
411 .shaderInt16 = false,
412 .alphaToOne = true,
413 .variableMultisampleRate = false,
414 .inheritedQueries = false,
415 };
416 }
417
418 void radv_GetPhysicalDeviceProperties(
419 VkPhysicalDevice physicalDevice,
420 VkPhysicalDeviceProperties* pProperties)
421 {
422 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
423 VkSampleCountFlags sample_counts = 0xf;
424 VkPhysicalDeviceLimits limits = {
425 .maxImageDimension1D = (1 << 14),
426 .maxImageDimension2D = (1 << 14),
427 .maxImageDimension3D = (1 << 11),
428 .maxImageDimensionCube = (1 << 14),
429 .maxImageArrayLayers = (1 << 11),
430 .maxTexelBufferElements = 128 * 1024 * 1024,
431 .maxUniformBufferRange = UINT32_MAX,
432 .maxStorageBufferRange = UINT32_MAX,
433 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
434 .maxMemoryAllocationCount = UINT32_MAX,
435 .maxSamplerAllocationCount = 64 * 1024,
436 .bufferImageGranularity = 64, /* A cache line */
437 .sparseAddressSpaceSize = 0,
438 .maxBoundDescriptorSets = MAX_SETS,
439 .maxPerStageDescriptorSamplers = 64,
440 .maxPerStageDescriptorUniformBuffers = 64,
441 .maxPerStageDescriptorStorageBuffers = 64,
442 .maxPerStageDescriptorSampledImages = 64,
443 .maxPerStageDescriptorStorageImages = 64,
444 .maxPerStageDescriptorInputAttachments = 64,
445 .maxPerStageResources = 128,
446 .maxDescriptorSetSamplers = 256,
447 .maxDescriptorSetUniformBuffers = 256,
448 .maxDescriptorSetUniformBuffersDynamic = 256,
449 .maxDescriptorSetStorageBuffers = 256,
450 .maxDescriptorSetStorageBuffersDynamic = 256,
451 .maxDescriptorSetSampledImages = 256,
452 .maxDescriptorSetStorageImages = 256,
453 .maxDescriptorSetInputAttachments = 256,
454 .maxVertexInputAttributes = 32,
455 .maxVertexInputBindings = 32,
456 .maxVertexInputAttributeOffset = 2047,
457 .maxVertexInputBindingStride = 2048,
458 .maxVertexOutputComponents = 128,
459 .maxTessellationGenerationLevel = 0,
460 .maxTessellationPatchSize = 0,
461 .maxTessellationControlPerVertexInputComponents = 0,
462 .maxTessellationControlPerVertexOutputComponents = 0,
463 .maxTessellationControlPerPatchOutputComponents = 0,
464 .maxTessellationControlTotalOutputComponents = 0,
465 .maxTessellationEvaluationInputComponents = 0,
466 .maxTessellationEvaluationOutputComponents = 0,
467 .maxGeometryShaderInvocations = 32,
468 .maxGeometryInputComponents = 64,
469 .maxGeometryOutputComponents = 128,
470 .maxGeometryOutputVertices = 256,
471 .maxGeometryTotalOutputComponents = 1024,
472 .maxFragmentInputComponents = 128,
473 .maxFragmentOutputAttachments = 8,
474 .maxFragmentDualSrcAttachments = 1,
475 .maxFragmentCombinedOutputResources = 8,
476 .maxComputeSharedMemorySize = 32768,
477 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
478 .maxComputeWorkGroupInvocations = 16 * 1024,
479 .maxComputeWorkGroupSize = {
480 16 * 1024/*devinfo->max_cs_threads*/,
481 16 * 1024,
482 16 * 1024
483 },
484 .subPixelPrecisionBits = 4 /* FIXME */,
485 .subTexelPrecisionBits = 4 /* FIXME */,
486 .mipmapPrecisionBits = 4 /* FIXME */,
487 .maxDrawIndexedIndexValue = UINT32_MAX,
488 .maxDrawIndirectCount = UINT32_MAX,
489 .maxSamplerLodBias = 16,
490 .maxSamplerAnisotropy = 16,
491 .maxViewports = MAX_VIEWPORTS,
492 .maxViewportDimensions = { (1 << 14), (1 << 14) },
493 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
494 .viewportSubPixelBits = 13, /* We take a float? */
495 .minMemoryMapAlignment = 4096, /* A page */
496 .minTexelBufferOffsetAlignment = 1,
497 .minUniformBufferOffsetAlignment = 4,
498 .minStorageBufferOffsetAlignment = 4,
499 .minTexelOffset = -8,
500 .maxTexelOffset = 7,
501 .minTexelGatherOffset = -8,
502 .maxTexelGatherOffset = 7,
503 .minInterpolationOffset = 0, /* FIXME */
504 .maxInterpolationOffset = 0, /* FIXME */
505 .subPixelInterpolationOffsetBits = 0, /* FIXME */
506 .maxFramebufferWidth = (1 << 14),
507 .maxFramebufferHeight = (1 << 14),
508 .maxFramebufferLayers = (1 << 10),
509 .framebufferColorSampleCounts = sample_counts,
510 .framebufferDepthSampleCounts = sample_counts,
511 .framebufferStencilSampleCounts = sample_counts,
512 .framebufferNoAttachmentsSampleCounts = sample_counts,
513 .maxColorAttachments = MAX_RTS,
514 .sampledImageColorSampleCounts = sample_counts,
515 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
516 .sampledImageDepthSampleCounts = sample_counts,
517 .sampledImageStencilSampleCounts = sample_counts,
518 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
519 .maxSampleMaskWords = 1,
520 .timestampComputeAndGraphics = false,
521 .timestampPeriod = 100000.0 / pdevice->rad_info.clock_crystal_freq,
522 .maxClipDistances = 8,
523 .maxCullDistances = 8,
524 .maxCombinedClipAndCullDistances = 8,
525 .discreteQueuePriorities = 1,
526 .pointSizeRange = { 0.125, 255.875 },
527 .lineWidthRange = { 0.0, 7.9921875 },
528 .pointSizeGranularity = (1.0 / 8.0),
529 .lineWidthGranularity = (1.0 / 128.0),
530 .strictLines = false, /* FINISHME */
531 .standardSampleLocations = true,
532 .optimalBufferCopyOffsetAlignment = 128,
533 .optimalBufferCopyRowPitchAlignment = 128,
534 .nonCoherentAtomSize = 64,
535 };
536
537 *pProperties = (VkPhysicalDeviceProperties) {
538 .apiVersion = VK_MAKE_VERSION(1, 0, 5),
539 .driverVersion = 1,
540 .vendorID = 0x1002,
541 .deviceID = pdevice->rad_info.pci_id,
542 .deviceType = VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU,
543 .limits = limits,
544 .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
545 };
546
547 strcpy(pProperties->deviceName, pdevice->name);
548 memcpy(pProperties->pipelineCacheUUID, pdevice->uuid, VK_UUID_SIZE);
549 }
550
551 void radv_GetPhysicalDeviceQueueFamilyProperties(
552 VkPhysicalDevice physicalDevice,
553 uint32_t* pCount,
554 VkQueueFamilyProperties* pQueueFamilyProperties)
555 {
556 if (pQueueFamilyProperties == NULL) {
557 *pCount = 1;
558 return;
559 }
560 assert(*pCount >= 1);
561
562 *pQueueFamilyProperties = (VkQueueFamilyProperties) {
563 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
564 VK_QUEUE_COMPUTE_BIT |
565 VK_QUEUE_TRANSFER_BIT,
566 .queueCount = 1,
567 .timestampValidBits = 64,
568 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
569 };
570 }
571
572 void radv_GetPhysicalDeviceMemoryProperties(
573 VkPhysicalDevice physicalDevice,
574 VkPhysicalDeviceMemoryProperties* pMemoryProperties)
575 {
576 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
577
578 STATIC_ASSERT(RADV_MEM_TYPE_COUNT <= VK_MAX_MEMORY_TYPES);
579
580 pMemoryProperties->memoryTypeCount = RADV_MEM_TYPE_COUNT;
581 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_VRAM] = (VkMemoryType) {
582 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
583 .heapIndex = RADV_MEM_HEAP_VRAM,
584 };
585 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_GTT_WRITE_COMBINE] = (VkMemoryType) {
586 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
587 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
588 .heapIndex = RADV_MEM_HEAP_GTT,
589 };
590 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_VRAM_CPU_ACCESS] = (VkMemoryType) {
591 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
592 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
593 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
594 .heapIndex = RADV_MEM_HEAP_VRAM_CPU_ACCESS,
595 };
596 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_GTT_CACHED] = (VkMemoryType) {
597 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
598 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
599 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
600 .heapIndex = RADV_MEM_HEAP_GTT,
601 };
602
603 STATIC_ASSERT(RADV_MEM_HEAP_COUNT <= VK_MAX_MEMORY_HEAPS);
604
605 pMemoryProperties->memoryHeapCount = RADV_MEM_HEAP_COUNT;
606 pMemoryProperties->memoryHeaps[RADV_MEM_HEAP_VRAM] = (VkMemoryHeap) {
607 .size = physical_device->rad_info.vram_size -
608 physical_device->rad_info.visible_vram_size,
609 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
610 };
611 pMemoryProperties->memoryHeaps[RADV_MEM_HEAP_VRAM_CPU_ACCESS] = (VkMemoryHeap) {
612 .size = physical_device->rad_info.visible_vram_size,
613 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
614 };
615 pMemoryProperties->memoryHeaps[RADV_MEM_HEAP_GTT] = (VkMemoryHeap) {
616 .size = physical_device->rad_info.gart_size,
617 .flags = 0,
618 };
619 }
620
621 static void
622 radv_queue_init(struct radv_device *device, struct radv_queue *queue)
623 {
624 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
625 queue->device = device;
626 }
627
628 static void
629 radv_queue_finish(struct radv_queue *queue)
630 {
631 }
632
633 VkResult radv_CreateDevice(
634 VkPhysicalDevice physicalDevice,
635 const VkDeviceCreateInfo* pCreateInfo,
636 const VkAllocationCallbacks* pAllocator,
637 VkDevice* pDevice)
638 {
639 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
640 VkResult result;
641 struct radv_device *device;
642
643 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
644 bool found = false;
645 for (uint32_t j = 0; j < ARRAY_SIZE(device_extensions); j++) {
646 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
647 device_extensions[j].extensionName) == 0) {
648 found = true;
649 break;
650 }
651 }
652 if (!found)
653 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
654 }
655
656 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
657 sizeof(*device), 8,
658 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
659 if (!device)
660 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
661
662 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
663 device->instance = physical_device->instance;
664 device->shader_stats_dump = false;
665
666 device->ws = physical_device->ws;
667 if (pAllocator)
668 device->alloc = *pAllocator;
669 else
670 device->alloc = physical_device->instance->alloc;
671
672 device->hw_ctx = device->ws->ctx_create(device->ws);
673 if (!device->hw_ctx) {
674 result = VK_ERROR_OUT_OF_HOST_MEMORY;
675 goto fail_free;
676 }
677
678 radv_queue_init(device, &device->queue);
679
680 result = radv_device_init_meta(device);
681 if (result != VK_SUCCESS) {
682 device->ws->ctx_destroy(device->hw_ctx);
683 goto fail_free;
684 }
685 device->allow_fast_clears = env_var_as_boolean("RADV_FAST_CLEARS", false);
686 device->allow_dcc = !env_var_as_boolean("RADV_DCC_DISABLE", false);
687 device->shader_stats_dump = env_var_as_boolean("RADV_SHADER_STATS", false);
688
689 if (device->allow_fast_clears && device->allow_dcc)
690 radv_finishme("DCC fast clears have not been tested\n");
691
692 radv_device_init_msaa(device);
693 device->empty_cs = device->ws->cs_create(device->ws, RING_GFX);
694 radeon_emit(device->empty_cs, PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
695 radeon_emit(device->empty_cs, CONTEXT_CONTROL_LOAD_ENABLE(1));
696 radeon_emit(device->empty_cs, CONTEXT_CONTROL_SHADOW_ENABLE(1));
697 device->ws->cs_finalize(device->empty_cs);
698 *pDevice = radv_device_to_handle(device);
699 return VK_SUCCESS;
700 fail_free:
701 vk_free(&device->alloc, device);
702 return result;
703 }
704
705 void radv_DestroyDevice(
706 VkDevice _device,
707 const VkAllocationCallbacks* pAllocator)
708 {
709 RADV_FROM_HANDLE(radv_device, device, _device);
710
711 device->ws->ctx_destroy(device->hw_ctx);
712 radv_queue_finish(&device->queue);
713 radv_device_finish_meta(device);
714
715 vk_free(&device->alloc, device);
716 }
717
718 VkResult radv_EnumerateInstanceExtensionProperties(
719 const char* pLayerName,
720 uint32_t* pPropertyCount,
721 VkExtensionProperties* pProperties)
722 {
723 if (pProperties == NULL) {
724 *pPropertyCount = ARRAY_SIZE(global_extensions);
725 return VK_SUCCESS;
726 }
727
728 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(global_extensions));
729 typed_memcpy(pProperties, global_extensions, *pPropertyCount);
730
731 if (*pPropertyCount < ARRAY_SIZE(global_extensions))
732 return VK_INCOMPLETE;
733
734 return VK_SUCCESS;
735 }
736
737 VkResult radv_EnumerateDeviceExtensionProperties(
738 VkPhysicalDevice physicalDevice,
739 const char* pLayerName,
740 uint32_t* pPropertyCount,
741 VkExtensionProperties* pProperties)
742 {
743 if (pProperties == NULL) {
744 *pPropertyCount = ARRAY_SIZE(device_extensions);
745 return VK_SUCCESS;
746 }
747
748 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(device_extensions));
749 typed_memcpy(pProperties, device_extensions, *pPropertyCount);
750
751 if (*pPropertyCount < ARRAY_SIZE(device_extensions))
752 return VK_INCOMPLETE;
753
754 return VK_SUCCESS;
755 }
756
757 VkResult radv_EnumerateInstanceLayerProperties(
758 uint32_t* pPropertyCount,
759 VkLayerProperties* pProperties)
760 {
761 if (pProperties == NULL) {
762 *pPropertyCount = 0;
763 return VK_SUCCESS;
764 }
765
766 /* None supported at this time */
767 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
768 }
769
770 VkResult radv_EnumerateDeviceLayerProperties(
771 VkPhysicalDevice physicalDevice,
772 uint32_t* pPropertyCount,
773 VkLayerProperties* pProperties)
774 {
775 if (pProperties == NULL) {
776 *pPropertyCount = 0;
777 return VK_SUCCESS;
778 }
779
780 /* None supported at this time */
781 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
782 }
783
784 void radv_GetDeviceQueue(
785 VkDevice _device,
786 uint32_t queueNodeIndex,
787 uint32_t queueIndex,
788 VkQueue* pQueue)
789 {
790 RADV_FROM_HANDLE(radv_device, device, _device);
791
792 assert(queueIndex == 0);
793
794 *pQueue = radv_queue_to_handle(&device->queue);
795 }
796
797 VkResult radv_QueueSubmit(
798 VkQueue _queue,
799 uint32_t submitCount,
800 const VkSubmitInfo* pSubmits,
801 VkFence _fence)
802 {
803 RADV_FROM_HANDLE(radv_queue, queue, _queue);
804 RADV_FROM_HANDLE(radv_fence, fence, _fence);
805 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
806 struct radeon_winsys_ctx *ctx = queue->device->hw_ctx;
807 int ret;
808
809 for (uint32_t i = 0; i < submitCount; i++) {
810 struct radeon_winsys_cs **cs_array;
811 bool can_patch = true;
812
813 if (!pSubmits[i].commandBufferCount)
814 continue;
815
816 cs_array = malloc(sizeof(struct radeon_winsys_cs *) *
817 pSubmits[i].commandBufferCount);
818
819 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
820 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
821 pSubmits[i].pCommandBuffers[j]);
822 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
823
824 cs_array[j] = cmd_buffer->cs;
825 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
826 can_patch = false;
827 }
828 ret = queue->device->ws->cs_submit(ctx, cs_array,
829 pSubmits[i].commandBufferCount,
830 can_patch, base_fence);
831 if (ret)
832 radv_loge("failed to submit CS %d\n", i);
833 free(cs_array);
834 }
835
836 if (fence) {
837 if (!submitCount)
838 ret = queue->device->ws->cs_submit(ctx, &queue->device->empty_cs,
839 1, false, base_fence);
840
841 fence->submitted = true;
842 }
843
844 return VK_SUCCESS;
845 }
846
847 VkResult radv_QueueWaitIdle(
848 VkQueue _queue)
849 {
850 RADV_FROM_HANDLE(radv_queue, queue, _queue);
851
852 queue->device->ws->ctx_wait_idle(queue->device->hw_ctx);
853 return VK_SUCCESS;
854 }
855
856 VkResult radv_DeviceWaitIdle(
857 VkDevice _device)
858 {
859 RADV_FROM_HANDLE(radv_device, device, _device);
860
861 device->ws->ctx_wait_idle(device->hw_ctx);
862 return VK_SUCCESS;
863 }
864
865 PFN_vkVoidFunction radv_GetInstanceProcAddr(
866 VkInstance instance,
867 const char* pName)
868 {
869 return radv_lookup_entrypoint(pName);
870 }
871
872 /* The loader wants us to expose a second GetInstanceProcAddr function
873 * to work around certain LD_PRELOAD issues seen in apps.
874 */
875 PUBLIC
876 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
877 VkInstance instance,
878 const char* pName);
879
880 PUBLIC
881 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
882 VkInstance instance,
883 const char* pName)
884 {
885 return radv_GetInstanceProcAddr(instance, pName);
886 }
887
888 PFN_vkVoidFunction radv_GetDeviceProcAddr(
889 VkDevice device,
890 const char* pName)
891 {
892 return radv_lookup_entrypoint(pName);
893 }
894
895 VkResult radv_AllocateMemory(
896 VkDevice _device,
897 const VkMemoryAllocateInfo* pAllocateInfo,
898 const VkAllocationCallbacks* pAllocator,
899 VkDeviceMemory* pMem)
900 {
901 RADV_FROM_HANDLE(radv_device, device, _device);
902 struct radv_device_memory *mem;
903 VkResult result;
904 enum radeon_bo_domain domain;
905 uint32_t flags = 0;
906 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
907
908 if (pAllocateInfo->allocationSize == 0) {
909 /* Apparently, this is allowed */
910 *pMem = VK_NULL_HANDLE;
911 return VK_SUCCESS;
912 }
913
914 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
915 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
916 if (mem == NULL)
917 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
918
919 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
920 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_WRITE_COMBINE ||
921 pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_CACHED)
922 domain = RADEON_DOMAIN_GTT;
923 else
924 domain = RADEON_DOMAIN_VRAM;
925
926 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_VRAM)
927 flags |= RADEON_FLAG_NO_CPU_ACCESS;
928 else
929 flags |= RADEON_FLAG_CPU_ACCESS;
930
931 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_WRITE_COMBINE)
932 flags |= RADEON_FLAG_GTT_WC;
933
934 mem->bo = device->ws->buffer_create(device->ws, alloc_size, 32768,
935 domain, flags);
936
937 if (!mem->bo) {
938 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
939 goto fail;
940 }
941 mem->type_index = pAllocateInfo->memoryTypeIndex;
942
943 *pMem = radv_device_memory_to_handle(mem);
944
945 return VK_SUCCESS;
946
947 fail:
948 vk_free2(&device->alloc, pAllocator, mem);
949
950 return result;
951 }
952
953 void radv_FreeMemory(
954 VkDevice _device,
955 VkDeviceMemory _mem,
956 const VkAllocationCallbacks* pAllocator)
957 {
958 RADV_FROM_HANDLE(radv_device, device, _device);
959 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
960
961 if (mem == NULL)
962 return;
963
964 device->ws->buffer_destroy(mem->bo);
965 mem->bo = NULL;
966
967 vk_free2(&device->alloc, pAllocator, mem);
968 }
969
970 VkResult radv_MapMemory(
971 VkDevice _device,
972 VkDeviceMemory _memory,
973 VkDeviceSize offset,
974 VkDeviceSize size,
975 VkMemoryMapFlags flags,
976 void** ppData)
977 {
978 RADV_FROM_HANDLE(radv_device, device, _device);
979 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
980
981 if (mem == NULL) {
982 *ppData = NULL;
983 return VK_SUCCESS;
984 }
985
986 *ppData = device->ws->buffer_map(mem->bo);
987 if (*ppData) {
988 *ppData += offset;
989 return VK_SUCCESS;
990 }
991
992 return VK_ERROR_MEMORY_MAP_FAILED;
993 }
994
995 void radv_UnmapMemory(
996 VkDevice _device,
997 VkDeviceMemory _memory)
998 {
999 RADV_FROM_HANDLE(radv_device, device, _device);
1000 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
1001
1002 if (mem == NULL)
1003 return;
1004
1005 device->ws->buffer_unmap(mem->bo);
1006 }
1007
1008 VkResult radv_FlushMappedMemoryRanges(
1009 VkDevice _device,
1010 uint32_t memoryRangeCount,
1011 const VkMappedMemoryRange* pMemoryRanges)
1012 {
1013 return VK_SUCCESS;
1014 }
1015
1016 VkResult radv_InvalidateMappedMemoryRanges(
1017 VkDevice _device,
1018 uint32_t memoryRangeCount,
1019 const VkMappedMemoryRange* pMemoryRanges)
1020 {
1021 return VK_SUCCESS;
1022 }
1023
1024 void radv_GetBufferMemoryRequirements(
1025 VkDevice device,
1026 VkBuffer _buffer,
1027 VkMemoryRequirements* pMemoryRequirements)
1028 {
1029 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
1030
1031 pMemoryRequirements->memoryTypeBits = (1u << RADV_MEM_TYPE_COUNT) - 1;
1032
1033 pMemoryRequirements->size = buffer->size;
1034 pMemoryRequirements->alignment = 16;
1035 }
1036
1037 void radv_GetImageMemoryRequirements(
1038 VkDevice device,
1039 VkImage _image,
1040 VkMemoryRequirements* pMemoryRequirements)
1041 {
1042 RADV_FROM_HANDLE(radv_image, image, _image);
1043
1044 pMemoryRequirements->memoryTypeBits = (1u << RADV_MEM_TYPE_COUNT) - 1;
1045
1046 pMemoryRequirements->size = image->size;
1047 pMemoryRequirements->alignment = image->alignment;
1048 }
1049
1050 void radv_GetImageSparseMemoryRequirements(
1051 VkDevice device,
1052 VkImage image,
1053 uint32_t* pSparseMemoryRequirementCount,
1054 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
1055 {
1056 stub();
1057 }
1058
1059 void radv_GetDeviceMemoryCommitment(
1060 VkDevice device,
1061 VkDeviceMemory memory,
1062 VkDeviceSize* pCommittedMemoryInBytes)
1063 {
1064 *pCommittedMemoryInBytes = 0;
1065 }
1066
1067 VkResult radv_BindBufferMemory(
1068 VkDevice device,
1069 VkBuffer _buffer,
1070 VkDeviceMemory _memory,
1071 VkDeviceSize memoryOffset)
1072 {
1073 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
1074 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
1075
1076 if (mem) {
1077 buffer->bo = mem->bo;
1078 buffer->offset = memoryOffset;
1079 } else {
1080 buffer->bo = NULL;
1081 buffer->offset = 0;
1082 }
1083
1084 return VK_SUCCESS;
1085 }
1086
1087 VkResult radv_BindImageMemory(
1088 VkDevice device,
1089 VkImage _image,
1090 VkDeviceMemory _memory,
1091 VkDeviceSize memoryOffset)
1092 {
1093 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
1094 RADV_FROM_HANDLE(radv_image, image, _image);
1095
1096 if (mem) {
1097 image->bo = mem->bo;
1098 image->offset = memoryOffset;
1099 } else {
1100 image->bo = NULL;
1101 image->offset = 0;
1102 }
1103
1104 return VK_SUCCESS;
1105 }
1106
1107 VkResult radv_QueueBindSparse(
1108 VkQueue queue,
1109 uint32_t bindInfoCount,
1110 const VkBindSparseInfo* pBindInfo,
1111 VkFence fence)
1112 {
1113 stub_return(VK_ERROR_INCOMPATIBLE_DRIVER);
1114 }
1115
1116 VkResult radv_CreateFence(
1117 VkDevice _device,
1118 const VkFenceCreateInfo* pCreateInfo,
1119 const VkAllocationCallbacks* pAllocator,
1120 VkFence* pFence)
1121 {
1122 RADV_FROM_HANDLE(radv_device, device, _device);
1123 struct radv_fence *fence = vk_alloc2(&device->alloc, pAllocator,
1124 sizeof(*fence), 8,
1125 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1126
1127 if (!fence)
1128 return VK_ERROR_OUT_OF_HOST_MEMORY;
1129
1130 memset(fence, 0, sizeof(*fence));
1131 fence->submitted = false;
1132 fence->signalled = !!(pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT);
1133 fence->fence = device->ws->create_fence();
1134 if (!fence->fence) {
1135 vk_free2(&device->alloc, pAllocator, fence);
1136 return VK_ERROR_OUT_OF_HOST_MEMORY;
1137 }
1138
1139 *pFence = radv_fence_to_handle(fence);
1140
1141 return VK_SUCCESS;
1142 }
1143
1144 void radv_DestroyFence(
1145 VkDevice _device,
1146 VkFence _fence,
1147 const VkAllocationCallbacks* pAllocator)
1148 {
1149 RADV_FROM_HANDLE(radv_device, device, _device);
1150 RADV_FROM_HANDLE(radv_fence, fence, _fence);
1151
1152 if (!fence)
1153 return;
1154 device->ws->destroy_fence(fence->fence);
1155 vk_free2(&device->alloc, pAllocator, fence);
1156 }
1157
1158 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
1159 {
1160 uint64_t current_time;
1161 struct timespec tv;
1162
1163 clock_gettime(CLOCK_MONOTONIC, &tv);
1164 current_time = tv.tv_nsec + tv.tv_sec*1000000000ull;
1165
1166 timeout = MIN2(UINT64_MAX - current_time, timeout);
1167
1168 return current_time + timeout;
1169 }
1170
1171 VkResult radv_WaitForFences(
1172 VkDevice _device,
1173 uint32_t fenceCount,
1174 const VkFence* pFences,
1175 VkBool32 waitAll,
1176 uint64_t timeout)
1177 {
1178 RADV_FROM_HANDLE(radv_device, device, _device);
1179 timeout = radv_get_absolute_timeout(timeout);
1180
1181 if (!waitAll && fenceCount > 1) {
1182 fprintf(stderr, "radv: WaitForFences without waitAll not implemented yet\n");
1183 }
1184
1185 for (uint32_t i = 0; i < fenceCount; ++i) {
1186 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
1187 bool expired = false;
1188
1189 if (fence->signalled)
1190 continue;
1191
1192 if (!fence->submitted)
1193 return VK_TIMEOUT;
1194
1195 expired = device->ws->fence_wait(device->ws, fence->fence, true, timeout);
1196 if (!expired)
1197 return VK_TIMEOUT;
1198
1199 fence->signalled = true;
1200 }
1201
1202 return VK_SUCCESS;
1203 }
1204
1205 VkResult radv_ResetFences(VkDevice device,
1206 uint32_t fenceCount,
1207 const VkFence *pFences)
1208 {
1209 for (unsigned i = 0; i < fenceCount; ++i) {
1210 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
1211 fence->submitted = fence->signalled = false;
1212 }
1213
1214 return VK_SUCCESS;
1215 }
1216
1217 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
1218 {
1219 RADV_FROM_HANDLE(radv_device, device, _device);
1220 RADV_FROM_HANDLE(radv_fence, fence, _fence);
1221
1222 if (fence->signalled)
1223 return VK_SUCCESS;
1224 if (!fence->submitted)
1225 return VK_NOT_READY;
1226
1227 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
1228 return VK_NOT_READY;
1229
1230 return VK_SUCCESS;
1231 }
1232
1233
1234 // Queue semaphore functions
1235
1236 VkResult radv_CreateSemaphore(
1237 VkDevice device,
1238 const VkSemaphoreCreateInfo* pCreateInfo,
1239 const VkAllocationCallbacks* pAllocator,
1240 VkSemaphore* pSemaphore)
1241 {
1242 /* The DRM execbuffer ioctl always execute in-oder, even between different
1243 * rings. As such, there's nothing to do for the user space semaphore.
1244 */
1245
1246 *pSemaphore = (VkSemaphore)1;
1247
1248 return VK_SUCCESS;
1249 }
1250
1251 void radv_DestroySemaphore(
1252 VkDevice device,
1253 VkSemaphore semaphore,
1254 const VkAllocationCallbacks* pAllocator)
1255 {
1256 }
1257
1258 VkResult radv_CreateEvent(
1259 VkDevice _device,
1260 const VkEventCreateInfo* pCreateInfo,
1261 const VkAllocationCallbacks* pAllocator,
1262 VkEvent* pEvent)
1263 {
1264 RADV_FROM_HANDLE(radv_device, device, _device);
1265 struct radv_event *event = vk_alloc2(&device->alloc, pAllocator,
1266 sizeof(*event), 8,
1267 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1268
1269 if (!event)
1270 return VK_ERROR_OUT_OF_HOST_MEMORY;
1271
1272 event->bo = device->ws->buffer_create(device->ws, 8, 8,
1273 RADEON_DOMAIN_GTT,
1274 RADEON_FLAG_CPU_ACCESS);
1275 if (!event->bo) {
1276 vk_free2(&device->alloc, pAllocator, event);
1277 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1278 }
1279
1280 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
1281
1282 *pEvent = radv_event_to_handle(event);
1283
1284 return VK_SUCCESS;
1285 }
1286
1287 void radv_DestroyEvent(
1288 VkDevice _device,
1289 VkEvent _event,
1290 const VkAllocationCallbacks* pAllocator)
1291 {
1292 RADV_FROM_HANDLE(radv_device, device, _device);
1293 RADV_FROM_HANDLE(radv_event, event, _event);
1294
1295 if (!event)
1296 return;
1297 device->ws->buffer_destroy(event->bo);
1298 vk_free2(&device->alloc, pAllocator, event);
1299 }
1300
1301 VkResult radv_GetEventStatus(
1302 VkDevice _device,
1303 VkEvent _event)
1304 {
1305 RADV_FROM_HANDLE(radv_event, event, _event);
1306
1307 if (*event->map == 1)
1308 return VK_EVENT_SET;
1309 return VK_EVENT_RESET;
1310 }
1311
1312 VkResult radv_SetEvent(
1313 VkDevice _device,
1314 VkEvent _event)
1315 {
1316 RADV_FROM_HANDLE(radv_event, event, _event);
1317 *event->map = 1;
1318
1319 return VK_SUCCESS;
1320 }
1321
1322 VkResult radv_ResetEvent(
1323 VkDevice _device,
1324 VkEvent _event)
1325 {
1326 RADV_FROM_HANDLE(radv_event, event, _event);
1327 *event->map = 0;
1328
1329 return VK_SUCCESS;
1330 }
1331
1332 VkResult radv_CreateBuffer(
1333 VkDevice _device,
1334 const VkBufferCreateInfo* pCreateInfo,
1335 const VkAllocationCallbacks* pAllocator,
1336 VkBuffer* pBuffer)
1337 {
1338 RADV_FROM_HANDLE(radv_device, device, _device);
1339 struct radv_buffer *buffer;
1340
1341 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
1342
1343 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
1344 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1345 if (buffer == NULL)
1346 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1347
1348 buffer->size = pCreateInfo->size;
1349 buffer->usage = pCreateInfo->usage;
1350 buffer->bo = NULL;
1351 buffer->offset = 0;
1352
1353 *pBuffer = radv_buffer_to_handle(buffer);
1354
1355 return VK_SUCCESS;
1356 }
1357
1358 void radv_DestroyBuffer(
1359 VkDevice _device,
1360 VkBuffer _buffer,
1361 const VkAllocationCallbacks* pAllocator)
1362 {
1363 RADV_FROM_HANDLE(radv_device, device, _device);
1364 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
1365
1366 if (!buffer)
1367 return;
1368
1369 vk_free2(&device->alloc, pAllocator, buffer);
1370 }
1371
1372 static inline unsigned
1373 si_tile_mode_index(const struct radv_image *image, unsigned level, bool stencil)
1374 {
1375 if (stencil)
1376 return image->surface.stencil_tiling_index[level];
1377 else
1378 return image->surface.tiling_index[level];
1379 }
1380
1381 static void
1382 radv_initialise_color_surface(struct radv_device *device,
1383 struct radv_color_buffer_info *cb,
1384 struct radv_image_view *iview)
1385 {
1386 const struct vk_format_description *desc;
1387 unsigned ntype, format, swap, endian;
1388 unsigned blend_clamp = 0, blend_bypass = 0;
1389 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
1390 uint64_t va;
1391 const struct radeon_surf *surf = &iview->image->surface;
1392 const struct radeon_surf_level *level_info = &surf->level[iview->base_mip];
1393
1394 desc = vk_format_description(iview->vk_format);
1395
1396 memset(cb, 0, sizeof(*cb));
1397
1398 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1399 va += level_info->offset;
1400 cb->cb_color_base = va >> 8;
1401
1402 /* CMASK variables */
1403 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1404 va += iview->image->cmask.offset;
1405 cb->cb_color_cmask = va >> 8;
1406 cb->cb_color_cmask_slice = iview->image->cmask.slice_tile_max;
1407
1408 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1409 va += iview->image->dcc_offset;
1410 cb->cb_dcc_base = va >> 8;
1411
1412 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
1413 S_028C6C_SLICE_MAX(iview->base_layer + iview->extent.depth - 1);
1414
1415 cb->micro_tile_mode = iview->image->surface.micro_tile_mode;
1416 pitch_tile_max = level_info->nblk_x / 8 - 1;
1417 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
1418 tile_mode_index = si_tile_mode_index(iview->image, iview->base_mip, false);
1419
1420 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
1421 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
1422
1423 /* Intensity is implemented as Red, so treat it that way. */
1424 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1) |
1425 S_028C74_TILE_MODE_INDEX(tile_mode_index);
1426
1427 if (iview->image->samples > 1) {
1428 unsigned log_samples = util_logbase2(iview->image->samples);
1429
1430 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
1431 S_028C74_NUM_FRAGMENTS(log_samples);
1432 }
1433
1434 if (iview->image->fmask.size) {
1435 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask.offset;
1436 if (device->instance->physicalDevice.rad_info.chip_class >= CIK)
1437 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(iview->image->fmask.pitch_in_pixels / 8 - 1);
1438 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(iview->image->fmask.tile_mode_index);
1439 cb->cb_color_fmask = va >> 8;
1440 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(iview->image->fmask.slice_tile_max);
1441 } else {
1442 /* This must be set for fast clear to work without FMASK. */
1443 if (device->instance->physicalDevice.rad_info.chip_class >= CIK)
1444 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
1445 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
1446 cb->cb_color_fmask = cb->cb_color_base;
1447 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
1448 }
1449
1450 ntype = radv_translate_color_numformat(iview->vk_format,
1451 desc,
1452 vk_format_get_first_non_void_channel(iview->vk_format));
1453 format = radv_translate_colorformat(iview->vk_format);
1454 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
1455 radv_finishme("Illegal color\n");
1456 swap = radv_translate_colorswap(iview->vk_format, FALSE);
1457 endian = radv_colorformat_endian_swap(format);
1458
1459 /* blend clamp should be set for all NORM/SRGB types */
1460 if (ntype == V_028C70_NUMBER_UNORM ||
1461 ntype == V_028C70_NUMBER_SNORM ||
1462 ntype == V_028C70_NUMBER_SRGB)
1463 blend_clamp = 1;
1464
1465 /* set blend bypass according to docs if SINT/UINT or
1466 8/24 COLOR variants */
1467 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
1468 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
1469 format == V_028C70_COLOR_X24_8_32_FLOAT) {
1470 blend_clamp = 0;
1471 blend_bypass = 1;
1472 }
1473 #if 0
1474 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
1475 (format == V_028C70_COLOR_8 ||
1476 format == V_028C70_COLOR_8_8 ||
1477 format == V_028C70_COLOR_8_8_8_8))
1478 ->color_is_int8 = true;
1479 #endif
1480 cb->cb_color_info = S_028C70_FORMAT(format) |
1481 S_028C70_COMP_SWAP(swap) |
1482 S_028C70_BLEND_CLAMP(blend_clamp) |
1483 S_028C70_BLEND_BYPASS(blend_bypass) |
1484 S_028C70_SIMPLE_FLOAT(1) |
1485 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
1486 ntype != V_028C70_NUMBER_SNORM &&
1487 ntype != V_028C70_NUMBER_SRGB &&
1488 format != V_028C70_COLOR_8_24 &&
1489 format != V_028C70_COLOR_24_8) |
1490 S_028C70_NUMBER_TYPE(ntype) |
1491 S_028C70_ENDIAN(endian);
1492 if (iview->image->samples > 1)
1493 if (iview->image->fmask.size)
1494 cb->cb_color_info |= S_028C70_COMPRESSION(1);
1495
1496 if (iview->image->cmask.size && device->allow_fast_clears)
1497 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
1498
1499 if (iview->image->surface.dcc_size && level_info->dcc_enabled)
1500 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
1501
1502 if (device->instance->physicalDevice.rad_info.chip_class >= VI) {
1503 unsigned max_uncompressed_block_size = 2;
1504 if (iview->image->samples > 1) {
1505 if (iview->image->surface.bpe == 1)
1506 max_uncompressed_block_size = 0;
1507 else if (iview->image->surface.bpe == 2)
1508 max_uncompressed_block_size = 1;
1509 }
1510
1511 cb->cb_dcc_control = S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
1512 S_028C78_INDEPENDENT_64B_BLOCKS(1);
1513 }
1514
1515 /* This must be set for fast clear to work without FMASK. */
1516 if (!iview->image->fmask.size &&
1517 device->instance->physicalDevice.rad_info.chip_class == SI) {
1518 unsigned bankh = util_logbase2(iview->image->surface.bankh);
1519 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
1520 }
1521 }
1522
1523 static void
1524 radv_initialise_ds_surface(struct radv_device *device,
1525 struct radv_ds_buffer_info *ds,
1526 struct radv_image_view *iview)
1527 {
1528 unsigned level = iview->base_mip;
1529 unsigned format;
1530 uint64_t va, s_offs, z_offs;
1531 const struct radeon_surf_level *level_info = &iview->image->surface.level[level];
1532 memset(ds, 0, sizeof(*ds));
1533 switch (iview->vk_format) {
1534 case VK_FORMAT_D24_UNORM_S8_UINT:
1535 case VK_FORMAT_X8_D24_UNORM_PACK32:
1536 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
1537 ds->offset_scale = 2.0f;
1538 break;
1539 case VK_FORMAT_D16_UNORM:
1540 case VK_FORMAT_D16_UNORM_S8_UINT:
1541 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
1542 ds->offset_scale = 4.0f;
1543 break;
1544 case VK_FORMAT_D32_SFLOAT:
1545 case VK_FORMAT_D32_SFLOAT_S8_UINT:
1546 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
1547 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
1548 ds->offset_scale = 1.0f;
1549 break;
1550 default:
1551 break;
1552 }
1553
1554 format = radv_translate_dbformat(iview->vk_format);
1555 if (format == V_028040_Z_INVALID) {
1556 fprintf(stderr, "Invalid DB format: %d, disabling DB.\n", iview->vk_format);
1557 }
1558
1559 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1560 s_offs = z_offs = va;
1561 z_offs += iview->image->surface.level[level].offset;
1562 s_offs += iview->image->surface.stencil_level[level].offset;
1563
1564 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
1565 S_028008_SLICE_MAX(iview->base_layer + iview->extent.depth - 1);
1566 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(1);
1567 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
1568
1569 if (iview->image->samples > 1)
1570 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->samples));
1571
1572 if (iview->image->surface.flags & RADEON_SURF_SBUFFER)
1573 ds->db_stencil_info = S_028044_FORMAT(V_028044_STENCIL_8);
1574 else
1575 ds->db_stencil_info = S_028044_FORMAT(V_028044_STENCIL_INVALID);
1576
1577 if (device->instance->physicalDevice.rad_info.chip_class >= CIK) {
1578 struct radeon_info *info = &device->instance->physicalDevice.rad_info;
1579 unsigned tiling_index = iview->image->surface.tiling_index[level];
1580 unsigned stencil_index = iview->image->surface.stencil_tiling_index[level];
1581 unsigned macro_index = iview->image->surface.macro_tile_index;
1582 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
1583 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
1584 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
1585
1586 ds->db_depth_info |=
1587 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
1588 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
1589 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
1590 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
1591 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
1592 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
1593 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
1594 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
1595 } else {
1596 unsigned tile_mode_index = si_tile_mode_index(iview->image, level, false);
1597 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
1598 tile_mode_index = si_tile_mode_index(iview->image, level, true);
1599 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
1600 }
1601
1602 if (iview->image->htile.size && !level) {
1603 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1) |
1604 S_028040_ALLOW_EXPCLEAR(1);
1605
1606 if (iview->image->surface.flags & RADEON_SURF_SBUFFER) {
1607 /* Workaround: For a not yet understood reason, the
1608 * combination of MSAA, fast stencil clear and stencil
1609 * decompress messes with subsequent stencil buffer
1610 * uses. Problem was reproduced on Verde, Bonaire,
1611 * Tonga, and Carrizo.
1612 *
1613 * Disabling EXPCLEAR works around the problem.
1614 *
1615 * Check piglit's arb_texture_multisample-stencil-clear
1616 * test if you want to try changing this.
1617 */
1618 if (iview->image->samples <= 1)
1619 ds->db_stencil_info |= S_028044_ALLOW_EXPCLEAR(1);
1620 } else
1621 /* Use all of the htile_buffer for depth if there's no stencil. */
1622 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
1623
1624 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset +
1625 iview->image->htile.offset;
1626 ds->db_htile_data_base = va >> 8;
1627 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
1628 } else {
1629 ds->db_htile_data_base = 0;
1630 ds->db_htile_surface = 0;
1631 }
1632
1633 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
1634 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
1635
1636 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
1637 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
1638 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
1639 }
1640
1641 VkResult radv_CreateFramebuffer(
1642 VkDevice _device,
1643 const VkFramebufferCreateInfo* pCreateInfo,
1644 const VkAllocationCallbacks* pAllocator,
1645 VkFramebuffer* pFramebuffer)
1646 {
1647 RADV_FROM_HANDLE(radv_device, device, _device);
1648 struct radv_framebuffer *framebuffer;
1649
1650 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
1651
1652 size_t size = sizeof(*framebuffer) +
1653 sizeof(struct radv_attachment_info) * pCreateInfo->attachmentCount;
1654 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
1655 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1656 if (framebuffer == NULL)
1657 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1658
1659 framebuffer->attachment_count = pCreateInfo->attachmentCount;
1660 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
1661 VkImageView _iview = pCreateInfo->pAttachments[i];
1662 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
1663 framebuffer->attachments[i].attachment = iview;
1664 if (iview->aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) {
1665 radv_initialise_color_surface(device, &framebuffer->attachments[i].cb, iview);
1666 } else if (iview->aspect_mask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1667 radv_initialise_ds_surface(device, &framebuffer->attachments[i].ds, iview);
1668 }
1669 }
1670
1671 framebuffer->width = pCreateInfo->width;
1672 framebuffer->height = pCreateInfo->height;
1673 framebuffer->layers = pCreateInfo->layers;
1674
1675 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
1676 return VK_SUCCESS;
1677 }
1678
1679 void radv_DestroyFramebuffer(
1680 VkDevice _device,
1681 VkFramebuffer _fb,
1682 const VkAllocationCallbacks* pAllocator)
1683 {
1684 RADV_FROM_HANDLE(radv_device, device, _device);
1685 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
1686
1687 if (!fb)
1688 return;
1689 vk_free2(&device->alloc, pAllocator, fb);
1690 }
1691
1692 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
1693 {
1694 switch (address_mode) {
1695 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
1696 return V_008F30_SQ_TEX_WRAP;
1697 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
1698 return V_008F30_SQ_TEX_MIRROR;
1699 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
1700 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
1701 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
1702 return V_008F30_SQ_TEX_CLAMP_BORDER;
1703 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
1704 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
1705 default:
1706 unreachable("illegal tex wrap mode");
1707 break;
1708 }
1709 }
1710
1711 static unsigned
1712 radv_tex_compare(VkCompareOp op)
1713 {
1714 switch (op) {
1715 case VK_COMPARE_OP_NEVER:
1716 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
1717 case VK_COMPARE_OP_LESS:
1718 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
1719 case VK_COMPARE_OP_EQUAL:
1720 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
1721 case VK_COMPARE_OP_LESS_OR_EQUAL:
1722 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
1723 case VK_COMPARE_OP_GREATER:
1724 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
1725 case VK_COMPARE_OP_NOT_EQUAL:
1726 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
1727 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1728 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
1729 case VK_COMPARE_OP_ALWAYS:
1730 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
1731 default:
1732 unreachable("illegal compare mode");
1733 break;
1734 }
1735 }
1736
1737 static unsigned
1738 radv_tex_filter(VkFilter filter, unsigned max_ansio)
1739 {
1740 switch (filter) {
1741 case VK_FILTER_NEAREST:
1742 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
1743 V_008F38_SQ_TEX_XY_FILTER_POINT);
1744 case VK_FILTER_LINEAR:
1745 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
1746 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
1747 case VK_FILTER_CUBIC_IMG:
1748 default:
1749 fprintf(stderr, "illegal texture filter");
1750 return 0;
1751 }
1752 }
1753
1754 static unsigned
1755 radv_tex_mipfilter(VkSamplerMipmapMode mode)
1756 {
1757 switch (mode) {
1758 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
1759 return V_008F38_SQ_TEX_Z_FILTER_POINT;
1760 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
1761 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
1762 default:
1763 return V_008F38_SQ_TEX_Z_FILTER_NONE;
1764 }
1765 }
1766
1767 static unsigned
1768 radv_tex_bordercolor(VkBorderColor bcolor)
1769 {
1770 switch (bcolor) {
1771 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
1772 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
1773 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
1774 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
1775 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
1776 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
1777 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
1778 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
1779 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
1780 default:
1781 break;
1782 }
1783 return 0;
1784 }
1785
1786 static unsigned
1787 radv_tex_aniso_filter(unsigned filter)
1788 {
1789 if (filter < 2)
1790 return 0;
1791 if (filter < 4)
1792 return 1;
1793 if (filter < 8)
1794 return 2;
1795 if (filter < 16)
1796 return 3;
1797 return 4;
1798 }
1799
1800 static void
1801 radv_init_sampler(struct radv_device *device,
1802 struct radv_sampler *sampler,
1803 const VkSamplerCreateInfo *pCreateInfo)
1804 {
1805 uint32_t max_aniso = pCreateInfo->anisotropyEnable && pCreateInfo->maxAnisotropy > 1.0 ?
1806 (uint32_t) pCreateInfo->maxAnisotropy : 0;
1807 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
1808 bool is_vi = (device->instance->physicalDevice.rad_info.chip_class >= VI);
1809
1810 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
1811 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
1812 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
1813 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
1814 S_008F30_DEPTH_COMPARE_FUNC(radv_tex_compare(pCreateInfo->compareOp)) |
1815 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
1816 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
1817 S_008F30_ANISO_BIAS(max_aniso_ratio) |
1818 S_008F30_DISABLE_CUBE_WRAP(0) |
1819 S_008F30_COMPAT_MODE(is_vi));
1820 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
1821 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
1822 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
1823 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
1824 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
1825 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
1826 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
1827 S_008F38_MIP_POINT_PRECLAMP(1) |
1828 S_008F38_DISABLE_LSB_CEIL(1) |
1829 S_008F38_FILTER_PREC_FIX(1) |
1830 S_008F38_ANISO_OVERRIDE(is_vi));
1831 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(0) |
1832 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(pCreateInfo->borderColor)));
1833 }
1834
1835 VkResult radv_CreateSampler(
1836 VkDevice _device,
1837 const VkSamplerCreateInfo* pCreateInfo,
1838 const VkAllocationCallbacks* pAllocator,
1839 VkSampler* pSampler)
1840 {
1841 RADV_FROM_HANDLE(radv_device, device, _device);
1842 struct radv_sampler *sampler;
1843
1844 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
1845
1846 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
1847 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1848 if (!sampler)
1849 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1850
1851 radv_init_sampler(device, sampler, pCreateInfo);
1852 *pSampler = radv_sampler_to_handle(sampler);
1853
1854 return VK_SUCCESS;
1855 }
1856
1857 void radv_DestroySampler(
1858 VkDevice _device,
1859 VkSampler _sampler,
1860 const VkAllocationCallbacks* pAllocator)
1861 {
1862 RADV_FROM_HANDLE(radv_device, device, _device);
1863 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
1864
1865 if (!sampler)
1866 return;
1867 vk_free2(&device->alloc, pAllocator, sampler);
1868 }