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