fd0ef720d8b2172722d5b46f1c9b8eae1161f7d4
[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 int queue_family_index, int idx)
624 {
625 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
626 queue->device = device;
627 queue->queue_family_index = queue_family_index;
628 queue->queue_idx = idx;
629 }
630
631 static void
632 radv_queue_finish(struct radv_queue *queue)
633 {
634 }
635
636 VkResult radv_CreateDevice(
637 VkPhysicalDevice physicalDevice,
638 const VkDeviceCreateInfo* pCreateInfo,
639 const VkAllocationCallbacks* pAllocator,
640 VkDevice* pDevice)
641 {
642 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
643 VkResult result;
644 struct radv_device *device;
645
646 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
647 bool found = false;
648 for (uint32_t j = 0; j < ARRAY_SIZE(device_extensions); j++) {
649 if (strcmp(pCreateInfo->ppEnabledExtensionNames[i],
650 device_extensions[j].extensionName) == 0) {
651 found = true;
652 break;
653 }
654 }
655 if (!found)
656 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
657 }
658
659 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
660 sizeof(*device), 8,
661 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
662 if (!device)
663 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
664
665 memset(device, 0, sizeof(*device));
666
667 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
668 device->instance = physical_device->instance;
669 device->shader_stats_dump = false;
670
671 device->ws = physical_device->ws;
672 if (pAllocator)
673 device->alloc = *pAllocator;
674 else
675 device->alloc = physical_device->instance->alloc;
676
677 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
678 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
679 uint32_t qfi = queue_create->queueFamilyIndex;
680
681 device->queues[qfi] = vk_alloc(&device->alloc,
682 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
683 if (!device->queues[qfi]) {
684 result = VK_ERROR_OUT_OF_HOST_MEMORY;
685 goto fail;
686 }
687
688 device->queue_count[qfi] = queue_create->queueCount;
689
690 for (unsigned q = 0; q < queue_create->queueCount; q++)
691 radv_queue_init(device, &device->queues[qfi][q], qfi, q);
692 }
693
694 device->hw_ctx = device->ws->ctx_create(device->ws);
695 if (!device->hw_ctx) {
696 result = VK_ERROR_OUT_OF_HOST_MEMORY;
697 goto fail;
698 }
699
700 result = radv_device_init_meta(device);
701 if (result != VK_SUCCESS) {
702 device->ws->ctx_destroy(device->hw_ctx);
703 goto fail;
704 }
705 device->allow_fast_clears = env_var_as_boolean("RADV_FAST_CLEARS", false);
706 device->allow_dcc = !env_var_as_boolean("RADV_DCC_DISABLE", false);
707 device->shader_stats_dump = env_var_as_boolean("RADV_SHADER_STATS", false);
708
709 if (device->allow_fast_clears && device->allow_dcc)
710 radv_finishme("DCC fast clears have not been tested\n");
711
712 radv_device_init_msaa(device);
713 device->empty_cs = device->ws->cs_create(device->ws, RING_GFX);
714 radeon_emit(device->empty_cs, PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
715 radeon_emit(device->empty_cs, CONTEXT_CONTROL_LOAD_ENABLE(1));
716 radeon_emit(device->empty_cs, CONTEXT_CONTROL_SHADOW_ENABLE(1));
717 device->ws->cs_finalize(device->empty_cs);
718 *pDevice = radv_device_to_handle(device);
719 return VK_SUCCESS;
720
721 fail:
722 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
723 for (unsigned q = 0; q < device->queue_count[i]; q++)
724 radv_queue_finish(&device->queues[i][q]);
725 if (device->queue_count[i])
726 vk_free(&device->alloc, device->queues[i]);
727 }
728 vk_free(&device->alloc, device);
729 return result;
730 }
731
732 void radv_DestroyDevice(
733 VkDevice _device,
734 const VkAllocationCallbacks* pAllocator)
735 {
736 RADV_FROM_HANDLE(radv_device, device, _device);
737
738 device->ws->ctx_destroy(device->hw_ctx);
739 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
740 for (unsigned q = 0; q < device->queue_count[i]; q++)
741 radv_queue_finish(&device->queues[i][q]);
742 if (device->queue_count[i])
743 vk_free(&device->alloc, device->queues[i]);
744 }
745 radv_device_finish_meta(device);
746
747 vk_free(&device->alloc, device);
748 }
749
750 VkResult radv_EnumerateInstanceExtensionProperties(
751 const char* pLayerName,
752 uint32_t* pPropertyCount,
753 VkExtensionProperties* pProperties)
754 {
755 if (pProperties == NULL) {
756 *pPropertyCount = ARRAY_SIZE(global_extensions);
757 return VK_SUCCESS;
758 }
759
760 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(global_extensions));
761 typed_memcpy(pProperties, global_extensions, *pPropertyCount);
762
763 if (*pPropertyCount < ARRAY_SIZE(global_extensions))
764 return VK_INCOMPLETE;
765
766 return VK_SUCCESS;
767 }
768
769 VkResult radv_EnumerateDeviceExtensionProperties(
770 VkPhysicalDevice physicalDevice,
771 const char* pLayerName,
772 uint32_t* pPropertyCount,
773 VkExtensionProperties* pProperties)
774 {
775 if (pProperties == NULL) {
776 *pPropertyCount = ARRAY_SIZE(device_extensions);
777 return VK_SUCCESS;
778 }
779
780 *pPropertyCount = MIN2(*pPropertyCount, ARRAY_SIZE(device_extensions));
781 typed_memcpy(pProperties, device_extensions, *pPropertyCount);
782
783 if (*pPropertyCount < ARRAY_SIZE(device_extensions))
784 return VK_INCOMPLETE;
785
786 return VK_SUCCESS;
787 }
788
789 VkResult radv_EnumerateInstanceLayerProperties(
790 uint32_t* pPropertyCount,
791 VkLayerProperties* pProperties)
792 {
793 if (pProperties == NULL) {
794 *pPropertyCount = 0;
795 return VK_SUCCESS;
796 }
797
798 /* None supported at this time */
799 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
800 }
801
802 VkResult radv_EnumerateDeviceLayerProperties(
803 VkPhysicalDevice physicalDevice,
804 uint32_t* pPropertyCount,
805 VkLayerProperties* pProperties)
806 {
807 if (pProperties == NULL) {
808 *pPropertyCount = 0;
809 return VK_SUCCESS;
810 }
811
812 /* None supported at this time */
813 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
814 }
815
816 void radv_GetDeviceQueue(
817 VkDevice _device,
818 uint32_t queueFamilyIndex,
819 uint32_t queueIndex,
820 VkQueue* pQueue)
821 {
822 RADV_FROM_HANDLE(radv_device, device, _device);
823
824 *pQueue = radv_queue_to_handle(&device->queues[queueFamilyIndex][queueIndex]);
825 }
826
827 VkResult radv_QueueSubmit(
828 VkQueue _queue,
829 uint32_t submitCount,
830 const VkSubmitInfo* pSubmits,
831 VkFence _fence)
832 {
833 RADV_FROM_HANDLE(radv_queue, queue, _queue);
834 RADV_FROM_HANDLE(radv_fence, fence, _fence);
835 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
836 struct radeon_winsys_ctx *ctx = queue->device->hw_ctx;
837 int ret;
838
839 for (uint32_t i = 0; i < submitCount; i++) {
840 struct radeon_winsys_cs **cs_array;
841 bool can_patch = true;
842
843 if (!pSubmits[i].commandBufferCount)
844 continue;
845
846 cs_array = malloc(sizeof(struct radeon_winsys_cs *) *
847 pSubmits[i].commandBufferCount);
848
849 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
850 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
851 pSubmits[i].pCommandBuffers[j]);
852 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
853
854 cs_array[j] = cmd_buffer->cs;
855 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
856 can_patch = false;
857 }
858 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array,
859 pSubmits[i].commandBufferCount,
860 can_patch, base_fence);
861 if (ret)
862 radv_loge("failed to submit CS %d\n", i);
863 free(cs_array);
864 }
865
866 if (fence) {
867 if (!submitCount)
868 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, &queue->device->empty_cs,
869 1, false, base_fence);
870
871 fence->submitted = true;
872 }
873
874 return VK_SUCCESS;
875 }
876
877 VkResult radv_QueueWaitIdle(
878 VkQueue _queue)
879 {
880 RADV_FROM_HANDLE(radv_queue, queue, _queue);
881
882 queue->device->ws->ctx_wait_idle(queue->device->hw_ctx,
883 radv_queue_family_to_ring(queue->queue_family_index),
884 queue->queue_idx);
885 return VK_SUCCESS;
886 }
887
888 VkResult radv_DeviceWaitIdle(
889 VkDevice _device)
890 {
891 RADV_FROM_HANDLE(radv_device, device, _device);
892
893 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
894 for (unsigned q = 0; q < device->queue_count[i]; q++) {
895 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
896 }
897 }
898 return VK_SUCCESS;
899 }
900
901 PFN_vkVoidFunction radv_GetInstanceProcAddr(
902 VkInstance instance,
903 const char* pName)
904 {
905 return radv_lookup_entrypoint(pName);
906 }
907
908 /* The loader wants us to expose a second GetInstanceProcAddr function
909 * to work around certain LD_PRELOAD issues seen in apps.
910 */
911 PUBLIC
912 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
913 VkInstance instance,
914 const char* pName);
915
916 PUBLIC
917 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
918 VkInstance instance,
919 const char* pName)
920 {
921 return radv_GetInstanceProcAddr(instance, pName);
922 }
923
924 PFN_vkVoidFunction radv_GetDeviceProcAddr(
925 VkDevice device,
926 const char* pName)
927 {
928 return radv_lookup_entrypoint(pName);
929 }
930
931 VkResult radv_AllocateMemory(
932 VkDevice _device,
933 const VkMemoryAllocateInfo* pAllocateInfo,
934 const VkAllocationCallbacks* pAllocator,
935 VkDeviceMemory* pMem)
936 {
937 RADV_FROM_HANDLE(radv_device, device, _device);
938 struct radv_device_memory *mem;
939 VkResult result;
940 enum radeon_bo_domain domain;
941 uint32_t flags = 0;
942 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
943
944 if (pAllocateInfo->allocationSize == 0) {
945 /* Apparently, this is allowed */
946 *pMem = VK_NULL_HANDLE;
947 return VK_SUCCESS;
948 }
949
950 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
951 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
952 if (mem == NULL)
953 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
954
955 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
956 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_WRITE_COMBINE ||
957 pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_CACHED)
958 domain = RADEON_DOMAIN_GTT;
959 else
960 domain = RADEON_DOMAIN_VRAM;
961
962 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_VRAM)
963 flags |= RADEON_FLAG_NO_CPU_ACCESS;
964 else
965 flags |= RADEON_FLAG_CPU_ACCESS;
966
967 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_WRITE_COMBINE)
968 flags |= RADEON_FLAG_GTT_WC;
969
970 mem->bo = device->ws->buffer_create(device->ws, alloc_size, 32768,
971 domain, flags);
972
973 if (!mem->bo) {
974 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
975 goto fail;
976 }
977 mem->type_index = pAllocateInfo->memoryTypeIndex;
978
979 *pMem = radv_device_memory_to_handle(mem);
980
981 return VK_SUCCESS;
982
983 fail:
984 vk_free2(&device->alloc, pAllocator, mem);
985
986 return result;
987 }
988
989 void radv_FreeMemory(
990 VkDevice _device,
991 VkDeviceMemory _mem,
992 const VkAllocationCallbacks* pAllocator)
993 {
994 RADV_FROM_HANDLE(radv_device, device, _device);
995 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
996
997 if (mem == NULL)
998 return;
999
1000 device->ws->buffer_destroy(mem->bo);
1001 mem->bo = NULL;
1002
1003 vk_free2(&device->alloc, pAllocator, mem);
1004 }
1005
1006 VkResult radv_MapMemory(
1007 VkDevice _device,
1008 VkDeviceMemory _memory,
1009 VkDeviceSize offset,
1010 VkDeviceSize size,
1011 VkMemoryMapFlags flags,
1012 void** ppData)
1013 {
1014 RADV_FROM_HANDLE(radv_device, device, _device);
1015 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
1016
1017 if (mem == NULL) {
1018 *ppData = NULL;
1019 return VK_SUCCESS;
1020 }
1021
1022 *ppData = device->ws->buffer_map(mem->bo);
1023 if (*ppData) {
1024 *ppData += offset;
1025 return VK_SUCCESS;
1026 }
1027
1028 return VK_ERROR_MEMORY_MAP_FAILED;
1029 }
1030
1031 void radv_UnmapMemory(
1032 VkDevice _device,
1033 VkDeviceMemory _memory)
1034 {
1035 RADV_FROM_HANDLE(radv_device, device, _device);
1036 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
1037
1038 if (mem == NULL)
1039 return;
1040
1041 device->ws->buffer_unmap(mem->bo);
1042 }
1043
1044 VkResult radv_FlushMappedMemoryRanges(
1045 VkDevice _device,
1046 uint32_t memoryRangeCount,
1047 const VkMappedMemoryRange* pMemoryRanges)
1048 {
1049 return VK_SUCCESS;
1050 }
1051
1052 VkResult radv_InvalidateMappedMemoryRanges(
1053 VkDevice _device,
1054 uint32_t memoryRangeCount,
1055 const VkMappedMemoryRange* pMemoryRanges)
1056 {
1057 return VK_SUCCESS;
1058 }
1059
1060 void radv_GetBufferMemoryRequirements(
1061 VkDevice device,
1062 VkBuffer _buffer,
1063 VkMemoryRequirements* pMemoryRequirements)
1064 {
1065 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
1066
1067 pMemoryRequirements->memoryTypeBits = (1u << RADV_MEM_TYPE_COUNT) - 1;
1068
1069 pMemoryRequirements->size = buffer->size;
1070 pMemoryRequirements->alignment = 16;
1071 }
1072
1073 void radv_GetImageMemoryRequirements(
1074 VkDevice device,
1075 VkImage _image,
1076 VkMemoryRequirements* pMemoryRequirements)
1077 {
1078 RADV_FROM_HANDLE(radv_image, image, _image);
1079
1080 pMemoryRequirements->memoryTypeBits = (1u << RADV_MEM_TYPE_COUNT) - 1;
1081
1082 pMemoryRequirements->size = image->size;
1083 pMemoryRequirements->alignment = image->alignment;
1084 }
1085
1086 void radv_GetImageSparseMemoryRequirements(
1087 VkDevice device,
1088 VkImage image,
1089 uint32_t* pSparseMemoryRequirementCount,
1090 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
1091 {
1092 stub();
1093 }
1094
1095 void radv_GetDeviceMemoryCommitment(
1096 VkDevice device,
1097 VkDeviceMemory memory,
1098 VkDeviceSize* pCommittedMemoryInBytes)
1099 {
1100 *pCommittedMemoryInBytes = 0;
1101 }
1102
1103 VkResult radv_BindBufferMemory(
1104 VkDevice device,
1105 VkBuffer _buffer,
1106 VkDeviceMemory _memory,
1107 VkDeviceSize memoryOffset)
1108 {
1109 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
1110 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
1111
1112 if (mem) {
1113 buffer->bo = mem->bo;
1114 buffer->offset = memoryOffset;
1115 } else {
1116 buffer->bo = NULL;
1117 buffer->offset = 0;
1118 }
1119
1120 return VK_SUCCESS;
1121 }
1122
1123 VkResult radv_BindImageMemory(
1124 VkDevice device,
1125 VkImage _image,
1126 VkDeviceMemory _memory,
1127 VkDeviceSize memoryOffset)
1128 {
1129 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
1130 RADV_FROM_HANDLE(radv_image, image, _image);
1131
1132 if (mem) {
1133 image->bo = mem->bo;
1134 image->offset = memoryOffset;
1135 } else {
1136 image->bo = NULL;
1137 image->offset = 0;
1138 }
1139
1140 return VK_SUCCESS;
1141 }
1142
1143 VkResult radv_QueueBindSparse(
1144 VkQueue queue,
1145 uint32_t bindInfoCount,
1146 const VkBindSparseInfo* pBindInfo,
1147 VkFence fence)
1148 {
1149 stub_return(VK_ERROR_INCOMPATIBLE_DRIVER);
1150 }
1151
1152 VkResult radv_CreateFence(
1153 VkDevice _device,
1154 const VkFenceCreateInfo* pCreateInfo,
1155 const VkAllocationCallbacks* pAllocator,
1156 VkFence* pFence)
1157 {
1158 RADV_FROM_HANDLE(radv_device, device, _device);
1159 struct radv_fence *fence = vk_alloc2(&device->alloc, pAllocator,
1160 sizeof(*fence), 8,
1161 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1162
1163 if (!fence)
1164 return VK_ERROR_OUT_OF_HOST_MEMORY;
1165
1166 memset(fence, 0, sizeof(*fence));
1167 fence->submitted = false;
1168 fence->signalled = !!(pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT);
1169 fence->fence = device->ws->create_fence();
1170 if (!fence->fence) {
1171 vk_free2(&device->alloc, pAllocator, fence);
1172 return VK_ERROR_OUT_OF_HOST_MEMORY;
1173 }
1174
1175 *pFence = radv_fence_to_handle(fence);
1176
1177 return VK_SUCCESS;
1178 }
1179
1180 void radv_DestroyFence(
1181 VkDevice _device,
1182 VkFence _fence,
1183 const VkAllocationCallbacks* pAllocator)
1184 {
1185 RADV_FROM_HANDLE(radv_device, device, _device);
1186 RADV_FROM_HANDLE(radv_fence, fence, _fence);
1187
1188 if (!fence)
1189 return;
1190 device->ws->destroy_fence(fence->fence);
1191 vk_free2(&device->alloc, pAllocator, fence);
1192 }
1193
1194 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
1195 {
1196 uint64_t current_time;
1197 struct timespec tv;
1198
1199 clock_gettime(CLOCK_MONOTONIC, &tv);
1200 current_time = tv.tv_nsec + tv.tv_sec*1000000000ull;
1201
1202 timeout = MIN2(UINT64_MAX - current_time, timeout);
1203
1204 return current_time + timeout;
1205 }
1206
1207 VkResult radv_WaitForFences(
1208 VkDevice _device,
1209 uint32_t fenceCount,
1210 const VkFence* pFences,
1211 VkBool32 waitAll,
1212 uint64_t timeout)
1213 {
1214 RADV_FROM_HANDLE(radv_device, device, _device);
1215 timeout = radv_get_absolute_timeout(timeout);
1216
1217 if (!waitAll && fenceCount > 1) {
1218 fprintf(stderr, "radv: WaitForFences without waitAll not implemented yet\n");
1219 }
1220
1221 for (uint32_t i = 0; i < fenceCount; ++i) {
1222 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
1223 bool expired = false;
1224
1225 if (fence->signalled)
1226 continue;
1227
1228 if (!fence->submitted)
1229 return VK_TIMEOUT;
1230
1231 expired = device->ws->fence_wait(device->ws, fence->fence, true, timeout);
1232 if (!expired)
1233 return VK_TIMEOUT;
1234
1235 fence->signalled = true;
1236 }
1237
1238 return VK_SUCCESS;
1239 }
1240
1241 VkResult radv_ResetFences(VkDevice device,
1242 uint32_t fenceCount,
1243 const VkFence *pFences)
1244 {
1245 for (unsigned i = 0; i < fenceCount; ++i) {
1246 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
1247 fence->submitted = fence->signalled = false;
1248 }
1249
1250 return VK_SUCCESS;
1251 }
1252
1253 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
1254 {
1255 RADV_FROM_HANDLE(radv_device, device, _device);
1256 RADV_FROM_HANDLE(radv_fence, fence, _fence);
1257
1258 if (fence->signalled)
1259 return VK_SUCCESS;
1260 if (!fence->submitted)
1261 return VK_NOT_READY;
1262
1263 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
1264 return VK_NOT_READY;
1265
1266 return VK_SUCCESS;
1267 }
1268
1269
1270 // Queue semaphore functions
1271
1272 VkResult radv_CreateSemaphore(
1273 VkDevice device,
1274 const VkSemaphoreCreateInfo* pCreateInfo,
1275 const VkAllocationCallbacks* pAllocator,
1276 VkSemaphore* pSemaphore)
1277 {
1278 /* The DRM execbuffer ioctl always execute in-oder, even between different
1279 * rings. As such, there's nothing to do for the user space semaphore.
1280 */
1281
1282 *pSemaphore = (VkSemaphore)1;
1283
1284 return VK_SUCCESS;
1285 }
1286
1287 void radv_DestroySemaphore(
1288 VkDevice device,
1289 VkSemaphore semaphore,
1290 const VkAllocationCallbacks* pAllocator)
1291 {
1292 }
1293
1294 VkResult radv_CreateEvent(
1295 VkDevice _device,
1296 const VkEventCreateInfo* pCreateInfo,
1297 const VkAllocationCallbacks* pAllocator,
1298 VkEvent* pEvent)
1299 {
1300 RADV_FROM_HANDLE(radv_device, device, _device);
1301 struct radv_event *event = vk_alloc2(&device->alloc, pAllocator,
1302 sizeof(*event), 8,
1303 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1304
1305 if (!event)
1306 return VK_ERROR_OUT_OF_HOST_MEMORY;
1307
1308 event->bo = device->ws->buffer_create(device->ws, 8, 8,
1309 RADEON_DOMAIN_GTT,
1310 RADEON_FLAG_CPU_ACCESS);
1311 if (!event->bo) {
1312 vk_free2(&device->alloc, pAllocator, event);
1313 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1314 }
1315
1316 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
1317
1318 *pEvent = radv_event_to_handle(event);
1319
1320 return VK_SUCCESS;
1321 }
1322
1323 void radv_DestroyEvent(
1324 VkDevice _device,
1325 VkEvent _event,
1326 const VkAllocationCallbacks* pAllocator)
1327 {
1328 RADV_FROM_HANDLE(radv_device, device, _device);
1329 RADV_FROM_HANDLE(radv_event, event, _event);
1330
1331 if (!event)
1332 return;
1333 device->ws->buffer_destroy(event->bo);
1334 vk_free2(&device->alloc, pAllocator, event);
1335 }
1336
1337 VkResult radv_GetEventStatus(
1338 VkDevice _device,
1339 VkEvent _event)
1340 {
1341 RADV_FROM_HANDLE(radv_event, event, _event);
1342
1343 if (*event->map == 1)
1344 return VK_EVENT_SET;
1345 return VK_EVENT_RESET;
1346 }
1347
1348 VkResult radv_SetEvent(
1349 VkDevice _device,
1350 VkEvent _event)
1351 {
1352 RADV_FROM_HANDLE(radv_event, event, _event);
1353 *event->map = 1;
1354
1355 return VK_SUCCESS;
1356 }
1357
1358 VkResult radv_ResetEvent(
1359 VkDevice _device,
1360 VkEvent _event)
1361 {
1362 RADV_FROM_HANDLE(radv_event, event, _event);
1363 *event->map = 0;
1364
1365 return VK_SUCCESS;
1366 }
1367
1368 VkResult radv_CreateBuffer(
1369 VkDevice _device,
1370 const VkBufferCreateInfo* pCreateInfo,
1371 const VkAllocationCallbacks* pAllocator,
1372 VkBuffer* pBuffer)
1373 {
1374 RADV_FROM_HANDLE(radv_device, device, _device);
1375 struct radv_buffer *buffer;
1376
1377 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
1378
1379 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
1380 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1381 if (buffer == NULL)
1382 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1383
1384 buffer->size = pCreateInfo->size;
1385 buffer->usage = pCreateInfo->usage;
1386 buffer->bo = NULL;
1387 buffer->offset = 0;
1388
1389 *pBuffer = radv_buffer_to_handle(buffer);
1390
1391 return VK_SUCCESS;
1392 }
1393
1394 void radv_DestroyBuffer(
1395 VkDevice _device,
1396 VkBuffer _buffer,
1397 const VkAllocationCallbacks* pAllocator)
1398 {
1399 RADV_FROM_HANDLE(radv_device, device, _device);
1400 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
1401
1402 if (!buffer)
1403 return;
1404
1405 vk_free2(&device->alloc, pAllocator, buffer);
1406 }
1407
1408 static inline unsigned
1409 si_tile_mode_index(const struct radv_image *image, unsigned level, bool stencil)
1410 {
1411 if (stencil)
1412 return image->surface.stencil_tiling_index[level];
1413 else
1414 return image->surface.tiling_index[level];
1415 }
1416
1417 static void
1418 radv_initialise_color_surface(struct radv_device *device,
1419 struct radv_color_buffer_info *cb,
1420 struct radv_image_view *iview)
1421 {
1422 const struct vk_format_description *desc;
1423 unsigned ntype, format, swap, endian;
1424 unsigned blend_clamp = 0, blend_bypass = 0;
1425 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
1426 uint64_t va;
1427 const struct radeon_surf *surf = &iview->image->surface;
1428 const struct radeon_surf_level *level_info = &surf->level[iview->base_mip];
1429
1430 desc = vk_format_description(iview->vk_format);
1431
1432 memset(cb, 0, sizeof(*cb));
1433
1434 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1435 va += level_info->offset;
1436 cb->cb_color_base = va >> 8;
1437
1438 /* CMASK variables */
1439 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1440 va += iview->image->cmask.offset;
1441 cb->cb_color_cmask = va >> 8;
1442 cb->cb_color_cmask_slice = iview->image->cmask.slice_tile_max;
1443
1444 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1445 va += iview->image->dcc_offset;
1446 cb->cb_dcc_base = va >> 8;
1447
1448 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
1449 S_028C6C_SLICE_MAX(iview->base_layer + iview->extent.depth - 1);
1450
1451 cb->micro_tile_mode = iview->image->surface.micro_tile_mode;
1452 pitch_tile_max = level_info->nblk_x / 8 - 1;
1453 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
1454 tile_mode_index = si_tile_mode_index(iview->image, iview->base_mip, false);
1455
1456 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
1457 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
1458
1459 /* Intensity is implemented as Red, so treat it that way. */
1460 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1) |
1461 S_028C74_TILE_MODE_INDEX(tile_mode_index);
1462
1463 if (iview->image->samples > 1) {
1464 unsigned log_samples = util_logbase2(iview->image->samples);
1465
1466 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
1467 S_028C74_NUM_FRAGMENTS(log_samples);
1468 }
1469
1470 if (iview->image->fmask.size) {
1471 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask.offset;
1472 if (device->instance->physicalDevice.rad_info.chip_class >= CIK)
1473 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(iview->image->fmask.pitch_in_pixels / 8 - 1);
1474 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(iview->image->fmask.tile_mode_index);
1475 cb->cb_color_fmask = va >> 8;
1476 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(iview->image->fmask.slice_tile_max);
1477 } else {
1478 /* This must be set for fast clear to work without FMASK. */
1479 if (device->instance->physicalDevice.rad_info.chip_class >= CIK)
1480 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
1481 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
1482 cb->cb_color_fmask = cb->cb_color_base;
1483 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
1484 }
1485
1486 ntype = radv_translate_color_numformat(iview->vk_format,
1487 desc,
1488 vk_format_get_first_non_void_channel(iview->vk_format));
1489 format = radv_translate_colorformat(iview->vk_format);
1490 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
1491 radv_finishme("Illegal color\n");
1492 swap = radv_translate_colorswap(iview->vk_format, FALSE);
1493 endian = radv_colorformat_endian_swap(format);
1494
1495 /* blend clamp should be set for all NORM/SRGB types */
1496 if (ntype == V_028C70_NUMBER_UNORM ||
1497 ntype == V_028C70_NUMBER_SNORM ||
1498 ntype == V_028C70_NUMBER_SRGB)
1499 blend_clamp = 1;
1500
1501 /* set blend bypass according to docs if SINT/UINT or
1502 8/24 COLOR variants */
1503 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
1504 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
1505 format == V_028C70_COLOR_X24_8_32_FLOAT) {
1506 blend_clamp = 0;
1507 blend_bypass = 1;
1508 }
1509 #if 0
1510 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
1511 (format == V_028C70_COLOR_8 ||
1512 format == V_028C70_COLOR_8_8 ||
1513 format == V_028C70_COLOR_8_8_8_8))
1514 ->color_is_int8 = true;
1515 #endif
1516 cb->cb_color_info = S_028C70_FORMAT(format) |
1517 S_028C70_COMP_SWAP(swap) |
1518 S_028C70_BLEND_CLAMP(blend_clamp) |
1519 S_028C70_BLEND_BYPASS(blend_bypass) |
1520 S_028C70_SIMPLE_FLOAT(1) |
1521 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
1522 ntype != V_028C70_NUMBER_SNORM &&
1523 ntype != V_028C70_NUMBER_SRGB &&
1524 format != V_028C70_COLOR_8_24 &&
1525 format != V_028C70_COLOR_24_8) |
1526 S_028C70_NUMBER_TYPE(ntype) |
1527 S_028C70_ENDIAN(endian);
1528 if (iview->image->samples > 1)
1529 if (iview->image->fmask.size)
1530 cb->cb_color_info |= S_028C70_COMPRESSION(1);
1531
1532 if (iview->image->cmask.size && device->allow_fast_clears)
1533 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
1534
1535 if (iview->image->surface.dcc_size && level_info->dcc_enabled)
1536 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
1537
1538 if (device->instance->physicalDevice.rad_info.chip_class >= VI) {
1539 unsigned max_uncompressed_block_size = 2;
1540 if (iview->image->samples > 1) {
1541 if (iview->image->surface.bpe == 1)
1542 max_uncompressed_block_size = 0;
1543 else if (iview->image->surface.bpe == 2)
1544 max_uncompressed_block_size = 1;
1545 }
1546
1547 cb->cb_dcc_control = S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
1548 S_028C78_INDEPENDENT_64B_BLOCKS(1);
1549 }
1550
1551 /* This must be set for fast clear to work without FMASK. */
1552 if (!iview->image->fmask.size &&
1553 device->instance->physicalDevice.rad_info.chip_class == SI) {
1554 unsigned bankh = util_logbase2(iview->image->surface.bankh);
1555 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
1556 }
1557 }
1558
1559 static void
1560 radv_initialise_ds_surface(struct radv_device *device,
1561 struct radv_ds_buffer_info *ds,
1562 struct radv_image_view *iview)
1563 {
1564 unsigned level = iview->base_mip;
1565 unsigned format;
1566 uint64_t va, s_offs, z_offs;
1567 const struct radeon_surf_level *level_info = &iview->image->surface.level[level];
1568 memset(ds, 0, sizeof(*ds));
1569 switch (iview->vk_format) {
1570 case VK_FORMAT_D24_UNORM_S8_UINT:
1571 case VK_FORMAT_X8_D24_UNORM_PACK32:
1572 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
1573 ds->offset_scale = 2.0f;
1574 break;
1575 case VK_FORMAT_D16_UNORM:
1576 case VK_FORMAT_D16_UNORM_S8_UINT:
1577 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
1578 ds->offset_scale = 4.0f;
1579 break;
1580 case VK_FORMAT_D32_SFLOAT:
1581 case VK_FORMAT_D32_SFLOAT_S8_UINT:
1582 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
1583 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
1584 ds->offset_scale = 1.0f;
1585 break;
1586 default:
1587 break;
1588 }
1589
1590 format = radv_translate_dbformat(iview->vk_format);
1591 if (format == V_028040_Z_INVALID) {
1592 fprintf(stderr, "Invalid DB format: %d, disabling DB.\n", iview->vk_format);
1593 }
1594
1595 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset;
1596 s_offs = z_offs = va;
1597 z_offs += iview->image->surface.level[level].offset;
1598 s_offs += iview->image->surface.stencil_level[level].offset;
1599
1600 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
1601 S_028008_SLICE_MAX(iview->base_layer + iview->extent.depth - 1);
1602 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(1);
1603 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
1604
1605 if (iview->image->samples > 1)
1606 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->samples));
1607
1608 if (iview->image->surface.flags & RADEON_SURF_SBUFFER)
1609 ds->db_stencil_info = S_028044_FORMAT(V_028044_STENCIL_8);
1610 else
1611 ds->db_stencil_info = S_028044_FORMAT(V_028044_STENCIL_INVALID);
1612
1613 if (device->instance->physicalDevice.rad_info.chip_class >= CIK) {
1614 struct radeon_info *info = &device->instance->physicalDevice.rad_info;
1615 unsigned tiling_index = iview->image->surface.tiling_index[level];
1616 unsigned stencil_index = iview->image->surface.stencil_tiling_index[level];
1617 unsigned macro_index = iview->image->surface.macro_tile_index;
1618 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
1619 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
1620 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
1621
1622 ds->db_depth_info |=
1623 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
1624 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
1625 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
1626 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
1627 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
1628 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
1629 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
1630 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
1631 } else {
1632 unsigned tile_mode_index = si_tile_mode_index(iview->image, level, false);
1633 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
1634 tile_mode_index = si_tile_mode_index(iview->image, level, true);
1635 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
1636 }
1637
1638 if (iview->image->htile.size && !level) {
1639 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1) |
1640 S_028040_ALLOW_EXPCLEAR(1);
1641
1642 if (iview->image->surface.flags & RADEON_SURF_SBUFFER) {
1643 /* Workaround: For a not yet understood reason, the
1644 * combination of MSAA, fast stencil clear and stencil
1645 * decompress messes with subsequent stencil buffer
1646 * uses. Problem was reproduced on Verde, Bonaire,
1647 * Tonga, and Carrizo.
1648 *
1649 * Disabling EXPCLEAR works around the problem.
1650 *
1651 * Check piglit's arb_texture_multisample-stencil-clear
1652 * test if you want to try changing this.
1653 */
1654 if (iview->image->samples <= 1)
1655 ds->db_stencil_info |= S_028044_ALLOW_EXPCLEAR(1);
1656 } else
1657 /* Use all of the htile_buffer for depth if there's no stencil. */
1658 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
1659
1660 va = device->ws->buffer_get_va(iview->bo) + iview->image->offset +
1661 iview->image->htile.offset;
1662 ds->db_htile_data_base = va >> 8;
1663 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
1664 } else {
1665 ds->db_htile_data_base = 0;
1666 ds->db_htile_surface = 0;
1667 }
1668
1669 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
1670 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
1671
1672 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
1673 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
1674 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
1675 }
1676
1677 VkResult radv_CreateFramebuffer(
1678 VkDevice _device,
1679 const VkFramebufferCreateInfo* pCreateInfo,
1680 const VkAllocationCallbacks* pAllocator,
1681 VkFramebuffer* pFramebuffer)
1682 {
1683 RADV_FROM_HANDLE(radv_device, device, _device);
1684 struct radv_framebuffer *framebuffer;
1685
1686 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
1687
1688 size_t size = sizeof(*framebuffer) +
1689 sizeof(struct radv_attachment_info) * pCreateInfo->attachmentCount;
1690 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
1691 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1692 if (framebuffer == NULL)
1693 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1694
1695 framebuffer->attachment_count = pCreateInfo->attachmentCount;
1696 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
1697 VkImageView _iview = pCreateInfo->pAttachments[i];
1698 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
1699 framebuffer->attachments[i].attachment = iview;
1700 if (iview->aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) {
1701 radv_initialise_color_surface(device, &framebuffer->attachments[i].cb, iview);
1702 } else if (iview->aspect_mask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
1703 radv_initialise_ds_surface(device, &framebuffer->attachments[i].ds, iview);
1704 }
1705 }
1706
1707 framebuffer->width = pCreateInfo->width;
1708 framebuffer->height = pCreateInfo->height;
1709 framebuffer->layers = pCreateInfo->layers;
1710
1711 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
1712 return VK_SUCCESS;
1713 }
1714
1715 void radv_DestroyFramebuffer(
1716 VkDevice _device,
1717 VkFramebuffer _fb,
1718 const VkAllocationCallbacks* pAllocator)
1719 {
1720 RADV_FROM_HANDLE(radv_device, device, _device);
1721 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
1722
1723 if (!fb)
1724 return;
1725 vk_free2(&device->alloc, pAllocator, fb);
1726 }
1727
1728 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
1729 {
1730 switch (address_mode) {
1731 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
1732 return V_008F30_SQ_TEX_WRAP;
1733 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
1734 return V_008F30_SQ_TEX_MIRROR;
1735 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
1736 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
1737 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
1738 return V_008F30_SQ_TEX_CLAMP_BORDER;
1739 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
1740 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
1741 default:
1742 unreachable("illegal tex wrap mode");
1743 break;
1744 }
1745 }
1746
1747 static unsigned
1748 radv_tex_compare(VkCompareOp op)
1749 {
1750 switch (op) {
1751 case VK_COMPARE_OP_NEVER:
1752 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
1753 case VK_COMPARE_OP_LESS:
1754 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
1755 case VK_COMPARE_OP_EQUAL:
1756 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
1757 case VK_COMPARE_OP_LESS_OR_EQUAL:
1758 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
1759 case VK_COMPARE_OP_GREATER:
1760 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
1761 case VK_COMPARE_OP_NOT_EQUAL:
1762 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
1763 case VK_COMPARE_OP_GREATER_OR_EQUAL:
1764 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
1765 case VK_COMPARE_OP_ALWAYS:
1766 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
1767 default:
1768 unreachable("illegal compare mode");
1769 break;
1770 }
1771 }
1772
1773 static unsigned
1774 radv_tex_filter(VkFilter filter, unsigned max_ansio)
1775 {
1776 switch (filter) {
1777 case VK_FILTER_NEAREST:
1778 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
1779 V_008F38_SQ_TEX_XY_FILTER_POINT);
1780 case VK_FILTER_LINEAR:
1781 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
1782 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
1783 case VK_FILTER_CUBIC_IMG:
1784 default:
1785 fprintf(stderr, "illegal texture filter");
1786 return 0;
1787 }
1788 }
1789
1790 static unsigned
1791 radv_tex_mipfilter(VkSamplerMipmapMode mode)
1792 {
1793 switch (mode) {
1794 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
1795 return V_008F38_SQ_TEX_Z_FILTER_POINT;
1796 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
1797 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
1798 default:
1799 return V_008F38_SQ_TEX_Z_FILTER_NONE;
1800 }
1801 }
1802
1803 static unsigned
1804 radv_tex_bordercolor(VkBorderColor bcolor)
1805 {
1806 switch (bcolor) {
1807 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
1808 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
1809 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
1810 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
1811 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
1812 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
1813 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
1814 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
1815 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
1816 default:
1817 break;
1818 }
1819 return 0;
1820 }
1821
1822 static unsigned
1823 radv_tex_aniso_filter(unsigned filter)
1824 {
1825 if (filter < 2)
1826 return 0;
1827 if (filter < 4)
1828 return 1;
1829 if (filter < 8)
1830 return 2;
1831 if (filter < 16)
1832 return 3;
1833 return 4;
1834 }
1835
1836 static void
1837 radv_init_sampler(struct radv_device *device,
1838 struct radv_sampler *sampler,
1839 const VkSamplerCreateInfo *pCreateInfo)
1840 {
1841 uint32_t max_aniso = pCreateInfo->anisotropyEnable && pCreateInfo->maxAnisotropy > 1.0 ?
1842 (uint32_t) pCreateInfo->maxAnisotropy : 0;
1843 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
1844 bool is_vi = (device->instance->physicalDevice.rad_info.chip_class >= VI);
1845
1846 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
1847 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
1848 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
1849 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
1850 S_008F30_DEPTH_COMPARE_FUNC(radv_tex_compare(pCreateInfo->compareOp)) |
1851 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
1852 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
1853 S_008F30_ANISO_BIAS(max_aniso_ratio) |
1854 S_008F30_DISABLE_CUBE_WRAP(0) |
1855 S_008F30_COMPAT_MODE(is_vi));
1856 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
1857 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
1858 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
1859 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
1860 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
1861 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
1862 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
1863 S_008F38_MIP_POINT_PRECLAMP(1) |
1864 S_008F38_DISABLE_LSB_CEIL(1) |
1865 S_008F38_FILTER_PREC_FIX(1) |
1866 S_008F38_ANISO_OVERRIDE(is_vi));
1867 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(0) |
1868 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(pCreateInfo->borderColor)));
1869 }
1870
1871 VkResult radv_CreateSampler(
1872 VkDevice _device,
1873 const VkSamplerCreateInfo* pCreateInfo,
1874 const VkAllocationCallbacks* pAllocator,
1875 VkSampler* pSampler)
1876 {
1877 RADV_FROM_HANDLE(radv_device, device, _device);
1878 struct radv_sampler *sampler;
1879
1880 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
1881
1882 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
1883 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1884 if (!sampler)
1885 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
1886
1887 radv_init_sampler(device, sampler, pCreateInfo);
1888 *pSampler = radv_sampler_to_handle(sampler);
1889
1890 return VK_SUCCESS;
1891 }
1892
1893 void radv_DestroySampler(
1894 VkDevice _device,
1895 VkSampler _sampler,
1896 const VkAllocationCallbacks* pAllocator)
1897 {
1898 RADV_FROM_HANDLE(radv_device, device, _device);
1899 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
1900
1901 if (!sampler)
1902 return;
1903 vk_free2(&device->alloc, pAllocator, sampler);
1904 }