radv: factor out radv_alloc_memory
[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 <stdbool.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include "radv_debug.h"
33 #include "radv_private.h"
34 #include "radv_shader.h"
35 #include "radv_cs.h"
36 #include "util/disk_cache.h"
37 #include "util/strtod.h"
38 #include "vk_util.h"
39 #include <xf86drm.h>
40 #include <amdgpu.h>
41 #include <amdgpu_drm.h>
42 #include "amdgpu_id.h"
43 #include "winsys/amdgpu/radv_amdgpu_winsys_public.h"
44 #include "ac_llvm_util.h"
45 #include "vk_format.h"
46 #include "sid.h"
47 #include "gfx9d.h"
48 #include "util/debug.h"
49
50 static int
51 radv_device_get_cache_uuid(enum radeon_family family, void *uuid)
52 {
53 uint32_t mesa_timestamp, llvm_timestamp;
54 uint16_t f = family;
55 memset(uuid, 0, VK_UUID_SIZE);
56 if (!disk_cache_get_function_timestamp(radv_device_get_cache_uuid, &mesa_timestamp) ||
57 !disk_cache_get_function_timestamp(LLVMInitializeAMDGPUTargetInfo, &llvm_timestamp))
58 return -1;
59
60 memcpy(uuid, &mesa_timestamp, 4);
61 memcpy((char*)uuid + 4, &llvm_timestamp, 4);
62 memcpy((char*)uuid + 8, &f, 2);
63 snprintf((char*)uuid + 10, VK_UUID_SIZE - 10, "radv");
64 return 0;
65 }
66
67 static void
68 radv_get_driver_uuid(void *uuid)
69 {
70 ac_compute_driver_uuid(uuid, VK_UUID_SIZE);
71 }
72
73 static void
74 radv_get_device_uuid(struct radeon_info *info, void *uuid)
75 {
76 ac_compute_device_uuid(info, uuid, VK_UUID_SIZE);
77 }
78
79 static const char *
80 get_chip_name(enum radeon_family family)
81 {
82 switch (family) {
83 case CHIP_TAHITI: return "AMD RADV TAHITI";
84 case CHIP_PITCAIRN: return "AMD RADV PITCAIRN";
85 case CHIP_VERDE: return "AMD RADV CAPE VERDE";
86 case CHIP_OLAND: return "AMD RADV OLAND";
87 case CHIP_HAINAN: return "AMD RADV HAINAN";
88 case CHIP_BONAIRE: return "AMD RADV BONAIRE";
89 case CHIP_KAVERI: return "AMD RADV KAVERI";
90 case CHIP_KABINI: return "AMD RADV KABINI";
91 case CHIP_HAWAII: return "AMD RADV HAWAII";
92 case CHIP_MULLINS: return "AMD RADV MULLINS";
93 case CHIP_TONGA: return "AMD RADV TONGA";
94 case CHIP_ICELAND: return "AMD RADV ICELAND";
95 case CHIP_CARRIZO: return "AMD RADV CARRIZO";
96 case CHIP_FIJI: return "AMD RADV FIJI";
97 case CHIP_POLARIS10: return "AMD RADV POLARIS10";
98 case CHIP_POLARIS11: return "AMD RADV POLARIS11";
99 case CHIP_POLARIS12: return "AMD RADV POLARIS12";
100 case CHIP_STONEY: return "AMD RADV STONEY";
101 case CHIP_VEGA10: return "AMD RADV VEGA";
102 case CHIP_RAVEN: return "AMD RADV RAVEN";
103 default: return "AMD RADV unknown";
104 }
105 }
106
107 static VkResult
108 radv_physical_device_init(struct radv_physical_device *device,
109 struct radv_instance *instance,
110 drmDevicePtr drm_device)
111 {
112 const char *path = drm_device->nodes[DRM_NODE_RENDER];
113 VkResult result;
114 drmVersionPtr version;
115 int fd;
116
117 fd = open(path, O_RDWR | O_CLOEXEC);
118 if (fd < 0)
119 return VK_ERROR_INCOMPATIBLE_DRIVER;
120
121 version = drmGetVersion(fd);
122 if (!version) {
123 close(fd);
124 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
125 "failed to get version %s: %m", path);
126 }
127
128 if (strcmp(version->name, "amdgpu")) {
129 drmFreeVersion(version);
130 close(fd);
131 return VK_ERROR_INCOMPATIBLE_DRIVER;
132 }
133 drmFreeVersion(version);
134
135 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
136 device->instance = instance;
137 assert(strlen(path) < ARRAY_SIZE(device->path));
138 strncpy(device->path, path, ARRAY_SIZE(device->path));
139
140 device->ws = radv_amdgpu_winsys_create(fd, instance->debug_flags,
141 instance->perftest_flags);
142 if (!device->ws) {
143 result = VK_ERROR_INCOMPATIBLE_DRIVER;
144 goto fail;
145 }
146
147 device->local_fd = fd;
148 device->ws->query_info(device->ws, &device->rad_info);
149 result = radv_init_wsi(device);
150 if (result != VK_SUCCESS) {
151 device->ws->destroy(device->ws);
152 goto fail;
153 }
154
155 if (radv_device_get_cache_uuid(device->rad_info.family, device->cache_uuid)) {
156 radv_finish_wsi(device);
157 device->ws->destroy(device->ws);
158 result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
159 "cannot generate UUID");
160 goto fail;
161 }
162
163 /* These flags affect shader compilation. */
164 uint64_t shader_env_flags =
165 (device->instance->perftest_flags & RADV_PERFTEST_SISCHED ? 0x1 : 0) |
166 (device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH ? 0x2 : 0);
167
168 /* The gpu id is already embeded in the uuid so we just pass "radv"
169 * when creating the cache.
170 */
171 char buf[VK_UUID_SIZE + 1];
172 disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE);
173 device->disk_cache = disk_cache_create("radv", buf, shader_env_flags);
174
175 fprintf(stderr, "WARNING: radv is not a conformant vulkan implementation, testing use only.\n");
176 device->name = get_chip_name(device->rad_info.family);
177
178 radv_get_driver_uuid(&device->device_uuid);
179 radv_get_device_uuid(&device->rad_info, &device->device_uuid);
180
181 if (device->rad_info.family == CHIP_STONEY ||
182 device->rad_info.chip_class >= GFX9) {
183 device->has_rbplus = true;
184 device->rbplus_allowed = device->rad_info.family == CHIP_STONEY;
185 }
186
187 /* The mere presense of CLEAR_STATE in the IB causes random GPU hangs
188 * on SI.
189 */
190 device->has_clear_state = device->rad_info.chip_class >= CIK;
191
192 return VK_SUCCESS;
193
194 fail:
195 close(fd);
196 return result;
197 }
198
199 static void
200 radv_physical_device_finish(struct radv_physical_device *device)
201 {
202 radv_finish_wsi(device);
203 device->ws->destroy(device->ws);
204 disk_cache_destroy(device->disk_cache);
205 close(device->local_fd);
206 }
207
208 static void *
209 default_alloc_func(void *pUserData, size_t size, size_t align,
210 VkSystemAllocationScope allocationScope)
211 {
212 return malloc(size);
213 }
214
215 static void *
216 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
217 size_t align, VkSystemAllocationScope allocationScope)
218 {
219 return realloc(pOriginal, size);
220 }
221
222 static void
223 default_free_func(void *pUserData, void *pMemory)
224 {
225 free(pMemory);
226 }
227
228 static const VkAllocationCallbacks default_alloc = {
229 .pUserData = NULL,
230 .pfnAllocation = default_alloc_func,
231 .pfnReallocation = default_realloc_func,
232 .pfnFree = default_free_func,
233 };
234
235 static const struct debug_control radv_debug_options[] = {
236 {"nofastclears", RADV_DEBUG_NO_FAST_CLEARS},
237 {"nodcc", RADV_DEBUG_NO_DCC},
238 {"shaders", RADV_DEBUG_DUMP_SHADERS},
239 {"nocache", RADV_DEBUG_NO_CACHE},
240 {"shaderstats", RADV_DEBUG_DUMP_SHADER_STATS},
241 {"nohiz", RADV_DEBUG_NO_HIZ},
242 {"nocompute", RADV_DEBUG_NO_COMPUTE_QUEUE},
243 {"unsafemath", RADV_DEBUG_UNSAFE_MATH},
244 {"allbos", RADV_DEBUG_ALL_BOS},
245 {"noibs", RADV_DEBUG_NO_IBS},
246 {"spirv", RADV_DEBUG_DUMP_SPIRV},
247 {"vmfaults", RADV_DEBUG_VM_FAULTS},
248 {"zerovram", RADV_DEBUG_ZERO_VRAM},
249 {"syncshaders", RADV_DEBUG_SYNC_SHADERS},
250 {NULL, 0}
251 };
252
253 const char *
254 radv_get_debug_option_name(int id)
255 {
256 assert(id < ARRAY_SIZE(radv_debug_options) - 1);
257 return radv_debug_options[id].string;
258 }
259
260 static const struct debug_control radv_perftest_options[] = {
261 {"nobatchchain", RADV_PERFTEST_NO_BATCHCHAIN},
262 {"sisched", RADV_PERFTEST_SISCHED},
263 {NULL, 0}
264 };
265
266 const char *
267 radv_get_perftest_option_name(int id)
268 {
269 assert(id < ARRAY_SIZE(radv_debug_options) - 1);
270 return radv_perftest_options[id].string;
271 }
272
273 VkResult radv_CreateInstance(
274 const VkInstanceCreateInfo* pCreateInfo,
275 const VkAllocationCallbacks* pAllocator,
276 VkInstance* pInstance)
277 {
278 struct radv_instance *instance;
279
280 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
281
282 uint32_t client_version;
283 if (pCreateInfo->pApplicationInfo &&
284 pCreateInfo->pApplicationInfo->apiVersion != 0) {
285 client_version = pCreateInfo->pApplicationInfo->apiVersion;
286 } else {
287 client_version = VK_MAKE_VERSION(1, 0, 0);
288 }
289
290 if (VK_MAKE_VERSION(1, 0, 0) > client_version ||
291 client_version > VK_MAKE_VERSION(1, 0, 0xfff)) {
292 return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
293 "Client requested version %d.%d.%d",
294 VK_VERSION_MAJOR(client_version),
295 VK_VERSION_MINOR(client_version),
296 VK_VERSION_PATCH(client_version));
297 }
298
299 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
300 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
301 if (!radv_instance_extension_supported(ext_name))
302 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
303 }
304
305 instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
306 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
307 if (!instance)
308 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
309
310 memset(instance, 0, sizeof(*instance));
311
312 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
313
314 if (pAllocator)
315 instance->alloc = *pAllocator;
316 else
317 instance->alloc = default_alloc;
318
319 instance->apiVersion = client_version;
320 instance->physicalDeviceCount = -1;
321
322 _mesa_locale_init();
323
324 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
325
326 instance->debug_flags = parse_debug_string(getenv("RADV_DEBUG"),
327 radv_debug_options);
328
329 instance->perftest_flags = parse_debug_string(getenv("RADV_PERFTEST"),
330 radv_perftest_options);
331
332 *pInstance = radv_instance_to_handle(instance);
333
334 return VK_SUCCESS;
335 }
336
337 void radv_DestroyInstance(
338 VkInstance _instance,
339 const VkAllocationCallbacks* pAllocator)
340 {
341 RADV_FROM_HANDLE(radv_instance, instance, _instance);
342
343 if (!instance)
344 return;
345
346 for (int i = 0; i < instance->physicalDeviceCount; ++i) {
347 radv_physical_device_finish(instance->physicalDevices + i);
348 }
349
350 VG(VALGRIND_DESTROY_MEMPOOL(instance));
351
352 _mesa_locale_fini();
353
354 vk_free(&instance->alloc, instance);
355 }
356
357 static VkResult
358 radv_enumerate_devices(struct radv_instance *instance)
359 {
360 /* TODO: Check for more devices ? */
361 drmDevicePtr devices[8];
362 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
363 int max_devices;
364
365 instance->physicalDeviceCount = 0;
366
367 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
368 if (max_devices < 1)
369 return VK_ERROR_INCOMPATIBLE_DRIVER;
370
371 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
372 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
373 devices[i]->bustype == DRM_BUS_PCI &&
374 devices[i]->deviceinfo.pci->vendor_id == ATI_VENDOR_ID) {
375
376 result = radv_physical_device_init(instance->physicalDevices +
377 instance->physicalDeviceCount,
378 instance,
379 devices[i]);
380 if (result == VK_SUCCESS)
381 ++instance->physicalDeviceCount;
382 else if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
383 break;
384 }
385 }
386 drmFreeDevices(devices, max_devices);
387
388 return result;
389 }
390
391 VkResult radv_EnumeratePhysicalDevices(
392 VkInstance _instance,
393 uint32_t* pPhysicalDeviceCount,
394 VkPhysicalDevice* pPhysicalDevices)
395 {
396 RADV_FROM_HANDLE(radv_instance, instance, _instance);
397 VkResult result;
398
399 if (instance->physicalDeviceCount < 0) {
400 result = radv_enumerate_devices(instance);
401 if (result != VK_SUCCESS &&
402 result != VK_ERROR_INCOMPATIBLE_DRIVER)
403 return result;
404 }
405
406 if (!pPhysicalDevices) {
407 *pPhysicalDeviceCount = instance->physicalDeviceCount;
408 } else {
409 *pPhysicalDeviceCount = MIN2(*pPhysicalDeviceCount, instance->physicalDeviceCount);
410 for (unsigned i = 0; i < *pPhysicalDeviceCount; ++i)
411 pPhysicalDevices[i] = radv_physical_device_to_handle(instance->physicalDevices + i);
412 }
413
414 return *pPhysicalDeviceCount < instance->physicalDeviceCount ? VK_INCOMPLETE
415 : VK_SUCCESS;
416 }
417
418 void radv_GetPhysicalDeviceFeatures(
419 VkPhysicalDevice physicalDevice,
420 VkPhysicalDeviceFeatures* pFeatures)
421 {
422 memset(pFeatures, 0, sizeof(*pFeatures));
423
424 *pFeatures = (VkPhysicalDeviceFeatures) {
425 .robustBufferAccess = true,
426 .fullDrawIndexUint32 = true,
427 .imageCubeArray = true,
428 .independentBlend = true,
429 .geometryShader = true,
430 .tessellationShader = true,
431 .sampleRateShading = true,
432 .dualSrcBlend = true,
433 .logicOp = true,
434 .multiDrawIndirect = true,
435 .drawIndirectFirstInstance = true,
436 .depthClamp = true,
437 .depthBiasClamp = true,
438 .fillModeNonSolid = true,
439 .depthBounds = true,
440 .wideLines = true,
441 .largePoints = true,
442 .alphaToOne = true,
443 .multiViewport = true,
444 .samplerAnisotropy = true,
445 .textureCompressionETC2 = false,
446 .textureCompressionASTC_LDR = false,
447 .textureCompressionBC = true,
448 .occlusionQueryPrecise = true,
449 .pipelineStatisticsQuery = true,
450 .vertexPipelineStoresAndAtomics = true,
451 .fragmentStoresAndAtomics = true,
452 .shaderTessellationAndGeometryPointSize = true,
453 .shaderImageGatherExtended = true,
454 .shaderStorageImageExtendedFormats = true,
455 .shaderStorageImageMultisample = false,
456 .shaderUniformBufferArrayDynamicIndexing = true,
457 .shaderSampledImageArrayDynamicIndexing = true,
458 .shaderStorageBufferArrayDynamicIndexing = true,
459 .shaderStorageImageArrayDynamicIndexing = true,
460 .shaderStorageImageReadWithoutFormat = true,
461 .shaderStorageImageWriteWithoutFormat = true,
462 .shaderClipDistance = true,
463 .shaderCullDistance = true,
464 .shaderFloat64 = true,
465 .shaderInt64 = true,
466 .shaderInt16 = false,
467 .sparseBinding = true,
468 .variableMultisampleRate = true,
469 .inheritedQueries = true,
470 };
471 }
472
473 void radv_GetPhysicalDeviceFeatures2KHR(
474 VkPhysicalDevice physicalDevice,
475 VkPhysicalDeviceFeatures2KHR *pFeatures)
476 {
477 vk_foreach_struct(ext, pFeatures->pNext) {
478 switch (ext->sType) {
479 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR: {
480 VkPhysicalDeviceVariablePointerFeaturesKHR *features = (void *)ext;
481 features->variablePointersStorageBuffer = true;
482 features->variablePointers = false;
483 break;
484 }
485 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHX: {
486 VkPhysicalDeviceMultiviewFeaturesKHX *features = (VkPhysicalDeviceMultiviewFeaturesKHX*)ext;
487 features->multiview = true;
488 features->multiviewGeometryShader = true;
489 features->multiviewTessellationShader = true;
490 break;
491 }
492 default:
493 break;
494 }
495 }
496 return radv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
497 }
498
499 void radv_GetPhysicalDeviceProperties(
500 VkPhysicalDevice physicalDevice,
501 VkPhysicalDeviceProperties* pProperties)
502 {
503 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
504 VkSampleCountFlags sample_counts = 0xf;
505
506 /* make sure that the entire descriptor set is addressable with a signed
507 * 32-bit int. So the sum of all limits scaled by descriptor size has to
508 * be at most 2 GiB. the combined image & samples object count as one of
509 * both. This limit is for the pipeline layout, not for the set layout, but
510 * there is no set limit, so we just set a pipeline limit. I don't think
511 * any app is going to hit this soon. */
512 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
513 (32 /* uniform buffer, 32 due to potential space wasted on alignement */ +
514 32 /* storage buffer, 32 due to potential space wasted on alignement */ +
515 32 /* sampler, largest when combined with image */ +
516 64 /* sampled image */ +
517 64 /* storage image */);
518
519 VkPhysicalDeviceLimits limits = {
520 .maxImageDimension1D = (1 << 14),
521 .maxImageDimension2D = (1 << 14),
522 .maxImageDimension3D = (1 << 11),
523 .maxImageDimensionCube = (1 << 14),
524 .maxImageArrayLayers = (1 << 11),
525 .maxTexelBufferElements = 128 * 1024 * 1024,
526 .maxUniformBufferRange = UINT32_MAX,
527 .maxStorageBufferRange = UINT32_MAX,
528 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
529 .maxMemoryAllocationCount = UINT32_MAX,
530 .maxSamplerAllocationCount = 64 * 1024,
531 .bufferImageGranularity = 64, /* A cache line */
532 .sparseAddressSpaceSize = 0xffffffffu, /* buffer max size */
533 .maxBoundDescriptorSets = MAX_SETS,
534 .maxPerStageDescriptorSamplers = max_descriptor_set_size,
535 .maxPerStageDescriptorUniformBuffers = max_descriptor_set_size,
536 .maxPerStageDescriptorStorageBuffers = max_descriptor_set_size,
537 .maxPerStageDescriptorSampledImages = max_descriptor_set_size,
538 .maxPerStageDescriptorStorageImages = max_descriptor_set_size,
539 .maxPerStageDescriptorInputAttachments = max_descriptor_set_size,
540 .maxPerStageResources = max_descriptor_set_size,
541 .maxDescriptorSetSamplers = max_descriptor_set_size,
542 .maxDescriptorSetUniformBuffers = max_descriptor_set_size,
543 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
544 .maxDescriptorSetStorageBuffers = max_descriptor_set_size,
545 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
546 .maxDescriptorSetSampledImages = max_descriptor_set_size,
547 .maxDescriptorSetStorageImages = max_descriptor_set_size,
548 .maxDescriptorSetInputAttachments = max_descriptor_set_size,
549 .maxVertexInputAttributes = 32,
550 .maxVertexInputBindings = 32,
551 .maxVertexInputAttributeOffset = 2047,
552 .maxVertexInputBindingStride = 2048,
553 .maxVertexOutputComponents = 128,
554 .maxTessellationGenerationLevel = 64,
555 .maxTessellationPatchSize = 32,
556 .maxTessellationControlPerVertexInputComponents = 128,
557 .maxTessellationControlPerVertexOutputComponents = 128,
558 .maxTessellationControlPerPatchOutputComponents = 120,
559 .maxTessellationControlTotalOutputComponents = 4096,
560 .maxTessellationEvaluationInputComponents = 128,
561 .maxTessellationEvaluationOutputComponents = 128,
562 .maxGeometryShaderInvocations = 127,
563 .maxGeometryInputComponents = 64,
564 .maxGeometryOutputComponents = 128,
565 .maxGeometryOutputVertices = 256,
566 .maxGeometryTotalOutputComponents = 1024,
567 .maxFragmentInputComponents = 128,
568 .maxFragmentOutputAttachments = 8,
569 .maxFragmentDualSrcAttachments = 1,
570 .maxFragmentCombinedOutputResources = 8,
571 .maxComputeSharedMemorySize = 32768,
572 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
573 .maxComputeWorkGroupInvocations = 2048,
574 .maxComputeWorkGroupSize = {
575 2048,
576 2048,
577 2048
578 },
579 .subPixelPrecisionBits = 4 /* FIXME */,
580 .subTexelPrecisionBits = 4 /* FIXME */,
581 .mipmapPrecisionBits = 4 /* FIXME */,
582 .maxDrawIndexedIndexValue = UINT32_MAX,
583 .maxDrawIndirectCount = UINT32_MAX,
584 .maxSamplerLodBias = 16,
585 .maxSamplerAnisotropy = 16,
586 .maxViewports = MAX_VIEWPORTS,
587 .maxViewportDimensions = { (1 << 14), (1 << 14) },
588 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
589 .viewportSubPixelBits = 13, /* We take a float? */
590 .minMemoryMapAlignment = 4096, /* A page */
591 .minTexelBufferOffsetAlignment = 1,
592 .minUniformBufferOffsetAlignment = 4,
593 .minStorageBufferOffsetAlignment = 4,
594 .minTexelOffset = -32,
595 .maxTexelOffset = 31,
596 .minTexelGatherOffset = -32,
597 .maxTexelGatherOffset = 31,
598 .minInterpolationOffset = -2,
599 .maxInterpolationOffset = 2,
600 .subPixelInterpolationOffsetBits = 8,
601 .maxFramebufferWidth = (1 << 14),
602 .maxFramebufferHeight = (1 << 14),
603 .maxFramebufferLayers = (1 << 10),
604 .framebufferColorSampleCounts = sample_counts,
605 .framebufferDepthSampleCounts = sample_counts,
606 .framebufferStencilSampleCounts = sample_counts,
607 .framebufferNoAttachmentsSampleCounts = sample_counts,
608 .maxColorAttachments = MAX_RTS,
609 .sampledImageColorSampleCounts = sample_counts,
610 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
611 .sampledImageDepthSampleCounts = sample_counts,
612 .sampledImageStencilSampleCounts = sample_counts,
613 .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
614 .maxSampleMaskWords = 1,
615 .timestampComputeAndGraphics = true,
616 .timestampPeriod = 1000000.0 / pdevice->rad_info.clock_crystal_freq,
617 .maxClipDistances = 8,
618 .maxCullDistances = 8,
619 .maxCombinedClipAndCullDistances = 8,
620 .discreteQueuePriorities = 1,
621 .pointSizeRange = { 0.125, 255.875 },
622 .lineWidthRange = { 0.0, 7.9921875 },
623 .pointSizeGranularity = (1.0 / 8.0),
624 .lineWidthGranularity = (1.0 / 128.0),
625 .strictLines = false, /* FINISHME */
626 .standardSampleLocations = true,
627 .optimalBufferCopyOffsetAlignment = 128,
628 .optimalBufferCopyRowPitchAlignment = 128,
629 .nonCoherentAtomSize = 64,
630 };
631
632 *pProperties = (VkPhysicalDeviceProperties) {
633 .apiVersion = radv_physical_device_api_version(pdevice),
634 .driverVersion = vk_get_driver_version(),
635 .vendorID = ATI_VENDOR_ID,
636 .deviceID = pdevice->rad_info.pci_id,
637 .deviceType = pdevice->rad_info.has_dedicated_vram ? VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU : VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
638 .limits = limits,
639 .sparseProperties = {0},
640 };
641
642 strcpy(pProperties->deviceName, pdevice->name);
643 memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
644 }
645
646 void radv_GetPhysicalDeviceProperties2KHR(
647 VkPhysicalDevice physicalDevice,
648 VkPhysicalDeviceProperties2KHR *pProperties)
649 {
650 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
651 radv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
652
653 vk_foreach_struct(ext, pProperties->pNext) {
654 switch (ext->sType) {
655 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
656 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
657 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
658 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
659 break;
660 }
661 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR: {
662 VkPhysicalDeviceIDPropertiesKHR *properties = (VkPhysicalDeviceIDPropertiesKHR*)ext;
663 memcpy(properties->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
664 memcpy(properties->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
665 properties->deviceLUIDValid = false;
666 break;
667 }
668 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHX: {
669 VkPhysicalDeviceMultiviewPropertiesKHX *properties = (VkPhysicalDeviceMultiviewPropertiesKHX*)ext;
670 properties->maxMultiviewViewCount = MAX_VIEWS;
671 properties->maxMultiviewInstanceIndex = INT_MAX;
672 break;
673 }
674 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES_KHR: {
675 VkPhysicalDevicePointClippingPropertiesKHR *properties =
676 (VkPhysicalDevicePointClippingPropertiesKHR*)ext;
677 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES_KHR;
678 break;
679 }
680 default:
681 break;
682 }
683 }
684 }
685
686 static void radv_get_physical_device_queue_family_properties(
687 struct radv_physical_device* pdevice,
688 uint32_t* pCount,
689 VkQueueFamilyProperties** pQueueFamilyProperties)
690 {
691 int num_queue_families = 1;
692 int idx;
693 if (pdevice->rad_info.num_compute_rings > 0 &&
694 pdevice->rad_info.chip_class >= CIK &&
695 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE))
696 num_queue_families++;
697
698 if (pQueueFamilyProperties == NULL) {
699 *pCount = num_queue_families;
700 return;
701 }
702
703 if (!*pCount)
704 return;
705
706 idx = 0;
707 if (*pCount >= 1) {
708 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
709 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
710 VK_QUEUE_COMPUTE_BIT |
711 VK_QUEUE_TRANSFER_BIT |
712 VK_QUEUE_SPARSE_BINDING_BIT,
713 .queueCount = 1,
714 .timestampValidBits = 64,
715 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
716 };
717 idx++;
718 }
719
720 if (pdevice->rad_info.num_compute_rings > 0 &&
721 pdevice->rad_info.chip_class >= CIK &&
722 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE)) {
723 if (*pCount > idx) {
724 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
725 .queueFlags = VK_QUEUE_COMPUTE_BIT |
726 VK_QUEUE_TRANSFER_BIT |
727 VK_QUEUE_SPARSE_BINDING_BIT,
728 .queueCount = pdevice->rad_info.num_compute_rings,
729 .timestampValidBits = 64,
730 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
731 };
732 idx++;
733 }
734 }
735 *pCount = idx;
736 }
737
738 void radv_GetPhysicalDeviceQueueFamilyProperties(
739 VkPhysicalDevice physicalDevice,
740 uint32_t* pCount,
741 VkQueueFamilyProperties* pQueueFamilyProperties)
742 {
743 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
744 if (!pQueueFamilyProperties) {
745 return radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
746 return;
747 }
748 VkQueueFamilyProperties *properties[] = {
749 pQueueFamilyProperties + 0,
750 pQueueFamilyProperties + 1,
751 pQueueFamilyProperties + 2,
752 };
753 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
754 assert(*pCount <= 3);
755 }
756
757 void radv_GetPhysicalDeviceQueueFamilyProperties2KHR(
758 VkPhysicalDevice physicalDevice,
759 uint32_t* pCount,
760 VkQueueFamilyProperties2KHR *pQueueFamilyProperties)
761 {
762 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
763 if (!pQueueFamilyProperties) {
764 return radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
765 return;
766 }
767 VkQueueFamilyProperties *properties[] = {
768 &pQueueFamilyProperties[0].queueFamilyProperties,
769 &pQueueFamilyProperties[1].queueFamilyProperties,
770 &pQueueFamilyProperties[2].queueFamilyProperties,
771 };
772 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
773 assert(*pCount <= 3);
774 }
775
776 void radv_GetPhysicalDeviceMemoryProperties(
777 VkPhysicalDevice physicalDevice,
778 VkPhysicalDeviceMemoryProperties *pMemoryProperties)
779 {
780 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
781
782 STATIC_ASSERT(RADV_MEM_TYPE_COUNT <= VK_MAX_MEMORY_TYPES);
783
784 pMemoryProperties->memoryTypeCount = RADV_MEM_TYPE_COUNT;
785 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_VRAM] = (VkMemoryType) {
786 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
787 .heapIndex = RADV_MEM_HEAP_VRAM,
788 };
789 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_GTT_WRITE_COMBINE] = (VkMemoryType) {
790 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
791 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
792 .heapIndex = RADV_MEM_HEAP_GTT,
793 };
794 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_VRAM_CPU_ACCESS] = (VkMemoryType) {
795 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
796 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
797 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
798 .heapIndex = RADV_MEM_HEAP_VRAM_CPU_ACCESS,
799 };
800 pMemoryProperties->memoryTypes[RADV_MEM_TYPE_GTT_CACHED] = (VkMemoryType) {
801 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
802 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
803 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
804 .heapIndex = RADV_MEM_HEAP_GTT,
805 };
806
807 STATIC_ASSERT(RADV_MEM_HEAP_COUNT <= VK_MAX_MEMORY_HEAPS);
808 uint64_t visible_vram_size = MIN2(physical_device->rad_info.vram_size,
809 physical_device->rad_info.vram_vis_size);
810
811 pMemoryProperties->memoryHeapCount = RADV_MEM_HEAP_COUNT;
812 pMemoryProperties->memoryHeaps[RADV_MEM_HEAP_VRAM] = (VkMemoryHeap) {
813 .size = physical_device->rad_info.vram_size -
814 visible_vram_size,
815 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
816 };
817 pMemoryProperties->memoryHeaps[RADV_MEM_HEAP_VRAM_CPU_ACCESS] = (VkMemoryHeap) {
818 .size = visible_vram_size,
819 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
820 };
821 pMemoryProperties->memoryHeaps[RADV_MEM_HEAP_GTT] = (VkMemoryHeap) {
822 .size = physical_device->rad_info.gart_size,
823 .flags = 0,
824 };
825 }
826
827 void radv_GetPhysicalDeviceMemoryProperties2KHR(
828 VkPhysicalDevice physicalDevice,
829 VkPhysicalDeviceMemoryProperties2KHR *pMemoryProperties)
830 {
831 return radv_GetPhysicalDeviceMemoryProperties(physicalDevice,
832 &pMemoryProperties->memoryProperties);
833 }
834
835 static enum radeon_ctx_priority
836 radv_get_queue_global_priority(const VkDeviceQueueGlobalPriorityCreateInfoEXT *pObj)
837 {
838 /* Default to MEDIUM when a specific global priority isn't requested */
839 if (!pObj)
840 return RADEON_CTX_PRIORITY_MEDIUM;
841
842 switch(pObj->globalPriority) {
843 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME:
844 return RADEON_CTX_PRIORITY_REALTIME;
845 case VK_QUEUE_GLOBAL_PRIORITY_HIGH:
846 return RADEON_CTX_PRIORITY_HIGH;
847 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM:
848 return RADEON_CTX_PRIORITY_MEDIUM;
849 case VK_QUEUE_GLOBAL_PRIORITY_LOW:
850 return RADEON_CTX_PRIORITY_LOW;
851 default:
852 unreachable("Illegal global priority value");
853 return RADEON_CTX_PRIORITY_INVALID;
854 }
855 }
856
857 static int
858 radv_queue_init(struct radv_device *device, struct radv_queue *queue,
859 int queue_family_index, int idx,
860 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority)
861 {
862 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
863 queue->device = device;
864 queue->queue_family_index = queue_family_index;
865 queue->queue_idx = idx;
866 queue->priority = radv_get_queue_global_priority(global_priority);
867
868 queue->hw_ctx = device->ws->ctx_create(device->ws, queue->priority);
869 if (!queue->hw_ctx)
870 return VK_ERROR_OUT_OF_HOST_MEMORY;
871
872 return VK_SUCCESS;
873 }
874
875 static void
876 radv_queue_finish(struct radv_queue *queue)
877 {
878 if (queue->hw_ctx)
879 queue->device->ws->ctx_destroy(queue->hw_ctx);
880
881 if (queue->initial_full_flush_preamble_cs)
882 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
883 if (queue->initial_preamble_cs)
884 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
885 if (queue->continue_preamble_cs)
886 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
887 if (queue->descriptor_bo)
888 queue->device->ws->buffer_destroy(queue->descriptor_bo);
889 if (queue->scratch_bo)
890 queue->device->ws->buffer_destroy(queue->scratch_bo);
891 if (queue->esgs_ring_bo)
892 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
893 if (queue->gsvs_ring_bo)
894 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
895 if (queue->tess_factor_ring_bo)
896 queue->device->ws->buffer_destroy(queue->tess_factor_ring_bo);
897 if (queue->tess_offchip_ring_bo)
898 queue->device->ws->buffer_destroy(queue->tess_offchip_ring_bo);
899 if (queue->compute_scratch_bo)
900 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
901 }
902
903 static void
904 radv_device_init_gs_info(struct radv_device *device)
905 {
906 switch (device->physical_device->rad_info.family) {
907 case CHIP_OLAND:
908 case CHIP_HAINAN:
909 case CHIP_KAVERI:
910 case CHIP_KABINI:
911 case CHIP_MULLINS:
912 case CHIP_ICELAND:
913 case CHIP_CARRIZO:
914 case CHIP_STONEY:
915 device->gs_table_depth = 16;
916 return;
917 case CHIP_TAHITI:
918 case CHIP_PITCAIRN:
919 case CHIP_VERDE:
920 case CHIP_BONAIRE:
921 case CHIP_HAWAII:
922 case CHIP_TONGA:
923 case CHIP_FIJI:
924 case CHIP_POLARIS10:
925 case CHIP_POLARIS11:
926 case CHIP_POLARIS12:
927 case CHIP_VEGA10:
928 case CHIP_RAVEN:
929 device->gs_table_depth = 32;
930 return;
931 default:
932 unreachable("unknown GPU");
933 }
934 }
935
936 VkResult radv_CreateDevice(
937 VkPhysicalDevice physicalDevice,
938 const VkDeviceCreateInfo* pCreateInfo,
939 const VkAllocationCallbacks* pAllocator,
940 VkDevice* pDevice)
941 {
942 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
943 VkResult result;
944 struct radv_device *device;
945
946 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
947 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
948 if (!radv_physical_device_extension_supported(physical_device, ext_name))
949 return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
950 }
951
952 /* Check enabled features */
953 if (pCreateInfo->pEnabledFeatures) {
954 VkPhysicalDeviceFeatures supported_features;
955 radv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
956 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
957 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
958 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
959 for (uint32_t i = 0; i < num_features; i++) {
960 if (enabled_feature[i] && !supported_feature[i])
961 return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
962 }
963 }
964
965 device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
966 sizeof(*device), 8,
967 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
968 if (!device)
969 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
970
971 memset(device, 0, sizeof(*device));
972
973 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
974 device->instance = physical_device->instance;
975 device->physical_device = physical_device;
976
977 device->ws = physical_device->ws;
978 if (pAllocator)
979 device->alloc = *pAllocator;
980 else
981 device->alloc = physical_device->instance->alloc;
982
983 mtx_init(&device->shader_slab_mutex, mtx_plain);
984 list_inithead(&device->shader_slabs);
985
986 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
987 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
988 uint32_t qfi = queue_create->queueFamilyIndex;
989 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
990 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
991
992 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
993
994 device->queues[qfi] = vk_alloc(&device->alloc,
995 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
996 if (!device->queues[qfi]) {
997 result = VK_ERROR_OUT_OF_HOST_MEMORY;
998 goto fail;
999 }
1000
1001 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
1002
1003 device->queue_count[qfi] = queue_create->queueCount;
1004
1005 for (unsigned q = 0; q < queue_create->queueCount; q++) {
1006 result = radv_queue_init(device, &device->queues[qfi][q], qfi, q, global_priority);
1007 if (result != VK_SUCCESS)
1008 goto fail;
1009 }
1010 }
1011
1012 #if HAVE_LLVM < 0x0400
1013 device->llvm_supports_spill = false;
1014 #else
1015 device->llvm_supports_spill = true;
1016 #endif
1017
1018 /* The maximum number of scratch waves. Scratch space isn't divided
1019 * evenly between CUs. The number is only a function of the number of CUs.
1020 * We can decrease the constant to decrease the scratch buffer size.
1021 *
1022 * sctx->scratch_waves must be >= the maximum posible size of
1023 * 1 threadgroup, so that the hw doesn't hang from being unable
1024 * to start any.
1025 *
1026 * The recommended value is 4 per CU at most. Higher numbers don't
1027 * bring much benefit, but they still occupy chip resources (think
1028 * async compute). I've seen ~2% performance difference between 4 and 32.
1029 */
1030 uint32_t max_threads_per_block = 2048;
1031 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
1032 max_threads_per_block / 64);
1033
1034 radv_device_init_gs_info(device);
1035
1036 device->tess_offchip_block_dw_size =
1037 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
1038 device->has_distributed_tess =
1039 device->physical_device->rad_info.chip_class >= VI &&
1040 device->physical_device->rad_info.max_se >= 2;
1041
1042 if (getenv("RADV_TRACE_FILE")) {
1043 if (!radv_init_trace(device))
1044 goto fail;
1045 }
1046
1047 result = radv_device_init_meta(device);
1048 if (result != VK_SUCCESS)
1049 goto fail;
1050
1051 radv_device_init_msaa(device);
1052
1053 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
1054 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
1055 switch (family) {
1056 case RADV_QUEUE_GENERAL:
1057 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
1058 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_LOAD_ENABLE(1));
1059 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_SHADOW_ENABLE(1));
1060 break;
1061 case RADV_QUEUE_COMPUTE:
1062 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
1063 radeon_emit(device->empty_cs[family], 0);
1064 break;
1065 }
1066 device->ws->cs_finalize(device->empty_cs[family]);
1067 }
1068
1069 if (device->physical_device->rad_info.chip_class >= CIK)
1070 cik_create_gfx_config(device);
1071
1072 VkPipelineCacheCreateInfo ci;
1073 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
1074 ci.pNext = NULL;
1075 ci.flags = 0;
1076 ci.pInitialData = NULL;
1077 ci.initialDataSize = 0;
1078 VkPipelineCache pc;
1079 result = radv_CreatePipelineCache(radv_device_to_handle(device),
1080 &ci, NULL, &pc);
1081 if (result != VK_SUCCESS)
1082 goto fail;
1083
1084 device->mem_cache = radv_pipeline_cache_from_handle(pc);
1085
1086 *pDevice = radv_device_to_handle(device);
1087 return VK_SUCCESS;
1088
1089 fail:
1090 if (device->trace_bo)
1091 device->ws->buffer_destroy(device->trace_bo);
1092
1093 if (device->gfx_init)
1094 device->ws->buffer_destroy(device->gfx_init);
1095
1096 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
1097 for (unsigned q = 0; q < device->queue_count[i]; q++)
1098 radv_queue_finish(&device->queues[i][q]);
1099 if (device->queue_count[i])
1100 vk_free(&device->alloc, device->queues[i]);
1101 }
1102
1103 vk_free(&device->alloc, device);
1104 return result;
1105 }
1106
1107 void radv_DestroyDevice(
1108 VkDevice _device,
1109 const VkAllocationCallbacks* pAllocator)
1110 {
1111 RADV_FROM_HANDLE(radv_device, device, _device);
1112
1113 if (!device)
1114 return;
1115
1116 if (device->trace_bo)
1117 device->ws->buffer_destroy(device->trace_bo);
1118
1119 if (device->gfx_init)
1120 device->ws->buffer_destroy(device->gfx_init);
1121
1122 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
1123 for (unsigned q = 0; q < device->queue_count[i]; q++)
1124 radv_queue_finish(&device->queues[i][q]);
1125 if (device->queue_count[i])
1126 vk_free(&device->alloc, device->queues[i]);
1127 if (device->empty_cs[i])
1128 device->ws->cs_destroy(device->empty_cs[i]);
1129 }
1130 radv_device_finish_meta(device);
1131
1132 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
1133 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
1134
1135 radv_destroy_shader_slabs(device);
1136
1137 vk_free(&device->alloc, device);
1138 }
1139
1140 VkResult radv_EnumerateInstanceLayerProperties(
1141 uint32_t* pPropertyCount,
1142 VkLayerProperties* pProperties)
1143 {
1144 if (pProperties == NULL) {
1145 *pPropertyCount = 0;
1146 return VK_SUCCESS;
1147 }
1148
1149 /* None supported at this time */
1150 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1151 }
1152
1153 VkResult radv_EnumerateDeviceLayerProperties(
1154 VkPhysicalDevice physicalDevice,
1155 uint32_t* pPropertyCount,
1156 VkLayerProperties* pProperties)
1157 {
1158 if (pProperties == NULL) {
1159 *pPropertyCount = 0;
1160 return VK_SUCCESS;
1161 }
1162
1163 /* None supported at this time */
1164 return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
1165 }
1166
1167 void radv_GetDeviceQueue(
1168 VkDevice _device,
1169 uint32_t queueFamilyIndex,
1170 uint32_t queueIndex,
1171 VkQueue* pQueue)
1172 {
1173 RADV_FROM_HANDLE(radv_device, device, _device);
1174
1175 *pQueue = radv_queue_to_handle(&device->queues[queueFamilyIndex][queueIndex]);
1176 }
1177
1178 static void
1179 fill_geom_tess_rings(struct radv_queue *queue,
1180 uint32_t *map,
1181 bool add_sample_positions,
1182 uint32_t esgs_ring_size,
1183 struct radeon_winsys_bo *esgs_ring_bo,
1184 uint32_t gsvs_ring_size,
1185 struct radeon_winsys_bo *gsvs_ring_bo,
1186 uint32_t tess_factor_ring_size,
1187 struct radeon_winsys_bo *tess_factor_ring_bo,
1188 uint32_t tess_offchip_ring_size,
1189 struct radeon_winsys_bo *tess_offchip_ring_bo)
1190 {
1191 uint64_t esgs_va = 0, gsvs_va = 0;
1192 uint64_t tess_factor_va = 0, tess_offchip_va = 0;
1193 uint32_t *desc = &map[4];
1194
1195 if (esgs_ring_bo)
1196 esgs_va = radv_buffer_get_va(esgs_ring_bo);
1197 if (gsvs_ring_bo)
1198 gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
1199 if (tess_factor_ring_bo)
1200 tess_factor_va = radv_buffer_get_va(tess_factor_ring_bo);
1201 if (tess_offchip_ring_bo)
1202 tess_offchip_va = radv_buffer_get_va(tess_offchip_ring_bo);
1203
1204 /* stride 0, num records - size, add tid, swizzle, elsize4,
1205 index stride 64 */
1206 desc[0] = esgs_va;
1207 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
1208 S_008F04_STRIDE(0) |
1209 S_008F04_SWIZZLE_ENABLE(true);
1210 desc[2] = esgs_ring_size;
1211 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1212 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1213 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1214 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
1215 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1216 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
1217 S_008F0C_ELEMENT_SIZE(1) |
1218 S_008F0C_INDEX_STRIDE(3) |
1219 S_008F0C_ADD_TID_ENABLE(true);
1220
1221 desc += 4;
1222 /* GS entry for ES->GS ring */
1223 /* stride 0, num records - size, elsize0,
1224 index stride 0 */
1225 desc[0] = esgs_va;
1226 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32)|
1227 S_008F04_STRIDE(0) |
1228 S_008F04_SWIZZLE_ENABLE(false);
1229 desc[2] = esgs_ring_size;
1230 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1231 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1232 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1233 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
1234 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1235 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
1236 S_008F0C_ELEMENT_SIZE(0) |
1237 S_008F0C_INDEX_STRIDE(0) |
1238 S_008F0C_ADD_TID_ENABLE(false);
1239
1240 desc += 4;
1241 /* VS entry for GS->VS ring */
1242 /* stride 0, num records - size, elsize0,
1243 index stride 0 */
1244 desc[0] = gsvs_va;
1245 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32)|
1246 S_008F04_STRIDE(0) |
1247 S_008F04_SWIZZLE_ENABLE(false);
1248 desc[2] = gsvs_ring_size;
1249 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1250 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1251 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1252 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
1253 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1254 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
1255 S_008F0C_ELEMENT_SIZE(0) |
1256 S_008F0C_INDEX_STRIDE(0) |
1257 S_008F0C_ADD_TID_ENABLE(false);
1258 desc += 4;
1259
1260 /* stride gsvs_itemsize, num records 64
1261 elsize 4, index stride 16 */
1262 /* shader will patch stride and desc[2] */
1263 desc[0] = gsvs_va;
1264 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32)|
1265 S_008F04_STRIDE(0) |
1266 S_008F04_SWIZZLE_ENABLE(true);
1267 desc[2] = 0;
1268 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1269 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1270 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1271 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
1272 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1273 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
1274 S_008F0C_ELEMENT_SIZE(1) |
1275 S_008F0C_INDEX_STRIDE(1) |
1276 S_008F0C_ADD_TID_ENABLE(true);
1277 desc += 4;
1278
1279 desc[0] = tess_factor_va;
1280 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_factor_va >> 32) |
1281 S_008F04_STRIDE(0) |
1282 S_008F04_SWIZZLE_ENABLE(false);
1283 desc[2] = tess_factor_ring_size;
1284 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1285 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1286 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1287 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
1288 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1289 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
1290 S_008F0C_ELEMENT_SIZE(0) |
1291 S_008F0C_INDEX_STRIDE(0) |
1292 S_008F0C_ADD_TID_ENABLE(false);
1293 desc += 4;
1294
1295 desc[0] = tess_offchip_va;
1296 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32) |
1297 S_008F04_STRIDE(0) |
1298 S_008F04_SWIZZLE_ENABLE(false);
1299 desc[2] = tess_offchip_ring_size;
1300 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
1301 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
1302 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
1303 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
1304 S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
1305 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
1306 S_008F0C_ELEMENT_SIZE(0) |
1307 S_008F0C_INDEX_STRIDE(0) |
1308 S_008F0C_ADD_TID_ENABLE(false);
1309 desc += 4;
1310
1311 /* add sample positions after all rings */
1312 memcpy(desc, queue->device->sample_locations_1x, 8);
1313 desc += 2;
1314 memcpy(desc, queue->device->sample_locations_2x, 16);
1315 desc += 4;
1316 memcpy(desc, queue->device->sample_locations_4x, 32);
1317 desc += 8;
1318 memcpy(desc, queue->device->sample_locations_8x, 64);
1319 desc += 16;
1320 memcpy(desc, queue->device->sample_locations_16x, 128);
1321 }
1322
1323 static unsigned
1324 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
1325 {
1326 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= CIK &&
1327 device->physical_device->rad_info.family != CHIP_CARRIZO &&
1328 device->physical_device->rad_info.family != CHIP_STONEY;
1329 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
1330 unsigned max_offchip_buffers = max_offchip_buffers_per_se *
1331 device->physical_device->rad_info.max_se;
1332 unsigned offchip_granularity;
1333 unsigned hs_offchip_param;
1334 switch (device->tess_offchip_block_dw_size) {
1335 default:
1336 assert(0);
1337 /* fall through */
1338 case 8192:
1339 offchip_granularity = V_03093C_X_8K_DWORDS;
1340 break;
1341 case 4096:
1342 offchip_granularity = V_03093C_X_4K_DWORDS;
1343 break;
1344 }
1345
1346 switch (device->physical_device->rad_info.chip_class) {
1347 case SI:
1348 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
1349 break;
1350 case CIK:
1351 case VI:
1352 case GFX9:
1353 default:
1354 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
1355 break;
1356 }
1357
1358 *max_offchip_buffers_p = max_offchip_buffers;
1359 if (device->physical_device->rad_info.chip_class >= CIK) {
1360 if (device->physical_device->rad_info.chip_class >= VI)
1361 --max_offchip_buffers;
1362 hs_offchip_param =
1363 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
1364 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
1365 } else {
1366 hs_offchip_param =
1367 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
1368 }
1369 return hs_offchip_param;
1370 }
1371
1372 static VkResult
1373 radv_get_preamble_cs(struct radv_queue *queue,
1374 uint32_t scratch_size,
1375 uint32_t compute_scratch_size,
1376 uint32_t esgs_ring_size,
1377 uint32_t gsvs_ring_size,
1378 bool needs_tess_rings,
1379 bool needs_sample_positions,
1380 struct radeon_winsys_cs **initial_full_flush_preamble_cs,
1381 struct radeon_winsys_cs **initial_preamble_cs,
1382 struct radeon_winsys_cs **continue_preamble_cs)
1383 {
1384 struct radeon_winsys_bo *scratch_bo = NULL;
1385 struct radeon_winsys_bo *descriptor_bo = NULL;
1386 struct radeon_winsys_bo *compute_scratch_bo = NULL;
1387 struct radeon_winsys_bo *esgs_ring_bo = NULL;
1388 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
1389 struct radeon_winsys_bo *tess_factor_ring_bo = NULL;
1390 struct radeon_winsys_bo *tess_offchip_ring_bo = NULL;
1391 struct radeon_winsys_cs *dest_cs[3] = {0};
1392 bool add_tess_rings = false, add_sample_positions = false;
1393 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
1394 unsigned max_offchip_buffers;
1395 unsigned hs_offchip_param = 0;
1396 if (!queue->has_tess_rings) {
1397 if (needs_tess_rings)
1398 add_tess_rings = true;
1399 }
1400 if (!queue->has_sample_positions) {
1401 if (needs_sample_positions)
1402 add_sample_positions = true;
1403 }
1404 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
1405 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
1406 &max_offchip_buffers);
1407 tess_offchip_ring_size = max_offchip_buffers *
1408 queue->device->tess_offchip_block_dw_size * 4;
1409
1410 if (scratch_size <= queue->scratch_size &&
1411 compute_scratch_size <= queue->compute_scratch_size &&
1412 esgs_ring_size <= queue->esgs_ring_size &&
1413 gsvs_ring_size <= queue->gsvs_ring_size &&
1414 !add_tess_rings && !add_sample_positions &&
1415 queue->initial_preamble_cs) {
1416 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
1417 *initial_preamble_cs = queue->initial_preamble_cs;
1418 *continue_preamble_cs = queue->continue_preamble_cs;
1419 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
1420 *continue_preamble_cs = NULL;
1421 return VK_SUCCESS;
1422 }
1423
1424 if (scratch_size > queue->scratch_size) {
1425 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
1426 scratch_size,
1427 4096,
1428 RADEON_DOMAIN_VRAM,
1429 RADEON_FLAG_NO_CPU_ACCESS);
1430 if (!scratch_bo)
1431 goto fail;
1432 } else
1433 scratch_bo = queue->scratch_bo;
1434
1435 if (compute_scratch_size > queue->compute_scratch_size) {
1436 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
1437 compute_scratch_size,
1438 4096,
1439 RADEON_DOMAIN_VRAM,
1440 RADEON_FLAG_NO_CPU_ACCESS);
1441 if (!compute_scratch_bo)
1442 goto fail;
1443
1444 } else
1445 compute_scratch_bo = queue->compute_scratch_bo;
1446
1447 if (esgs_ring_size > queue->esgs_ring_size) {
1448 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
1449 esgs_ring_size,
1450 4096,
1451 RADEON_DOMAIN_VRAM,
1452 RADEON_FLAG_NO_CPU_ACCESS);
1453 if (!esgs_ring_bo)
1454 goto fail;
1455 } else {
1456 esgs_ring_bo = queue->esgs_ring_bo;
1457 esgs_ring_size = queue->esgs_ring_size;
1458 }
1459
1460 if (gsvs_ring_size > queue->gsvs_ring_size) {
1461 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
1462 gsvs_ring_size,
1463 4096,
1464 RADEON_DOMAIN_VRAM,
1465 RADEON_FLAG_NO_CPU_ACCESS);
1466 if (!gsvs_ring_bo)
1467 goto fail;
1468 } else {
1469 gsvs_ring_bo = queue->gsvs_ring_bo;
1470 gsvs_ring_size = queue->gsvs_ring_size;
1471 }
1472
1473 if (add_tess_rings) {
1474 tess_factor_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
1475 tess_factor_ring_size,
1476 256,
1477 RADEON_DOMAIN_VRAM,
1478 RADEON_FLAG_NO_CPU_ACCESS);
1479 if (!tess_factor_ring_bo)
1480 goto fail;
1481 tess_offchip_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
1482 tess_offchip_ring_size,
1483 256,
1484 RADEON_DOMAIN_VRAM,
1485 RADEON_FLAG_NO_CPU_ACCESS);
1486 if (!tess_offchip_ring_bo)
1487 goto fail;
1488 } else {
1489 tess_factor_ring_bo = queue->tess_factor_ring_bo;
1490 tess_offchip_ring_bo = queue->tess_offchip_ring_bo;
1491 }
1492
1493 if (scratch_bo != queue->scratch_bo ||
1494 esgs_ring_bo != queue->esgs_ring_bo ||
1495 gsvs_ring_bo != queue->gsvs_ring_bo ||
1496 tess_factor_ring_bo != queue->tess_factor_ring_bo ||
1497 tess_offchip_ring_bo != queue->tess_offchip_ring_bo || add_sample_positions) {
1498 uint32_t size = 0;
1499 if (gsvs_ring_bo || esgs_ring_bo ||
1500 tess_factor_ring_bo || tess_offchip_ring_bo || add_sample_positions) {
1501 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
1502 if (add_sample_positions)
1503 size += 256; /* 32+16+8+4+2+1 samples * 4 * 2 = 248 bytes. */
1504 }
1505 else if (scratch_bo)
1506 size = 8; /* 2 dword */
1507
1508 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
1509 size,
1510 4096,
1511 RADEON_DOMAIN_VRAM,
1512 RADEON_FLAG_CPU_ACCESS);
1513 if (!descriptor_bo)
1514 goto fail;
1515 } else
1516 descriptor_bo = queue->descriptor_bo;
1517
1518 for(int i = 0; i < 3; ++i) {
1519 struct radeon_winsys_cs *cs = NULL;
1520 cs = queue->device->ws->cs_create(queue->device->ws,
1521 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
1522 if (!cs)
1523 goto fail;
1524
1525 dest_cs[i] = cs;
1526
1527 if (scratch_bo)
1528 queue->device->ws->cs_add_buffer(cs, scratch_bo, 8);
1529
1530 if (esgs_ring_bo)
1531 queue->device->ws->cs_add_buffer(cs, esgs_ring_bo, 8);
1532
1533 if (gsvs_ring_bo)
1534 queue->device->ws->cs_add_buffer(cs, gsvs_ring_bo, 8);
1535
1536 if (tess_factor_ring_bo)
1537 queue->device->ws->cs_add_buffer(cs, tess_factor_ring_bo, 8);
1538
1539 if (tess_offchip_ring_bo)
1540 queue->device->ws->cs_add_buffer(cs, tess_offchip_ring_bo, 8);
1541
1542 if (descriptor_bo)
1543 queue->device->ws->cs_add_buffer(cs, descriptor_bo, 8);
1544
1545 if (descriptor_bo != queue->descriptor_bo) {
1546 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
1547
1548 if (scratch_bo) {
1549 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
1550 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
1551 S_008F04_SWIZZLE_ENABLE(1);
1552 map[0] = scratch_va;
1553 map[1] = rsrc1;
1554 }
1555
1556 if (esgs_ring_bo || gsvs_ring_bo || tess_factor_ring_bo || tess_offchip_ring_bo ||
1557 add_sample_positions)
1558 fill_geom_tess_rings(queue, map, add_sample_positions,
1559 esgs_ring_size, esgs_ring_bo,
1560 gsvs_ring_size, gsvs_ring_bo,
1561 tess_factor_ring_size, tess_factor_ring_bo,
1562 tess_offchip_ring_size, tess_offchip_ring_bo);
1563
1564 queue->device->ws->buffer_unmap(descriptor_bo);
1565 }
1566
1567 if (esgs_ring_bo || gsvs_ring_bo || tess_factor_ring_bo || tess_offchip_ring_bo) {
1568 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
1569 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
1570 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
1571 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
1572 }
1573
1574 if (esgs_ring_bo || gsvs_ring_bo) {
1575 if (queue->device->physical_device->rad_info.chip_class >= CIK) {
1576 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
1577 radeon_emit(cs, esgs_ring_size >> 8);
1578 radeon_emit(cs, gsvs_ring_size >> 8);
1579 } else {
1580 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
1581 radeon_emit(cs, esgs_ring_size >> 8);
1582 radeon_emit(cs, gsvs_ring_size >> 8);
1583 }
1584 }
1585
1586 if (tess_factor_ring_bo) {
1587 uint64_t tf_va = radv_buffer_get_va(tess_factor_ring_bo);
1588 if (queue->device->physical_device->rad_info.chip_class >= CIK) {
1589 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
1590 S_030938_SIZE(tess_factor_ring_size / 4));
1591 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
1592 tf_va >> 8);
1593 if (queue->device->physical_device->rad_info.chip_class >= GFX9) {
1594 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
1595 tf_va >> 40);
1596 }
1597 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM, hs_offchip_param);
1598 } else {
1599 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
1600 S_008988_SIZE(tess_factor_ring_size / 4));
1601 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
1602 tf_va >> 8);
1603 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
1604 hs_offchip_param);
1605 }
1606 }
1607
1608 if (descriptor_bo) {
1609 uint64_t va = radv_buffer_get_va(descriptor_bo);
1610 if (queue->device->physical_device->rad_info.chip_class >= GFX9) {
1611 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
1612 R_00B130_SPI_SHADER_USER_DATA_VS_0,
1613 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
1614 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
1615
1616 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
1617 radeon_set_sh_reg_seq(cs, regs[i], 2);
1618 radeon_emit(cs, va);
1619 radeon_emit(cs, va >> 32);
1620 }
1621 } else {
1622 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
1623 R_00B130_SPI_SHADER_USER_DATA_VS_0,
1624 R_00B230_SPI_SHADER_USER_DATA_GS_0,
1625 R_00B330_SPI_SHADER_USER_DATA_ES_0,
1626 R_00B430_SPI_SHADER_USER_DATA_HS_0,
1627 R_00B530_SPI_SHADER_USER_DATA_LS_0};
1628
1629 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
1630 radeon_set_sh_reg_seq(cs, regs[i], 2);
1631 radeon_emit(cs, va);
1632 radeon_emit(cs, va >> 32);
1633 }
1634 }
1635 }
1636
1637 if (compute_scratch_bo) {
1638 uint64_t scratch_va = radv_buffer_get_va(compute_scratch_bo);
1639 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
1640 S_008F04_SWIZZLE_ENABLE(1);
1641
1642 queue->device->ws->cs_add_buffer(cs, compute_scratch_bo, 8);
1643
1644 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
1645 radeon_emit(cs, scratch_va);
1646 radeon_emit(cs, rsrc1);
1647 }
1648
1649 if (i == 0) {
1650 si_cs_emit_cache_flush(cs,
1651 false,
1652 queue->device->physical_device->rad_info.chip_class,
1653 NULL, 0,
1654 queue->queue_family_index == RING_COMPUTE &&
1655 queue->device->physical_device->rad_info.chip_class >= CIK,
1656 (queue->queue_family_index == RADV_QUEUE_COMPUTE ? RADV_CMD_FLAG_CS_PARTIAL_FLUSH : (RADV_CMD_FLAG_CS_PARTIAL_FLUSH | RADV_CMD_FLAG_PS_PARTIAL_FLUSH)) |
1657 RADV_CMD_FLAG_INV_ICACHE |
1658 RADV_CMD_FLAG_INV_SMEM_L1 |
1659 RADV_CMD_FLAG_INV_VMEM_L1 |
1660 RADV_CMD_FLAG_INV_GLOBAL_L2);
1661 } else if (i == 1) {
1662 si_cs_emit_cache_flush(cs,
1663 false,
1664 queue->device->physical_device->rad_info.chip_class,
1665 NULL, 0,
1666 queue->queue_family_index == RING_COMPUTE &&
1667 queue->device->physical_device->rad_info.chip_class >= CIK,
1668 RADV_CMD_FLAG_INV_ICACHE |
1669 RADV_CMD_FLAG_INV_SMEM_L1 |
1670 RADV_CMD_FLAG_INV_VMEM_L1 |
1671 RADV_CMD_FLAG_INV_GLOBAL_L2);
1672 }
1673
1674 if (!queue->device->ws->cs_finalize(cs))
1675 goto fail;
1676 }
1677
1678 if (queue->initial_full_flush_preamble_cs)
1679 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
1680
1681 if (queue->initial_preamble_cs)
1682 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
1683
1684 if (queue->continue_preamble_cs)
1685 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
1686
1687 queue->initial_full_flush_preamble_cs = dest_cs[0];
1688 queue->initial_preamble_cs = dest_cs[1];
1689 queue->continue_preamble_cs = dest_cs[2];
1690
1691 if (scratch_bo != queue->scratch_bo) {
1692 if (queue->scratch_bo)
1693 queue->device->ws->buffer_destroy(queue->scratch_bo);
1694 queue->scratch_bo = scratch_bo;
1695 queue->scratch_size = scratch_size;
1696 }
1697
1698 if (compute_scratch_bo != queue->compute_scratch_bo) {
1699 if (queue->compute_scratch_bo)
1700 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
1701 queue->compute_scratch_bo = compute_scratch_bo;
1702 queue->compute_scratch_size = compute_scratch_size;
1703 }
1704
1705 if (esgs_ring_bo != queue->esgs_ring_bo) {
1706 if (queue->esgs_ring_bo)
1707 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
1708 queue->esgs_ring_bo = esgs_ring_bo;
1709 queue->esgs_ring_size = esgs_ring_size;
1710 }
1711
1712 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
1713 if (queue->gsvs_ring_bo)
1714 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
1715 queue->gsvs_ring_bo = gsvs_ring_bo;
1716 queue->gsvs_ring_size = gsvs_ring_size;
1717 }
1718
1719 if (tess_factor_ring_bo != queue->tess_factor_ring_bo) {
1720 queue->tess_factor_ring_bo = tess_factor_ring_bo;
1721 }
1722
1723 if (tess_offchip_ring_bo != queue->tess_offchip_ring_bo) {
1724 queue->tess_offchip_ring_bo = tess_offchip_ring_bo;
1725 queue->has_tess_rings = true;
1726 }
1727
1728 if (descriptor_bo != queue->descriptor_bo) {
1729 if (queue->descriptor_bo)
1730 queue->device->ws->buffer_destroy(queue->descriptor_bo);
1731
1732 queue->descriptor_bo = descriptor_bo;
1733 }
1734
1735 if (add_sample_positions)
1736 queue->has_sample_positions = true;
1737
1738 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
1739 *initial_preamble_cs = queue->initial_preamble_cs;
1740 *continue_preamble_cs = queue->continue_preamble_cs;
1741 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
1742 *continue_preamble_cs = NULL;
1743 return VK_SUCCESS;
1744 fail:
1745 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
1746 if (dest_cs[i])
1747 queue->device->ws->cs_destroy(dest_cs[i]);
1748 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
1749 queue->device->ws->buffer_destroy(descriptor_bo);
1750 if (scratch_bo && scratch_bo != queue->scratch_bo)
1751 queue->device->ws->buffer_destroy(scratch_bo);
1752 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
1753 queue->device->ws->buffer_destroy(compute_scratch_bo);
1754 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
1755 queue->device->ws->buffer_destroy(esgs_ring_bo);
1756 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
1757 queue->device->ws->buffer_destroy(gsvs_ring_bo);
1758 if (tess_factor_ring_bo && tess_factor_ring_bo != queue->tess_factor_ring_bo)
1759 queue->device->ws->buffer_destroy(tess_factor_ring_bo);
1760 if (tess_offchip_ring_bo && tess_offchip_ring_bo != queue->tess_offchip_ring_bo)
1761 queue->device->ws->buffer_destroy(tess_offchip_ring_bo);
1762 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
1763 }
1764
1765 static VkResult radv_alloc_sem_counts(struct radv_winsys_sem_counts *counts,
1766 int num_sems,
1767 const VkSemaphore *sems,
1768 bool reset_temp)
1769 {
1770 int syncobj_idx = 0, sem_idx = 0;
1771
1772 if (num_sems == 0)
1773 return VK_SUCCESS;
1774 for (uint32_t i = 0; i < num_sems; i++) {
1775 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
1776
1777 if (sem->temp_syncobj || sem->syncobj)
1778 counts->syncobj_count++;
1779 else
1780 counts->sem_count++;
1781 }
1782
1783 if (counts->syncobj_count) {
1784 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
1785 if (!counts->syncobj)
1786 return VK_ERROR_OUT_OF_HOST_MEMORY;
1787 }
1788
1789 if (counts->sem_count) {
1790 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
1791 if (!counts->sem) {
1792 free(counts->syncobj);
1793 return VK_ERROR_OUT_OF_HOST_MEMORY;
1794 }
1795 }
1796
1797 for (uint32_t i = 0; i < num_sems; i++) {
1798 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
1799
1800 if (sem->temp_syncobj) {
1801 counts->syncobj[syncobj_idx++] = sem->temp_syncobj;
1802 if (reset_temp) {
1803 /* after we wait on a temp import - drop it */
1804 sem->temp_syncobj = 0;
1805 }
1806 }
1807 else if (sem->syncobj)
1808 counts->syncobj[syncobj_idx++] = sem->syncobj;
1809 else {
1810 assert(sem->sem);
1811 counts->sem[sem_idx++] = sem->sem;
1812 }
1813 }
1814
1815 return VK_SUCCESS;
1816 }
1817
1818 void radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
1819 {
1820 free(sem_info->wait.syncobj);
1821 free(sem_info->wait.sem);
1822 free(sem_info->signal.syncobj);
1823 free(sem_info->signal.sem);
1824 }
1825
1826 VkResult radv_alloc_sem_info(struct radv_winsys_sem_info *sem_info,
1827 int num_wait_sems,
1828 const VkSemaphore *wait_sems,
1829 int num_signal_sems,
1830 const VkSemaphore *signal_sems)
1831 {
1832 VkResult ret;
1833 memset(sem_info, 0, sizeof(*sem_info));
1834
1835 ret = radv_alloc_sem_counts(&sem_info->wait, num_wait_sems, wait_sems, true);
1836 if (ret)
1837 return ret;
1838 ret = radv_alloc_sem_counts(&sem_info->signal, num_signal_sems, signal_sems, false);
1839 if (ret)
1840 radv_free_sem_info(sem_info);
1841
1842 /* caller can override these */
1843 sem_info->cs_emit_wait = true;
1844 sem_info->cs_emit_signal = true;
1845 return ret;
1846 }
1847
1848 VkResult radv_QueueSubmit(
1849 VkQueue _queue,
1850 uint32_t submitCount,
1851 const VkSubmitInfo* pSubmits,
1852 VkFence _fence)
1853 {
1854 RADV_FROM_HANDLE(radv_queue, queue, _queue);
1855 RADV_FROM_HANDLE(radv_fence, fence, _fence);
1856 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
1857 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
1858 int ret;
1859 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : UINT32_MAX;
1860 uint32_t scratch_size = 0;
1861 uint32_t compute_scratch_size = 0;
1862 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
1863 struct radeon_winsys_cs *initial_preamble_cs = NULL, *initial_flush_preamble_cs = NULL, *continue_preamble_cs = NULL;
1864 VkResult result;
1865 bool fence_emitted = false;
1866 bool tess_rings_needed = false;
1867 bool sample_positions_needed = false;
1868
1869 /* Do this first so failing to allocate scratch buffers can't result in
1870 * partially executed submissions. */
1871 for (uint32_t i = 0; i < submitCount; i++) {
1872 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
1873 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
1874 pSubmits[i].pCommandBuffers[j]);
1875
1876 scratch_size = MAX2(scratch_size, cmd_buffer->scratch_size_needed);
1877 compute_scratch_size = MAX2(compute_scratch_size,
1878 cmd_buffer->compute_scratch_size_needed);
1879 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
1880 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
1881 tess_rings_needed |= cmd_buffer->tess_rings_needed;
1882 sample_positions_needed |= cmd_buffer->sample_positions_needed;
1883 }
1884 }
1885
1886 result = radv_get_preamble_cs(queue, scratch_size, compute_scratch_size,
1887 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
1888 sample_positions_needed, &initial_flush_preamble_cs,
1889 &initial_preamble_cs, &continue_preamble_cs);
1890 if (result != VK_SUCCESS)
1891 return result;
1892
1893 for (uint32_t i = 0; i < submitCount; i++) {
1894 struct radeon_winsys_cs **cs_array;
1895 bool do_flush = !i || pSubmits[i].pWaitDstStageMask;
1896 bool can_patch = true;
1897 uint32_t advance;
1898 struct radv_winsys_sem_info sem_info;
1899
1900 result = radv_alloc_sem_info(&sem_info,
1901 pSubmits[i].waitSemaphoreCount,
1902 pSubmits[i].pWaitSemaphores,
1903 pSubmits[i].signalSemaphoreCount,
1904 pSubmits[i].pSignalSemaphores);
1905 if (result != VK_SUCCESS)
1906 return result;
1907
1908 if (!pSubmits[i].commandBufferCount) {
1909 if (pSubmits[i].waitSemaphoreCount || pSubmits[i].signalSemaphoreCount) {
1910 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
1911 &queue->device->empty_cs[queue->queue_family_index],
1912 1, NULL, NULL,
1913 &sem_info,
1914 false, base_fence);
1915 if (ret) {
1916 radv_loge("failed to submit CS %d\n", i);
1917 abort();
1918 }
1919 fence_emitted = true;
1920 }
1921 radv_free_sem_info(&sem_info);
1922 continue;
1923 }
1924
1925 cs_array = malloc(sizeof(struct radeon_winsys_cs *) *
1926 (pSubmits[i].commandBufferCount));
1927
1928 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
1929 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
1930 pSubmits[i].pCommandBuffers[j]);
1931 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
1932
1933 cs_array[j] = cmd_buffer->cs;
1934 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
1935 can_patch = false;
1936 }
1937
1938 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j += advance) {
1939 struct radeon_winsys_cs *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
1940 advance = MIN2(max_cs_submission,
1941 pSubmits[i].commandBufferCount - j);
1942
1943 if (queue->device->trace_bo)
1944 *queue->device->trace_id_ptr = 0;
1945
1946 sem_info.cs_emit_wait = j == 0;
1947 sem_info.cs_emit_signal = j + advance == pSubmits[i].commandBufferCount;
1948
1949 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
1950 advance, initial_preamble, continue_preamble_cs,
1951 &sem_info,
1952 can_patch, base_fence);
1953
1954 if (ret) {
1955 radv_loge("failed to submit CS %d\n", i);
1956 abort();
1957 }
1958 fence_emitted = true;
1959 if (queue->device->trace_bo) {
1960 radv_check_gpu_hangs(queue, cs_array[j]);
1961 }
1962 }
1963
1964 radv_free_sem_info(&sem_info);
1965 free(cs_array);
1966 }
1967
1968 if (fence) {
1969 if (!fence_emitted) {
1970 struct radv_winsys_sem_info sem_info = {0};
1971 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
1972 &queue->device->empty_cs[queue->queue_family_index],
1973 1, NULL, NULL, &sem_info,
1974 false, base_fence);
1975 }
1976 fence->submitted = true;
1977 }
1978
1979 return VK_SUCCESS;
1980 }
1981
1982 VkResult radv_QueueWaitIdle(
1983 VkQueue _queue)
1984 {
1985 RADV_FROM_HANDLE(radv_queue, queue, _queue);
1986
1987 queue->device->ws->ctx_wait_idle(queue->hw_ctx,
1988 radv_queue_family_to_ring(queue->queue_family_index),
1989 queue->queue_idx);
1990 return VK_SUCCESS;
1991 }
1992
1993 VkResult radv_DeviceWaitIdle(
1994 VkDevice _device)
1995 {
1996 RADV_FROM_HANDLE(radv_device, device, _device);
1997
1998 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
1999 for (unsigned q = 0; q < device->queue_count[i]; q++) {
2000 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
2001 }
2002 }
2003 return VK_SUCCESS;
2004 }
2005
2006 PFN_vkVoidFunction radv_GetInstanceProcAddr(
2007 VkInstance instance,
2008 const char* pName)
2009 {
2010 return radv_lookup_entrypoint(pName);
2011 }
2012
2013 /* The loader wants us to expose a second GetInstanceProcAddr function
2014 * to work around certain LD_PRELOAD issues seen in apps.
2015 */
2016 PUBLIC
2017 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
2018 VkInstance instance,
2019 const char* pName);
2020
2021 PUBLIC
2022 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
2023 VkInstance instance,
2024 const char* pName)
2025 {
2026 return radv_GetInstanceProcAddr(instance, pName);
2027 }
2028
2029 PFN_vkVoidFunction radv_GetDeviceProcAddr(
2030 VkDevice device,
2031 const char* pName)
2032 {
2033 return radv_lookup_entrypoint(pName);
2034 }
2035
2036 bool radv_get_memory_fd(struct radv_device *device,
2037 struct radv_device_memory *memory,
2038 int *pFD)
2039 {
2040 struct radeon_bo_metadata metadata;
2041
2042 if (memory->image) {
2043 radv_init_metadata(device, memory->image, &metadata);
2044 device->ws->buffer_set_metadata(memory->bo, &metadata);
2045 }
2046
2047 return device->ws->buffer_get_fd(device->ws, memory->bo,
2048 pFD);
2049 }
2050
2051 VkResult radv_alloc_memory(VkDevice _device,
2052 const VkMemoryAllocateInfo* pAllocateInfo,
2053 const VkAllocationCallbacks* pAllocator,
2054 enum radv_mem_flags_bits mem_flags,
2055 VkDeviceMemory* pMem)
2056 {
2057 RADV_FROM_HANDLE(radv_device, device, _device);
2058 struct radv_device_memory *mem;
2059 VkResult result;
2060 enum radeon_bo_domain domain;
2061 uint32_t flags = 0;
2062
2063 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
2064
2065 if (pAllocateInfo->allocationSize == 0) {
2066 /* Apparently, this is allowed */
2067 *pMem = VK_NULL_HANDLE;
2068 return VK_SUCCESS;
2069 }
2070
2071 const VkImportMemoryFdInfoKHR *import_info =
2072 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
2073 const VkMemoryDedicatedAllocateInfoKHR *dedicate_info =
2074 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO_KHR);
2075
2076 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
2077 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2078 if (mem == NULL)
2079 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2080
2081 if (dedicate_info) {
2082 mem->image = radv_image_from_handle(dedicate_info->image);
2083 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
2084 } else {
2085 mem->image = NULL;
2086 mem->buffer = NULL;
2087 }
2088
2089 if (import_info) {
2090 assert(import_info->handleType ==
2091 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR);
2092 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
2093 NULL, NULL);
2094 if (!mem->bo) {
2095 result = VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR;
2096 goto fail;
2097 } else {
2098 close(import_info->fd);
2099 goto out_success;
2100 }
2101 }
2102
2103 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
2104 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_WRITE_COMBINE ||
2105 pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_CACHED)
2106 domain = RADEON_DOMAIN_GTT;
2107 else
2108 domain = RADEON_DOMAIN_VRAM;
2109
2110 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_VRAM)
2111 flags |= RADEON_FLAG_NO_CPU_ACCESS;
2112 else
2113 flags |= RADEON_FLAG_CPU_ACCESS;
2114
2115 if (pAllocateInfo->memoryTypeIndex == RADV_MEM_TYPE_GTT_WRITE_COMBINE)
2116 flags |= RADEON_FLAG_GTT_WC;
2117
2118 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
2119 domain, flags);
2120
2121 if (!mem->bo) {
2122 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
2123 goto fail;
2124 }
2125 mem->type_index = pAllocateInfo->memoryTypeIndex;
2126 out_success:
2127 *pMem = radv_device_memory_to_handle(mem);
2128
2129 return VK_SUCCESS;
2130
2131 fail:
2132 vk_free2(&device->alloc, pAllocator, mem);
2133
2134 return result;
2135 }
2136
2137 VkResult radv_AllocateMemory(
2138 VkDevice _device,
2139 const VkMemoryAllocateInfo* pAllocateInfo,
2140 const VkAllocationCallbacks* pAllocator,
2141 VkDeviceMemory* pMem)
2142 {
2143 return radv_alloc_memory(_device, pAllocateInfo, pAllocator, 0, pMem);
2144 }
2145
2146 void radv_FreeMemory(
2147 VkDevice _device,
2148 VkDeviceMemory _mem,
2149 const VkAllocationCallbacks* pAllocator)
2150 {
2151 RADV_FROM_HANDLE(radv_device, device, _device);
2152 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
2153
2154 if (mem == NULL)
2155 return;
2156
2157 device->ws->buffer_destroy(mem->bo);
2158 mem->bo = NULL;
2159
2160 vk_free2(&device->alloc, pAllocator, mem);
2161 }
2162
2163 VkResult radv_MapMemory(
2164 VkDevice _device,
2165 VkDeviceMemory _memory,
2166 VkDeviceSize offset,
2167 VkDeviceSize size,
2168 VkMemoryMapFlags flags,
2169 void** ppData)
2170 {
2171 RADV_FROM_HANDLE(radv_device, device, _device);
2172 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
2173
2174 if (mem == NULL) {
2175 *ppData = NULL;
2176 return VK_SUCCESS;
2177 }
2178
2179 *ppData = device->ws->buffer_map(mem->bo);
2180 if (*ppData) {
2181 *ppData += offset;
2182 return VK_SUCCESS;
2183 }
2184
2185 return VK_ERROR_MEMORY_MAP_FAILED;
2186 }
2187
2188 void radv_UnmapMemory(
2189 VkDevice _device,
2190 VkDeviceMemory _memory)
2191 {
2192 RADV_FROM_HANDLE(radv_device, device, _device);
2193 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
2194
2195 if (mem == NULL)
2196 return;
2197
2198 device->ws->buffer_unmap(mem->bo);
2199 }
2200
2201 VkResult radv_FlushMappedMemoryRanges(
2202 VkDevice _device,
2203 uint32_t memoryRangeCount,
2204 const VkMappedMemoryRange* pMemoryRanges)
2205 {
2206 return VK_SUCCESS;
2207 }
2208
2209 VkResult radv_InvalidateMappedMemoryRanges(
2210 VkDevice _device,
2211 uint32_t memoryRangeCount,
2212 const VkMappedMemoryRange* pMemoryRanges)
2213 {
2214 return VK_SUCCESS;
2215 }
2216
2217 void radv_GetBufferMemoryRequirements(
2218 VkDevice device,
2219 VkBuffer _buffer,
2220 VkMemoryRequirements* pMemoryRequirements)
2221 {
2222 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
2223
2224 pMemoryRequirements->memoryTypeBits = (1u << RADV_MEM_TYPE_COUNT) - 1;
2225
2226 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
2227 pMemoryRequirements->alignment = 4096;
2228 else
2229 pMemoryRequirements->alignment = 16;
2230
2231 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
2232 }
2233
2234 void radv_GetBufferMemoryRequirements2KHR(
2235 VkDevice device,
2236 const VkBufferMemoryRequirementsInfo2KHR* pInfo,
2237 VkMemoryRequirements2KHR* pMemoryRequirements)
2238 {
2239 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
2240 &pMemoryRequirements->memoryRequirements);
2241
2242 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2243 switch (ext->sType) {
2244 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
2245 VkMemoryDedicatedRequirementsKHR *req =
2246 (VkMemoryDedicatedRequirementsKHR *) ext;
2247 req->requiresDedicatedAllocation = false;
2248 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
2249 break;
2250 }
2251 default:
2252 break;
2253 }
2254 }
2255 }
2256
2257 void radv_GetImageMemoryRequirements(
2258 VkDevice device,
2259 VkImage _image,
2260 VkMemoryRequirements* pMemoryRequirements)
2261 {
2262 RADV_FROM_HANDLE(radv_image, image, _image);
2263
2264 pMemoryRequirements->memoryTypeBits = (1u << RADV_MEM_TYPE_COUNT) - 1;
2265
2266 pMemoryRequirements->size = image->size;
2267 pMemoryRequirements->alignment = image->alignment;
2268 }
2269
2270 void radv_GetImageMemoryRequirements2KHR(
2271 VkDevice device,
2272 const VkImageMemoryRequirementsInfo2KHR* pInfo,
2273 VkMemoryRequirements2KHR* pMemoryRequirements)
2274 {
2275 radv_GetImageMemoryRequirements(device, pInfo->image,
2276 &pMemoryRequirements->memoryRequirements);
2277
2278 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
2279
2280 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
2281 switch (ext->sType) {
2282 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
2283 VkMemoryDedicatedRequirementsKHR *req =
2284 (VkMemoryDedicatedRequirementsKHR *) ext;
2285 req->requiresDedicatedAllocation = image->shareable;
2286 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
2287 break;
2288 }
2289 default:
2290 break;
2291 }
2292 }
2293 }
2294
2295 void radv_GetImageSparseMemoryRequirements(
2296 VkDevice device,
2297 VkImage image,
2298 uint32_t* pSparseMemoryRequirementCount,
2299 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
2300 {
2301 stub();
2302 }
2303
2304 void radv_GetImageSparseMemoryRequirements2KHR(
2305 VkDevice device,
2306 const VkImageSparseMemoryRequirementsInfo2KHR* pInfo,
2307 uint32_t* pSparseMemoryRequirementCount,
2308 VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements)
2309 {
2310 stub();
2311 }
2312
2313 void radv_GetDeviceMemoryCommitment(
2314 VkDevice device,
2315 VkDeviceMemory memory,
2316 VkDeviceSize* pCommittedMemoryInBytes)
2317 {
2318 *pCommittedMemoryInBytes = 0;
2319 }
2320
2321 VkResult radv_BindBufferMemory2KHR(VkDevice device,
2322 uint32_t bindInfoCount,
2323 const VkBindBufferMemoryInfoKHR *pBindInfos)
2324 {
2325 for (uint32_t i = 0; i < bindInfoCount; ++i) {
2326 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
2327 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
2328
2329 if (mem) {
2330 buffer->bo = mem->bo;
2331 buffer->offset = pBindInfos[i].memoryOffset;
2332 } else {
2333 buffer->bo = NULL;
2334 }
2335 }
2336 return VK_SUCCESS;
2337 }
2338
2339 VkResult radv_BindBufferMemory(
2340 VkDevice device,
2341 VkBuffer buffer,
2342 VkDeviceMemory memory,
2343 VkDeviceSize memoryOffset)
2344 {
2345 const VkBindBufferMemoryInfoKHR info = {
2346 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR,
2347 .buffer = buffer,
2348 .memory = memory,
2349 .memoryOffset = memoryOffset
2350 };
2351
2352 return radv_BindBufferMemory2KHR(device, 1, &info);
2353 }
2354
2355 VkResult radv_BindImageMemory2KHR(VkDevice device,
2356 uint32_t bindInfoCount,
2357 const VkBindImageMemoryInfoKHR *pBindInfos)
2358 {
2359 for (uint32_t i = 0; i < bindInfoCount; ++i) {
2360 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
2361 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
2362
2363 if (mem) {
2364 image->bo = mem->bo;
2365 image->offset = pBindInfos[i].memoryOffset;
2366 } else {
2367 image->bo = NULL;
2368 image->offset = 0;
2369 }
2370 }
2371 return VK_SUCCESS;
2372 }
2373
2374
2375 VkResult radv_BindImageMemory(
2376 VkDevice device,
2377 VkImage image,
2378 VkDeviceMemory memory,
2379 VkDeviceSize memoryOffset)
2380 {
2381 const VkBindImageMemoryInfoKHR info = {
2382 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHR,
2383 .image = image,
2384 .memory = memory,
2385 .memoryOffset = memoryOffset
2386 };
2387
2388 return radv_BindImageMemory2KHR(device, 1, &info);
2389 }
2390
2391
2392 static void
2393 radv_sparse_buffer_bind_memory(struct radv_device *device,
2394 const VkSparseBufferMemoryBindInfo *bind)
2395 {
2396 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
2397
2398 for (uint32_t i = 0; i < bind->bindCount; ++i) {
2399 struct radv_device_memory *mem = NULL;
2400
2401 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
2402 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
2403
2404 device->ws->buffer_virtual_bind(buffer->bo,
2405 bind->pBinds[i].resourceOffset,
2406 bind->pBinds[i].size,
2407 mem ? mem->bo : NULL,
2408 bind->pBinds[i].memoryOffset);
2409 }
2410 }
2411
2412 static void
2413 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
2414 const VkSparseImageOpaqueMemoryBindInfo *bind)
2415 {
2416 RADV_FROM_HANDLE(radv_image, image, bind->image);
2417
2418 for (uint32_t i = 0; i < bind->bindCount; ++i) {
2419 struct radv_device_memory *mem = NULL;
2420
2421 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
2422 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
2423
2424 device->ws->buffer_virtual_bind(image->bo,
2425 bind->pBinds[i].resourceOffset,
2426 bind->pBinds[i].size,
2427 mem ? mem->bo : NULL,
2428 bind->pBinds[i].memoryOffset);
2429 }
2430 }
2431
2432 VkResult radv_QueueBindSparse(
2433 VkQueue _queue,
2434 uint32_t bindInfoCount,
2435 const VkBindSparseInfo* pBindInfo,
2436 VkFence _fence)
2437 {
2438 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2439 RADV_FROM_HANDLE(radv_queue, queue, _queue);
2440 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
2441 bool fence_emitted = false;
2442
2443 for (uint32_t i = 0; i < bindInfoCount; ++i) {
2444 struct radv_winsys_sem_info sem_info;
2445 for (uint32_t j = 0; j < pBindInfo[i].bufferBindCount; ++j) {
2446 radv_sparse_buffer_bind_memory(queue->device,
2447 pBindInfo[i].pBufferBinds + j);
2448 }
2449
2450 for (uint32_t j = 0; j < pBindInfo[i].imageOpaqueBindCount; ++j) {
2451 radv_sparse_image_opaque_bind_memory(queue->device,
2452 pBindInfo[i].pImageOpaqueBinds + j);
2453 }
2454
2455 VkResult result;
2456 result = radv_alloc_sem_info(&sem_info,
2457 pBindInfo[i].waitSemaphoreCount,
2458 pBindInfo[i].pWaitSemaphores,
2459 pBindInfo[i].signalSemaphoreCount,
2460 pBindInfo[i].pSignalSemaphores);
2461 if (result != VK_SUCCESS)
2462 return result;
2463
2464 if (pBindInfo[i].waitSemaphoreCount || pBindInfo[i].signalSemaphoreCount) {
2465 queue->device->ws->cs_submit(queue->hw_ctx, queue->queue_idx,
2466 &queue->device->empty_cs[queue->queue_family_index],
2467 1, NULL, NULL,
2468 &sem_info,
2469 false, base_fence);
2470 fence_emitted = true;
2471 if (fence)
2472 fence->submitted = true;
2473 }
2474
2475 radv_free_sem_info(&sem_info);
2476
2477 }
2478
2479 if (fence && !fence_emitted) {
2480 fence->signalled = true;
2481 }
2482
2483 return VK_SUCCESS;
2484 }
2485
2486 VkResult radv_CreateFence(
2487 VkDevice _device,
2488 const VkFenceCreateInfo* pCreateInfo,
2489 const VkAllocationCallbacks* pAllocator,
2490 VkFence* pFence)
2491 {
2492 RADV_FROM_HANDLE(radv_device, device, _device);
2493 struct radv_fence *fence = vk_alloc2(&device->alloc, pAllocator,
2494 sizeof(*fence), 8,
2495 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2496
2497 if (!fence)
2498 return VK_ERROR_OUT_OF_HOST_MEMORY;
2499
2500 memset(fence, 0, sizeof(*fence));
2501 fence->submitted = false;
2502 fence->signalled = !!(pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT);
2503 fence->fence = device->ws->create_fence();
2504 if (!fence->fence) {
2505 vk_free2(&device->alloc, pAllocator, fence);
2506 return VK_ERROR_OUT_OF_HOST_MEMORY;
2507 }
2508
2509 *pFence = radv_fence_to_handle(fence);
2510
2511 return VK_SUCCESS;
2512 }
2513
2514 void radv_DestroyFence(
2515 VkDevice _device,
2516 VkFence _fence,
2517 const VkAllocationCallbacks* pAllocator)
2518 {
2519 RADV_FROM_HANDLE(radv_device, device, _device);
2520 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2521
2522 if (!fence)
2523 return;
2524 device->ws->destroy_fence(fence->fence);
2525 vk_free2(&device->alloc, pAllocator, fence);
2526 }
2527
2528 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
2529 {
2530 uint64_t current_time;
2531 struct timespec tv;
2532
2533 clock_gettime(CLOCK_MONOTONIC, &tv);
2534 current_time = tv.tv_nsec + tv.tv_sec*1000000000ull;
2535
2536 timeout = MIN2(UINT64_MAX - current_time, timeout);
2537
2538 return current_time + timeout;
2539 }
2540
2541 VkResult radv_WaitForFences(
2542 VkDevice _device,
2543 uint32_t fenceCount,
2544 const VkFence* pFences,
2545 VkBool32 waitAll,
2546 uint64_t timeout)
2547 {
2548 RADV_FROM_HANDLE(radv_device, device, _device);
2549 timeout = radv_get_absolute_timeout(timeout);
2550
2551 if (!waitAll && fenceCount > 1) {
2552 fprintf(stderr, "radv: WaitForFences without waitAll not implemented yet\n");
2553 }
2554
2555 for (uint32_t i = 0; i < fenceCount; ++i) {
2556 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
2557 bool expired = false;
2558
2559 if (fence->signalled)
2560 continue;
2561
2562 if (!fence->submitted)
2563 return VK_TIMEOUT;
2564
2565 expired = device->ws->fence_wait(device->ws, fence->fence, true, timeout);
2566 if (!expired)
2567 return VK_TIMEOUT;
2568
2569 fence->signalled = true;
2570 }
2571
2572 return VK_SUCCESS;
2573 }
2574
2575 VkResult radv_ResetFences(VkDevice device,
2576 uint32_t fenceCount,
2577 const VkFence *pFences)
2578 {
2579 for (unsigned i = 0; i < fenceCount; ++i) {
2580 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
2581 fence->submitted = fence->signalled = false;
2582 }
2583
2584 return VK_SUCCESS;
2585 }
2586
2587 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
2588 {
2589 RADV_FROM_HANDLE(radv_device, device, _device);
2590 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2591
2592 if (fence->signalled)
2593 return VK_SUCCESS;
2594 if (!fence->submitted)
2595 return VK_NOT_READY;
2596
2597 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
2598 return VK_NOT_READY;
2599
2600 return VK_SUCCESS;
2601 }
2602
2603
2604 // Queue semaphore functions
2605
2606 VkResult radv_CreateSemaphore(
2607 VkDevice _device,
2608 const VkSemaphoreCreateInfo* pCreateInfo,
2609 const VkAllocationCallbacks* pAllocator,
2610 VkSemaphore* pSemaphore)
2611 {
2612 RADV_FROM_HANDLE(radv_device, device, _device);
2613 const VkExportSemaphoreCreateInfoKHR *export =
2614 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO_KHR);
2615 VkExternalSemaphoreHandleTypeFlagsKHR handleTypes =
2616 export ? export->handleTypes : 0;
2617
2618 struct radv_semaphore *sem = vk_alloc2(&device->alloc, pAllocator,
2619 sizeof(*sem), 8,
2620 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2621 if (!sem)
2622 return VK_ERROR_OUT_OF_HOST_MEMORY;
2623
2624 sem->temp_syncobj = 0;
2625 /* create a syncobject if we are going to export this semaphore */
2626 if (handleTypes) {
2627 assert (device->physical_device->rad_info.has_syncobj);
2628 assert (handleTypes == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR);
2629 int ret = device->ws->create_syncobj(device->ws, &sem->syncobj);
2630 if (ret) {
2631 vk_free2(&device->alloc, pAllocator, sem);
2632 return VK_ERROR_OUT_OF_HOST_MEMORY;
2633 }
2634 sem->sem = NULL;
2635 } else {
2636 sem->sem = device->ws->create_sem(device->ws);
2637 if (!sem->sem) {
2638 vk_free2(&device->alloc, pAllocator, sem);
2639 return VK_ERROR_OUT_OF_HOST_MEMORY;
2640 }
2641 sem->syncobj = 0;
2642 }
2643
2644 *pSemaphore = radv_semaphore_to_handle(sem);
2645 return VK_SUCCESS;
2646 }
2647
2648 void radv_DestroySemaphore(
2649 VkDevice _device,
2650 VkSemaphore _semaphore,
2651 const VkAllocationCallbacks* pAllocator)
2652 {
2653 RADV_FROM_HANDLE(radv_device, device, _device);
2654 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
2655 if (!_semaphore)
2656 return;
2657
2658 if (sem->syncobj)
2659 device->ws->destroy_syncobj(device->ws, sem->syncobj);
2660 else
2661 device->ws->destroy_sem(sem->sem);
2662 vk_free2(&device->alloc, pAllocator, sem);
2663 }
2664
2665 VkResult radv_CreateEvent(
2666 VkDevice _device,
2667 const VkEventCreateInfo* pCreateInfo,
2668 const VkAllocationCallbacks* pAllocator,
2669 VkEvent* pEvent)
2670 {
2671 RADV_FROM_HANDLE(radv_device, device, _device);
2672 struct radv_event *event = vk_alloc2(&device->alloc, pAllocator,
2673 sizeof(*event), 8,
2674 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2675
2676 if (!event)
2677 return VK_ERROR_OUT_OF_HOST_MEMORY;
2678
2679 event->bo = device->ws->buffer_create(device->ws, 8, 8,
2680 RADEON_DOMAIN_GTT,
2681 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS);
2682 if (!event->bo) {
2683 vk_free2(&device->alloc, pAllocator, event);
2684 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
2685 }
2686
2687 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
2688
2689 *pEvent = radv_event_to_handle(event);
2690
2691 return VK_SUCCESS;
2692 }
2693
2694 void radv_DestroyEvent(
2695 VkDevice _device,
2696 VkEvent _event,
2697 const VkAllocationCallbacks* pAllocator)
2698 {
2699 RADV_FROM_HANDLE(radv_device, device, _device);
2700 RADV_FROM_HANDLE(radv_event, event, _event);
2701
2702 if (!event)
2703 return;
2704 device->ws->buffer_destroy(event->bo);
2705 vk_free2(&device->alloc, pAllocator, event);
2706 }
2707
2708 VkResult radv_GetEventStatus(
2709 VkDevice _device,
2710 VkEvent _event)
2711 {
2712 RADV_FROM_HANDLE(radv_event, event, _event);
2713
2714 if (*event->map == 1)
2715 return VK_EVENT_SET;
2716 return VK_EVENT_RESET;
2717 }
2718
2719 VkResult radv_SetEvent(
2720 VkDevice _device,
2721 VkEvent _event)
2722 {
2723 RADV_FROM_HANDLE(radv_event, event, _event);
2724 *event->map = 1;
2725
2726 return VK_SUCCESS;
2727 }
2728
2729 VkResult radv_ResetEvent(
2730 VkDevice _device,
2731 VkEvent _event)
2732 {
2733 RADV_FROM_HANDLE(radv_event, event, _event);
2734 *event->map = 0;
2735
2736 return VK_SUCCESS;
2737 }
2738
2739 VkResult radv_CreateBuffer(
2740 VkDevice _device,
2741 const VkBufferCreateInfo* pCreateInfo,
2742 const VkAllocationCallbacks* pAllocator,
2743 VkBuffer* pBuffer)
2744 {
2745 RADV_FROM_HANDLE(radv_device, device, _device);
2746 struct radv_buffer *buffer;
2747
2748 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
2749
2750 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
2751 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2752 if (buffer == NULL)
2753 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
2754
2755 buffer->size = pCreateInfo->size;
2756 buffer->usage = pCreateInfo->usage;
2757 buffer->bo = NULL;
2758 buffer->offset = 0;
2759 buffer->flags = pCreateInfo->flags;
2760
2761 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
2762 buffer->bo = device->ws->buffer_create(device->ws,
2763 align64(buffer->size, 4096),
2764 4096, 0, RADEON_FLAG_VIRTUAL);
2765 if (!buffer->bo) {
2766 vk_free2(&device->alloc, pAllocator, buffer);
2767 return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
2768 }
2769 }
2770
2771 *pBuffer = radv_buffer_to_handle(buffer);
2772
2773 return VK_SUCCESS;
2774 }
2775
2776 void radv_DestroyBuffer(
2777 VkDevice _device,
2778 VkBuffer _buffer,
2779 const VkAllocationCallbacks* pAllocator)
2780 {
2781 RADV_FROM_HANDLE(radv_device, device, _device);
2782 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
2783
2784 if (!buffer)
2785 return;
2786
2787 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
2788 device->ws->buffer_destroy(buffer->bo);
2789
2790 vk_free2(&device->alloc, pAllocator, buffer);
2791 }
2792
2793 static inline unsigned
2794 si_tile_mode_index(const struct radv_image *image, unsigned level, bool stencil)
2795 {
2796 if (stencil)
2797 return image->surface.u.legacy.stencil_tiling_index[level];
2798 else
2799 return image->surface.u.legacy.tiling_index[level];
2800 }
2801
2802 static uint32_t radv_surface_layer_count(struct radv_image_view *iview)
2803 {
2804 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : iview->layer_count;
2805 }
2806
2807 static void
2808 radv_initialise_color_surface(struct radv_device *device,
2809 struct radv_color_buffer_info *cb,
2810 struct radv_image_view *iview)
2811 {
2812 const struct vk_format_description *desc;
2813 unsigned ntype, format, swap, endian;
2814 unsigned blend_clamp = 0, blend_bypass = 0;
2815 uint64_t va;
2816 const struct radeon_surf *surf = &iview->image->surface;
2817
2818 desc = vk_format_description(iview->vk_format);
2819
2820 memset(cb, 0, sizeof(*cb));
2821
2822 /* Intensity is implemented as Red, so treat it that way. */
2823 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
2824
2825 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
2826
2827 cb->cb_color_base = va >> 8;
2828
2829 if (device->physical_device->rad_info.chip_class >= GFX9) {
2830 struct gfx9_surf_meta_flags meta;
2831 if (iview->image->dcc_offset)
2832 meta = iview->image->surface.u.gfx9.dcc;
2833 else
2834 meta = iview->image->surface.u.gfx9.cmask;
2835
2836 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(iview->image->surface.u.gfx9.surf.swizzle_mode) |
2837 S_028C74_FMASK_SW_MODE(iview->image->surface.u.gfx9.fmask.swizzle_mode) |
2838 S_028C74_RB_ALIGNED(meta.rb_aligned) |
2839 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
2840
2841 cb->cb_color_base += iview->image->surface.u.gfx9.surf_offset >> 8;
2842 cb->cb_color_base |= iview->image->surface.tile_swizzle;
2843 } else {
2844 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
2845 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
2846
2847 cb->cb_color_base += level_info->offset >> 8;
2848 if (level_info->mode == RADEON_SURF_MODE_2D)
2849 cb->cb_color_base |= iview->image->surface.tile_swizzle;
2850
2851 pitch_tile_max = level_info->nblk_x / 8 - 1;
2852 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
2853 tile_mode_index = si_tile_mode_index(iview->image, iview->base_mip, false);
2854
2855 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
2856 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
2857 cb->cb_color_cmask_slice = iview->image->cmask.slice_tile_max;
2858
2859 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
2860 cb->micro_tile_mode = iview->image->surface.micro_tile_mode;
2861
2862 if (iview->image->fmask.size) {
2863 if (device->physical_device->rad_info.chip_class >= CIK)
2864 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(iview->image->fmask.pitch_in_pixels / 8 - 1);
2865 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(iview->image->fmask.tile_mode_index);
2866 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(iview->image->fmask.slice_tile_max);
2867 } else {
2868 /* This must be set for fast clear to work without FMASK. */
2869 if (device->physical_device->rad_info.chip_class >= CIK)
2870 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
2871 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
2872 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
2873 }
2874 }
2875
2876 /* CMASK variables */
2877 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
2878 va += iview->image->cmask.offset;
2879 cb->cb_color_cmask = va >> 8;
2880
2881 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
2882 va += iview->image->dcc_offset;
2883 cb->cb_dcc_base = va >> 8;
2884 cb->cb_dcc_base |= iview->image->surface.tile_swizzle;
2885
2886 uint32_t max_slice = radv_surface_layer_count(iview);
2887 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
2888 S_028C6C_SLICE_MAX(iview->base_layer + max_slice - 1);
2889
2890 if (iview->image->info.samples > 1) {
2891 unsigned log_samples = util_logbase2(iview->image->info.samples);
2892
2893 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
2894 S_028C74_NUM_FRAGMENTS(log_samples);
2895 }
2896
2897 if (iview->image->fmask.size) {
2898 va = radv_buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask.offset;
2899 cb->cb_color_fmask = va >> 8;
2900 cb->cb_color_fmask |= iview->image->fmask.tile_swizzle;
2901 } else {
2902 cb->cb_color_fmask = cb->cb_color_base;
2903 }
2904
2905 ntype = radv_translate_color_numformat(iview->vk_format,
2906 desc,
2907 vk_format_get_first_non_void_channel(iview->vk_format));
2908 format = radv_translate_colorformat(iview->vk_format);
2909 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
2910 radv_finishme("Illegal color\n");
2911 swap = radv_translate_colorswap(iview->vk_format, FALSE);
2912 endian = radv_colorformat_endian_swap(format);
2913
2914 /* blend clamp should be set for all NORM/SRGB types */
2915 if (ntype == V_028C70_NUMBER_UNORM ||
2916 ntype == V_028C70_NUMBER_SNORM ||
2917 ntype == V_028C70_NUMBER_SRGB)
2918 blend_clamp = 1;
2919
2920 /* set blend bypass according to docs if SINT/UINT or
2921 8/24 COLOR variants */
2922 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
2923 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
2924 format == V_028C70_COLOR_X24_8_32_FLOAT) {
2925 blend_clamp = 0;
2926 blend_bypass = 1;
2927 }
2928 #if 0
2929 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
2930 (format == V_028C70_COLOR_8 ||
2931 format == V_028C70_COLOR_8_8 ||
2932 format == V_028C70_COLOR_8_8_8_8))
2933 ->color_is_int8 = true;
2934 #endif
2935 cb->cb_color_info = S_028C70_FORMAT(format) |
2936 S_028C70_COMP_SWAP(swap) |
2937 S_028C70_BLEND_CLAMP(blend_clamp) |
2938 S_028C70_BLEND_BYPASS(blend_bypass) |
2939 S_028C70_SIMPLE_FLOAT(1) |
2940 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
2941 ntype != V_028C70_NUMBER_SNORM &&
2942 ntype != V_028C70_NUMBER_SRGB &&
2943 format != V_028C70_COLOR_8_24 &&
2944 format != V_028C70_COLOR_24_8) |
2945 S_028C70_NUMBER_TYPE(ntype) |
2946 S_028C70_ENDIAN(endian);
2947 if ((iview->image->info.samples > 1) && iview->image->fmask.size) {
2948 cb->cb_color_info |= S_028C70_COMPRESSION(1);
2949 if (device->physical_device->rad_info.chip_class == SI) {
2950 unsigned fmask_bankh = util_logbase2(iview->image->fmask.bank_height);
2951 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
2952 }
2953 }
2954
2955 if (iview->image->cmask.size &&
2956 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
2957 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
2958
2959 if (radv_vi_dcc_enabled(iview->image, iview->base_mip))
2960 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
2961
2962 if (device->physical_device->rad_info.chip_class >= VI) {
2963 unsigned max_uncompressed_block_size = 2;
2964 if (iview->image->info.samples > 1) {
2965 if (iview->image->surface.bpe == 1)
2966 max_uncompressed_block_size = 0;
2967 else if (iview->image->surface.bpe == 2)
2968 max_uncompressed_block_size = 1;
2969 }
2970
2971 cb->cb_dcc_control = S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
2972 S_028C78_INDEPENDENT_64B_BLOCKS(1);
2973 }
2974
2975 /* This must be set for fast clear to work without FMASK. */
2976 if (!iview->image->fmask.size &&
2977 device->physical_device->rad_info.chip_class == SI) {
2978 unsigned bankh = util_logbase2(iview->image->surface.u.legacy.bankh);
2979 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
2980 }
2981
2982 if (device->physical_device->rad_info.chip_class >= GFX9) {
2983 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
2984 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
2985
2986 cb->cb_color_view |= S_028C6C_MIP_LEVEL(iview->base_mip);
2987 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
2988 S_028C74_RESOURCE_TYPE(iview->image->surface.u.gfx9.resource_type);
2989 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(iview->extent.width - 1) |
2990 S_028C68_MIP0_HEIGHT(iview->extent.height - 1) |
2991 S_028C68_MAX_MIP(iview->image->info.levels - 1);
2992
2993 cb->gfx9_epitch = S_0287A0_EPITCH(iview->image->surface.u.gfx9.surf.epitch);
2994
2995 }
2996 }
2997
2998 static void
2999 radv_initialise_ds_surface(struct radv_device *device,
3000 struct radv_ds_buffer_info *ds,
3001 struct radv_image_view *iview)
3002 {
3003 unsigned level = iview->base_mip;
3004 unsigned format, stencil_format;
3005 uint64_t va, s_offs, z_offs;
3006 bool stencil_only = false;
3007 memset(ds, 0, sizeof(*ds));
3008 switch (iview->image->vk_format) {
3009 case VK_FORMAT_D24_UNORM_S8_UINT:
3010 case VK_FORMAT_X8_D24_UNORM_PACK32:
3011 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
3012 ds->offset_scale = 2.0f;
3013 break;
3014 case VK_FORMAT_D16_UNORM:
3015 case VK_FORMAT_D16_UNORM_S8_UINT:
3016 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
3017 ds->offset_scale = 4.0f;
3018 break;
3019 case VK_FORMAT_D32_SFLOAT:
3020 case VK_FORMAT_D32_SFLOAT_S8_UINT:
3021 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
3022 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
3023 ds->offset_scale = 1.0f;
3024 break;
3025 case VK_FORMAT_S8_UINT:
3026 stencil_only = true;
3027 break;
3028 default:
3029 break;
3030 }
3031
3032 format = radv_translate_dbformat(iview->image->vk_format);
3033 stencil_format = iview->image->surface.has_stencil ?
3034 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
3035
3036 uint32_t max_slice = radv_surface_layer_count(iview);
3037 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
3038 S_028008_SLICE_MAX(iview->base_layer + max_slice - 1);
3039
3040 ds->db_htile_data_base = 0;
3041 ds->db_htile_surface = 0;
3042
3043 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
3044 s_offs = z_offs = va;
3045
3046 if (device->physical_device->rad_info.chip_class >= GFX9) {
3047 assert(iview->image->surface.u.gfx9.surf_offset == 0);
3048 s_offs += iview->image->surface.u.gfx9.stencil_offset;
3049
3050 ds->db_z_info = S_028038_FORMAT(format) |
3051 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
3052 S_028038_SW_MODE(iview->image->surface.u.gfx9.surf.swizzle_mode) |
3053 S_028038_MAXMIP(iview->image->info.levels - 1);
3054 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
3055 S_02803C_SW_MODE(iview->image->surface.u.gfx9.stencil.swizzle_mode);
3056
3057 ds->db_z_info2 = S_028068_EPITCH(iview->image->surface.u.gfx9.surf.epitch);
3058 ds->db_stencil_info2 = S_02806C_EPITCH(iview->image->surface.u.gfx9.stencil.epitch);
3059 ds->db_depth_view |= S_028008_MIPID(level);
3060
3061 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
3062 S_02801C_Y_MAX(iview->image->info.height - 1);
3063
3064 if (radv_htile_enabled(iview->image, level)) {
3065 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
3066
3067 if (iview->image->tc_compatible_htile) {
3068 unsigned max_zplanes = 4;
3069
3070 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
3071 iview->image->info.samples > 1)
3072 max_zplanes = 2;
3073
3074 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes + 1) |
3075 S_028038_ITERATE_FLUSH(1);
3076 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
3077 }
3078
3079 if (!iview->image->surface.has_stencil)
3080 /* Use all of the htile_buffer for depth if there's no stencil. */
3081 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
3082 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
3083 iview->image->htile_offset;
3084 ds->db_htile_data_base = va >> 8;
3085 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
3086 S_028ABC_PIPE_ALIGNED(iview->image->surface.u.gfx9.htile.pipe_aligned) |
3087 S_028ABC_RB_ALIGNED(iview->image->surface.u.gfx9.htile.rb_aligned);
3088 }
3089 } else {
3090 const struct legacy_surf_level *level_info = &iview->image->surface.u.legacy.level[level];
3091
3092 if (stencil_only)
3093 level_info = &iview->image->surface.u.legacy.stencil_level[level];
3094
3095 z_offs += iview->image->surface.u.legacy.level[level].offset;
3096 s_offs += iview->image->surface.u.legacy.stencil_level[level].offset;
3097
3098 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!iview->image->tc_compatible_htile);
3099 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
3100 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
3101
3102 if (iview->image->info.samples > 1)
3103 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
3104
3105 if (device->physical_device->rad_info.chip_class >= CIK) {
3106 struct radeon_info *info = &device->physical_device->rad_info;
3107 unsigned tiling_index = iview->image->surface.u.legacy.tiling_index[level];
3108 unsigned stencil_index = iview->image->surface.u.legacy.stencil_tiling_index[level];
3109 unsigned macro_index = iview->image->surface.u.legacy.macro_tile_index;
3110 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
3111 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
3112 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
3113
3114 if (stencil_only)
3115 tile_mode = stencil_tile_mode;
3116
3117 ds->db_depth_info |=
3118 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
3119 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
3120 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
3121 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
3122 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
3123 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
3124 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
3125 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
3126 } else {
3127 unsigned tile_mode_index = si_tile_mode_index(iview->image, level, false);
3128 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
3129 tile_mode_index = si_tile_mode_index(iview->image, level, true);
3130 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
3131 if (stencil_only)
3132 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
3133 }
3134
3135 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
3136 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
3137 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
3138
3139 if (radv_htile_enabled(iview->image, level)) {
3140 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
3141
3142 if (!iview->image->surface.has_stencil &&
3143 !iview->image->tc_compatible_htile)
3144 /* Use all of the htile_buffer for depth if there's no stencil. */
3145 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
3146
3147 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
3148 iview->image->htile_offset;
3149 ds->db_htile_data_base = va >> 8;
3150 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
3151
3152 if (iview->image->tc_compatible_htile) {
3153 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
3154
3155 if (iview->image->info.samples <= 1)
3156 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(5);
3157 else if (iview->image->info.samples <= 4)
3158 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(3);
3159 else
3160 ds->db_z_info|= S_028040_DECOMPRESS_ON_N_ZPLANES(2);
3161 }
3162 }
3163 }
3164
3165 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
3166 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
3167 }
3168
3169 VkResult radv_CreateFramebuffer(
3170 VkDevice _device,
3171 const VkFramebufferCreateInfo* pCreateInfo,
3172 const VkAllocationCallbacks* pAllocator,
3173 VkFramebuffer* pFramebuffer)
3174 {
3175 RADV_FROM_HANDLE(radv_device, device, _device);
3176 struct radv_framebuffer *framebuffer;
3177
3178 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
3179
3180 size_t size = sizeof(*framebuffer) +
3181 sizeof(struct radv_attachment_info) * pCreateInfo->attachmentCount;
3182 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
3183 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3184 if (framebuffer == NULL)
3185 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3186
3187 framebuffer->attachment_count = pCreateInfo->attachmentCount;
3188 framebuffer->width = pCreateInfo->width;
3189 framebuffer->height = pCreateInfo->height;
3190 framebuffer->layers = pCreateInfo->layers;
3191 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
3192 VkImageView _iview = pCreateInfo->pAttachments[i];
3193 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
3194 framebuffer->attachments[i].attachment = iview;
3195 if (iview->aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) {
3196 radv_initialise_color_surface(device, &framebuffer->attachments[i].cb, iview);
3197 } else if (iview->aspect_mask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) {
3198 radv_initialise_ds_surface(device, &framebuffer->attachments[i].ds, iview);
3199 }
3200 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
3201 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
3202 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_layer_count(iview));
3203 }
3204
3205 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
3206 return VK_SUCCESS;
3207 }
3208
3209 void radv_DestroyFramebuffer(
3210 VkDevice _device,
3211 VkFramebuffer _fb,
3212 const VkAllocationCallbacks* pAllocator)
3213 {
3214 RADV_FROM_HANDLE(radv_device, device, _device);
3215 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
3216
3217 if (!fb)
3218 return;
3219 vk_free2(&device->alloc, pAllocator, fb);
3220 }
3221
3222 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
3223 {
3224 switch (address_mode) {
3225 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
3226 return V_008F30_SQ_TEX_WRAP;
3227 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
3228 return V_008F30_SQ_TEX_MIRROR;
3229 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
3230 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
3231 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
3232 return V_008F30_SQ_TEX_CLAMP_BORDER;
3233 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
3234 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
3235 default:
3236 unreachable("illegal tex wrap mode");
3237 break;
3238 }
3239 }
3240
3241 static unsigned
3242 radv_tex_compare(VkCompareOp op)
3243 {
3244 switch (op) {
3245 case VK_COMPARE_OP_NEVER:
3246 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
3247 case VK_COMPARE_OP_LESS:
3248 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
3249 case VK_COMPARE_OP_EQUAL:
3250 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
3251 case VK_COMPARE_OP_LESS_OR_EQUAL:
3252 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
3253 case VK_COMPARE_OP_GREATER:
3254 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
3255 case VK_COMPARE_OP_NOT_EQUAL:
3256 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
3257 case VK_COMPARE_OP_GREATER_OR_EQUAL:
3258 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
3259 case VK_COMPARE_OP_ALWAYS:
3260 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
3261 default:
3262 unreachable("illegal compare mode");
3263 break;
3264 }
3265 }
3266
3267 static unsigned
3268 radv_tex_filter(VkFilter filter, unsigned max_ansio)
3269 {
3270 switch (filter) {
3271 case VK_FILTER_NEAREST:
3272 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
3273 V_008F38_SQ_TEX_XY_FILTER_POINT);
3274 case VK_FILTER_LINEAR:
3275 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
3276 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
3277 case VK_FILTER_CUBIC_IMG:
3278 default:
3279 fprintf(stderr, "illegal texture filter");
3280 return 0;
3281 }
3282 }
3283
3284 static unsigned
3285 radv_tex_mipfilter(VkSamplerMipmapMode mode)
3286 {
3287 switch (mode) {
3288 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
3289 return V_008F38_SQ_TEX_Z_FILTER_POINT;
3290 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
3291 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
3292 default:
3293 return V_008F38_SQ_TEX_Z_FILTER_NONE;
3294 }
3295 }
3296
3297 static unsigned
3298 radv_tex_bordercolor(VkBorderColor bcolor)
3299 {
3300 switch (bcolor) {
3301 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
3302 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
3303 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
3304 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
3305 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
3306 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
3307 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
3308 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
3309 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
3310 default:
3311 break;
3312 }
3313 return 0;
3314 }
3315
3316 static unsigned
3317 radv_tex_aniso_filter(unsigned filter)
3318 {
3319 if (filter < 2)
3320 return 0;
3321 if (filter < 4)
3322 return 1;
3323 if (filter < 8)
3324 return 2;
3325 if (filter < 16)
3326 return 3;
3327 return 4;
3328 }
3329
3330 static void
3331 radv_init_sampler(struct radv_device *device,
3332 struct radv_sampler *sampler,
3333 const VkSamplerCreateInfo *pCreateInfo)
3334 {
3335 uint32_t max_aniso = pCreateInfo->anisotropyEnable && pCreateInfo->maxAnisotropy > 1.0 ?
3336 (uint32_t) pCreateInfo->maxAnisotropy : 0;
3337 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
3338 bool is_vi = (device->physical_device->rad_info.chip_class >= VI);
3339
3340 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
3341 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
3342 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
3343 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
3344 S_008F30_DEPTH_COMPARE_FUNC(radv_tex_compare(pCreateInfo->compareOp)) |
3345 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
3346 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
3347 S_008F30_ANISO_BIAS(max_aniso_ratio) |
3348 S_008F30_DISABLE_CUBE_WRAP(0) |
3349 S_008F30_COMPAT_MODE(is_vi));
3350 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
3351 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
3352 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
3353 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
3354 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
3355 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
3356 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
3357 S_008F38_MIP_POINT_PRECLAMP(0) |
3358 S_008F38_DISABLE_LSB_CEIL(1) |
3359 S_008F38_FILTER_PREC_FIX(1) |
3360 S_008F38_ANISO_OVERRIDE(is_vi));
3361 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(0) |
3362 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(pCreateInfo->borderColor)));
3363 }
3364
3365 VkResult radv_CreateSampler(
3366 VkDevice _device,
3367 const VkSamplerCreateInfo* pCreateInfo,
3368 const VkAllocationCallbacks* pAllocator,
3369 VkSampler* pSampler)
3370 {
3371 RADV_FROM_HANDLE(radv_device, device, _device);
3372 struct radv_sampler *sampler;
3373
3374 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
3375
3376 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
3377 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3378 if (!sampler)
3379 return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
3380
3381 radv_init_sampler(device, sampler, pCreateInfo);
3382 *pSampler = radv_sampler_to_handle(sampler);
3383
3384 return VK_SUCCESS;
3385 }
3386
3387 void radv_DestroySampler(
3388 VkDevice _device,
3389 VkSampler _sampler,
3390 const VkAllocationCallbacks* pAllocator)
3391 {
3392 RADV_FROM_HANDLE(radv_device, device, _device);
3393 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
3394
3395 if (!sampler)
3396 return;
3397 vk_free2(&device->alloc, pAllocator, sampler);
3398 }
3399
3400 /* vk_icd.h does not declare this function, so we declare it here to
3401 * suppress Wmissing-prototypes.
3402 */
3403 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
3404 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
3405
3406 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
3407 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
3408 {
3409 /* For the full details on loader interface versioning, see
3410 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
3411 * What follows is a condensed summary, to help you navigate the large and
3412 * confusing official doc.
3413 *
3414 * - Loader interface v0 is incompatible with later versions. We don't
3415 * support it.
3416 *
3417 * - In loader interface v1:
3418 * - The first ICD entrypoint called by the loader is
3419 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
3420 * entrypoint.
3421 * - The ICD must statically expose no other Vulkan symbol unless it is
3422 * linked with -Bsymbolic.
3423 * - Each dispatchable Vulkan handle created by the ICD must be
3424 * a pointer to a struct whose first member is VK_LOADER_DATA. The
3425 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
3426 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
3427 * vkDestroySurfaceKHR(). The ICD must be capable of working with
3428 * such loader-managed surfaces.
3429 *
3430 * - Loader interface v2 differs from v1 in:
3431 * - The first ICD entrypoint called by the loader is
3432 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
3433 * statically expose this entrypoint.
3434 *
3435 * - Loader interface v3 differs from v2 in:
3436 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
3437 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
3438 * because the loader no longer does so.
3439 */
3440 *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
3441 return VK_SUCCESS;
3442 }
3443
3444 VkResult radv_GetMemoryFdKHR(VkDevice _device,
3445 const VkMemoryGetFdInfoKHR *pGetFdInfo,
3446 int *pFD)
3447 {
3448 RADV_FROM_HANDLE(radv_device, device, _device);
3449 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
3450
3451 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
3452
3453 /* We support only one handle type. */
3454 assert(pGetFdInfo->handleType ==
3455 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR);
3456
3457 bool ret = radv_get_memory_fd(device, memory, pFD);
3458 if (ret == false)
3459 return VK_ERROR_OUT_OF_DEVICE_MEMORY;
3460 return VK_SUCCESS;
3461 }
3462
3463 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
3464 VkExternalMemoryHandleTypeFlagBitsKHR handleType,
3465 int fd,
3466 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
3467 {
3468 /* The valid usage section for this function says:
3469 *
3470 * "handleType must not be one of the handle types defined as opaque."
3471 *
3472 * Since we only handle opaque handles for now, there are no FD properties.
3473 */
3474 return VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR;
3475 }
3476
3477 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
3478 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
3479 {
3480 RADV_FROM_HANDLE(radv_device, device, _device);
3481 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
3482 uint32_t syncobj_handle = 0;
3483 assert(pImportSemaphoreFdInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR);
3484
3485 int ret = device->ws->import_syncobj(device->ws, pImportSemaphoreFdInfo->fd, &syncobj_handle);
3486 if (ret != 0)
3487 return VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR;
3488
3489 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR) {
3490 sem->temp_syncobj = syncobj_handle;
3491 } else {
3492 sem->syncobj = syncobj_handle;
3493 }
3494 close(pImportSemaphoreFdInfo->fd);
3495 return VK_SUCCESS;
3496 }
3497
3498 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
3499 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
3500 int *pFd)
3501 {
3502 RADV_FROM_HANDLE(radv_device, device, _device);
3503 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
3504 int ret;
3505 uint32_t syncobj_handle;
3506
3507 assert(pGetFdInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR);
3508 if (sem->temp_syncobj)
3509 syncobj_handle = sem->temp_syncobj;
3510 else
3511 syncobj_handle = sem->syncobj;
3512 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
3513 if (ret)
3514 return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR);
3515 return VK_SUCCESS;
3516 }
3517
3518 void radv_GetPhysicalDeviceExternalSemaphorePropertiesKHR(
3519 VkPhysicalDevice physicalDevice,
3520 const VkPhysicalDeviceExternalSemaphoreInfoKHR* pExternalSemaphoreInfo,
3521 VkExternalSemaphorePropertiesKHR* pExternalSemaphoreProperties)
3522 {
3523 if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR) {
3524 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
3525 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT_KHR;
3526 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT_KHR |
3527 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT_KHR;
3528 } else {
3529 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
3530 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
3531 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
3532 }
3533 }