ac: add rbplus_allowed to ac_gpu_info
[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 "winsys/amdgpu/radv_amdgpu_winsys_public.h"
43 #include "ac_llvm_util.h"
44 #include "vk_format.h"
45 #include "sid.h"
46 #include "git_sha1.h"
47 #include "util/build_id.h"
48 #include "util/debug.h"
49 #include "util/mesa-sha1.h"
50 #include "compiler/glsl_types.h"
51 #include "util/xmlpool.h"
52
53 static int
54 radv_device_get_cache_uuid(enum radeon_family family, void *uuid)
55 {
56 struct mesa_sha1 ctx;
57 unsigned char sha1[20];
58 unsigned ptr_size = sizeof(void*);
59
60 memset(uuid, 0, VK_UUID_SIZE);
61 _mesa_sha1_init(&ctx);
62
63 if (!disk_cache_get_function_identifier(radv_device_get_cache_uuid, &ctx) ||
64 !disk_cache_get_function_identifier(LLVMInitializeAMDGPUTargetInfo, &ctx))
65 return -1;
66
67 _mesa_sha1_update(&ctx, &family, sizeof(family));
68 _mesa_sha1_update(&ctx, &ptr_size, sizeof(ptr_size));
69 _mesa_sha1_final(&ctx, sha1);
70
71 memcpy(uuid, sha1, VK_UUID_SIZE);
72 return 0;
73 }
74
75 static void
76 radv_get_driver_uuid(void *uuid)
77 {
78 ac_compute_driver_uuid(uuid, VK_UUID_SIZE);
79 }
80
81 static void
82 radv_get_device_uuid(struct radeon_info *info, void *uuid)
83 {
84 ac_compute_device_uuid(info, uuid, VK_UUID_SIZE);
85 }
86
87 static void
88 radv_get_device_name(enum radeon_family family, char *name, size_t name_len)
89 {
90 const char *chip_string;
91
92 switch (family) {
93 case CHIP_TAHITI: chip_string = "AMD RADV TAHITI"; break;
94 case CHIP_PITCAIRN: chip_string = "AMD RADV PITCAIRN"; break;
95 case CHIP_VERDE: chip_string = "AMD RADV CAPE VERDE"; break;
96 case CHIP_OLAND: chip_string = "AMD RADV OLAND"; break;
97 case CHIP_HAINAN: chip_string = "AMD RADV HAINAN"; break;
98 case CHIP_BONAIRE: chip_string = "AMD RADV BONAIRE"; break;
99 case CHIP_KAVERI: chip_string = "AMD RADV KAVERI"; break;
100 case CHIP_KABINI: chip_string = "AMD RADV KABINI"; break;
101 case CHIP_HAWAII: chip_string = "AMD RADV HAWAII"; break;
102 case CHIP_TONGA: chip_string = "AMD RADV TONGA"; break;
103 case CHIP_ICELAND: chip_string = "AMD RADV ICELAND"; break;
104 case CHIP_CARRIZO: chip_string = "AMD RADV CARRIZO"; break;
105 case CHIP_FIJI: chip_string = "AMD RADV FIJI"; break;
106 case CHIP_POLARIS10: chip_string = "AMD RADV POLARIS10"; break;
107 case CHIP_POLARIS11: chip_string = "AMD RADV POLARIS11"; break;
108 case CHIP_POLARIS12: chip_string = "AMD RADV POLARIS12"; break;
109 case CHIP_STONEY: chip_string = "AMD RADV STONEY"; break;
110 case CHIP_VEGAM: chip_string = "AMD RADV VEGA M"; break;
111 case CHIP_VEGA10: chip_string = "AMD RADV VEGA10"; break;
112 case CHIP_VEGA12: chip_string = "AMD RADV VEGA12"; break;
113 case CHIP_VEGA20: chip_string = "AMD RADV VEGA20"; break;
114 case CHIP_RAVEN: chip_string = "AMD RADV RAVEN"; break;
115 case CHIP_RAVEN2: chip_string = "AMD RADV RAVEN2"; break;
116 case CHIP_NAVI10: chip_string = "AMD RADV NAVI10"; break;
117 case CHIP_NAVI12: chip_string = "AMD RADV NAVI12"; break;
118 case CHIP_NAVI14: chip_string = "AMD RADV NAVI14"; break;
119 default: chip_string = "AMD RADV unknown"; break;
120 }
121
122 snprintf(name, name_len, "%s (LLVM " MESA_LLVM_VERSION_STRING ")", chip_string);
123 }
124
125 static uint64_t
126 radv_get_visible_vram_size(struct radv_physical_device *device)
127 {
128 return MIN2(device->rad_info.vram_size, device->rad_info.vram_vis_size);
129 }
130
131 static uint64_t
132 radv_get_vram_size(struct radv_physical_device *device)
133 {
134 return device->rad_info.vram_size - radv_get_visible_vram_size(device);
135 }
136
137 static void
138 radv_physical_device_init_mem_types(struct radv_physical_device *device)
139 {
140 STATIC_ASSERT(RADV_MEM_HEAP_COUNT <= VK_MAX_MEMORY_HEAPS);
141 uint64_t visible_vram_size = radv_get_visible_vram_size(device);
142 uint64_t vram_size = radv_get_vram_size(device);
143 int vram_index = -1, visible_vram_index = -1, gart_index = -1;
144 device->memory_properties.memoryHeapCount = 0;
145 if (vram_size > 0) {
146 vram_index = device->memory_properties.memoryHeapCount++;
147 device->memory_properties.memoryHeaps[vram_index] = (VkMemoryHeap) {
148 .size = vram_size,
149 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
150 };
151 }
152 if (visible_vram_size) {
153 visible_vram_index = device->memory_properties.memoryHeapCount++;
154 device->memory_properties.memoryHeaps[visible_vram_index] = (VkMemoryHeap) {
155 .size = visible_vram_size,
156 .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
157 };
158 }
159 if (device->rad_info.gart_size > 0) {
160 gart_index = device->memory_properties.memoryHeapCount++;
161 device->memory_properties.memoryHeaps[gart_index] = (VkMemoryHeap) {
162 .size = device->rad_info.gart_size,
163 .flags = device->rad_info.has_dedicated_vram ? 0 : VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
164 };
165 }
166
167 STATIC_ASSERT(RADV_MEM_TYPE_COUNT <= VK_MAX_MEMORY_TYPES);
168 unsigned type_count = 0;
169 if (vram_index >= 0) {
170 device->mem_type_indices[type_count] = RADV_MEM_TYPE_VRAM;
171 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
172 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
173 .heapIndex = vram_index,
174 };
175 }
176 if (gart_index >= 0 && device->rad_info.has_dedicated_vram) {
177 device->mem_type_indices[type_count] = RADV_MEM_TYPE_GTT_WRITE_COMBINE;
178 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
179 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
180 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
181 .heapIndex = gart_index,
182 };
183 }
184 if (visible_vram_index >= 0) {
185 device->mem_type_indices[type_count] = RADV_MEM_TYPE_VRAM_CPU_ACCESS;
186 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
187 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
188 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
189 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
190 .heapIndex = visible_vram_index,
191 };
192 }
193 if (gart_index >= 0 && !device->rad_info.has_dedicated_vram) {
194 /* Put GTT after visible VRAM for GPUs without dedicated VRAM
195 * as they have identical property flags, and according to the
196 * spec, for types with identical flags, the one with greater
197 * performance must be given a lower index. */
198 device->mem_type_indices[type_count] = RADV_MEM_TYPE_GTT_WRITE_COMBINE;
199 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
200 .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
201 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
202 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
203 .heapIndex = gart_index,
204 };
205 }
206 if (gart_index >= 0) {
207 device->mem_type_indices[type_count] = RADV_MEM_TYPE_GTT_CACHED;
208 device->memory_properties.memoryTypes[type_count++] = (VkMemoryType) {
209 .propertyFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
210 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
211 VK_MEMORY_PROPERTY_HOST_CACHED_BIT |
212 (device->rad_info.has_dedicated_vram ? 0 : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT),
213 .heapIndex = gart_index,
214 };
215 }
216 device->memory_properties.memoryTypeCount = type_count;
217 }
218
219 static void
220 radv_handle_env_var_force_family(struct radv_physical_device *device)
221 {
222 const char *family = getenv("RADV_FORCE_FAMILY");
223 unsigned i;
224
225 if (!family)
226 return;
227
228 for (i = CHIP_TAHITI; i < CHIP_LAST; i++) {
229 if (!strcmp(family, ac_get_llvm_processor_name(i))) {
230 /* Override family and chip_class. */
231 device->rad_info.family = i;
232
233 if (i >= CHIP_NAVI10)
234 device->rad_info.chip_class = GFX10;
235 else if (i >= CHIP_VEGA10)
236 device->rad_info.chip_class = GFX9;
237 else if (i >= CHIP_TONGA)
238 device->rad_info.chip_class = GFX8;
239 else if (i >= CHIP_BONAIRE)
240 device->rad_info.chip_class = GFX7;
241 else
242 device->rad_info.chip_class = GFX6;
243
244 return;
245 }
246 }
247
248 fprintf(stderr, "radv: Unknown family: %s\n", family);
249 exit(1);
250 }
251
252 static VkResult
253 radv_physical_device_init(struct radv_physical_device *device,
254 struct radv_instance *instance,
255 drmDevicePtr drm_device)
256 {
257 const char *path = drm_device->nodes[DRM_NODE_RENDER];
258 VkResult result;
259 drmVersionPtr version;
260 int fd;
261 int master_fd = -1;
262
263 fd = open(path, O_RDWR | O_CLOEXEC);
264 if (fd < 0) {
265 if (instance->debug_flags & RADV_DEBUG_STARTUP)
266 radv_logi("Could not open device '%s'", path);
267
268 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
269 }
270
271 version = drmGetVersion(fd);
272 if (!version) {
273 close(fd);
274
275 if (instance->debug_flags & RADV_DEBUG_STARTUP)
276 radv_logi("Could not get the kernel driver version for device '%s'", path);
277
278 return vk_errorf(instance, VK_ERROR_INCOMPATIBLE_DRIVER,
279 "failed to get version %s: %m", path);
280 }
281
282 if (strcmp(version->name, "amdgpu")) {
283 drmFreeVersion(version);
284 close(fd);
285
286 if (instance->debug_flags & RADV_DEBUG_STARTUP)
287 radv_logi("Device '%s' is not using the amdgpu kernel driver.", path);
288
289 return VK_ERROR_INCOMPATIBLE_DRIVER;
290 }
291 drmFreeVersion(version);
292
293 if (instance->debug_flags & RADV_DEBUG_STARTUP)
294 radv_logi("Found compatible device '%s'.", path);
295
296 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
297 device->instance = instance;
298
299 device->ws = radv_amdgpu_winsys_create(fd, instance->debug_flags,
300 instance->perftest_flags);
301 if (!device->ws) {
302 result = vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
303 goto fail;
304 }
305
306 if (instance->enabled_extensions.KHR_display) {
307 master_fd = open(drm_device->nodes[DRM_NODE_PRIMARY], O_RDWR | O_CLOEXEC);
308 if (master_fd >= 0) {
309 uint32_t accel_working = 0;
310 struct drm_amdgpu_info request = {
311 .return_pointer = (uintptr_t)&accel_working,
312 .return_size = sizeof(accel_working),
313 .query = AMDGPU_INFO_ACCEL_WORKING
314 };
315
316 if (drmCommandWrite(master_fd, DRM_AMDGPU_INFO, &request, sizeof (struct drm_amdgpu_info)) < 0 || !accel_working) {
317 close(master_fd);
318 master_fd = -1;
319 }
320 }
321 }
322
323 device->master_fd = master_fd;
324 device->local_fd = fd;
325 device->ws->query_info(device->ws, &device->rad_info);
326
327 radv_handle_env_var_force_family(device);
328
329 radv_get_device_name(device->rad_info.family, device->name, sizeof(device->name));
330
331 if (radv_device_get_cache_uuid(device->rad_info.family, device->cache_uuid)) {
332 device->ws->destroy(device->ws);
333 result = vk_errorf(instance, VK_ERROR_INITIALIZATION_FAILED,
334 "cannot generate UUID");
335 goto fail;
336 }
337
338 /* These flags affect shader compilation. */
339 uint64_t shader_env_flags =
340 (device->instance->perftest_flags & RADV_PERFTEST_SISCHED ? 0x1 : 0) |
341 (device->instance->debug_flags & RADV_DEBUG_UNSAFE_MATH ? 0x2 : 0);
342
343 /* The gpu id is already embedded in the uuid so we just pass "radv"
344 * when creating the cache.
345 */
346 char buf[VK_UUID_SIZE * 2 + 1];
347 disk_cache_format_hex_id(buf, device->cache_uuid, VK_UUID_SIZE * 2);
348 device->disk_cache = disk_cache_create(device->name, buf, shader_env_flags);
349
350 if (device->rad_info.chip_class < GFX8 ||
351 device->rad_info.chip_class > GFX9)
352 fprintf(stderr, "WARNING: radv is not a conformant vulkan implementation, testing use only.\n");
353
354 radv_get_driver_uuid(&device->driver_uuid);
355 radv_get_device_uuid(&device->rad_info, &device->device_uuid);
356
357 device->out_of_order_rast_allowed = device->rad_info.has_out_of_order_rast &&
358 !(device->instance->debug_flags & RADV_DEBUG_NO_OUT_OF_ORDER);
359
360 device->dcc_msaa_allowed =
361 (device->instance->perftest_flags & RADV_PERFTEST_DCC_MSAA);
362
363 device->use_shader_ballot = device->rad_info.chip_class >= GFX8 &&
364 device->instance->perftest_flags & RADV_PERFTEST_SHADER_BALLOT;
365
366 /* Determine the number of threads per wave for all stages. */
367 device->cs_wave_size = 64;
368 device->ps_wave_size = 64;
369 device->ge_wave_size = 64;
370
371 if (device->rad_info.chip_class >= GFX10) {
372 if (device->instance->perftest_flags & RADV_PERFTEST_CS_WAVE_32)
373 device->cs_wave_size = 32;
374
375 /* For pixel shaders, wave64 is recommanded. */
376 if (device->instance->perftest_flags & RADV_PERFTEST_PS_WAVE_32)
377 device->ps_wave_size = 32;
378
379 if (device->instance->perftest_flags & RADV_PERFTEST_GE_WAVE_32)
380 device->ge_wave_size = 32;
381 }
382
383 radv_physical_device_init_mem_types(device);
384 radv_fill_device_extension_table(device, &device->supported_extensions);
385
386 device->bus_info = *drm_device->businfo.pci;
387
388 if ((device->instance->debug_flags & RADV_DEBUG_INFO))
389 ac_print_gpu_info(&device->rad_info);
390
391 /* The WSI is structured as a layer on top of the driver, so this has
392 * to be the last part of initialization (at least until we get other
393 * semi-layers).
394 */
395 result = radv_init_wsi(device);
396 if (result != VK_SUCCESS) {
397 device->ws->destroy(device->ws);
398 vk_error(instance, result);
399 goto fail;
400 }
401
402 return VK_SUCCESS;
403
404 fail:
405 close(fd);
406 if (master_fd != -1)
407 close(master_fd);
408 return result;
409 }
410
411 static void
412 radv_physical_device_finish(struct radv_physical_device *device)
413 {
414 radv_finish_wsi(device);
415 device->ws->destroy(device->ws);
416 disk_cache_destroy(device->disk_cache);
417 close(device->local_fd);
418 if (device->master_fd != -1)
419 close(device->master_fd);
420 }
421
422 static void *
423 default_alloc_func(void *pUserData, size_t size, size_t align,
424 VkSystemAllocationScope allocationScope)
425 {
426 return malloc(size);
427 }
428
429 static void *
430 default_realloc_func(void *pUserData, void *pOriginal, size_t size,
431 size_t align, VkSystemAllocationScope allocationScope)
432 {
433 return realloc(pOriginal, size);
434 }
435
436 static void
437 default_free_func(void *pUserData, void *pMemory)
438 {
439 free(pMemory);
440 }
441
442 static const VkAllocationCallbacks default_alloc = {
443 .pUserData = NULL,
444 .pfnAllocation = default_alloc_func,
445 .pfnReallocation = default_realloc_func,
446 .pfnFree = default_free_func,
447 };
448
449 static const struct debug_control radv_debug_options[] = {
450 {"nofastclears", RADV_DEBUG_NO_FAST_CLEARS},
451 {"nodcc", RADV_DEBUG_NO_DCC},
452 {"shaders", RADV_DEBUG_DUMP_SHADERS},
453 {"nocache", RADV_DEBUG_NO_CACHE},
454 {"shaderstats", RADV_DEBUG_DUMP_SHADER_STATS},
455 {"nohiz", RADV_DEBUG_NO_HIZ},
456 {"nocompute", RADV_DEBUG_NO_COMPUTE_QUEUE},
457 {"unsafemath", RADV_DEBUG_UNSAFE_MATH},
458 {"allbos", RADV_DEBUG_ALL_BOS},
459 {"noibs", RADV_DEBUG_NO_IBS},
460 {"spirv", RADV_DEBUG_DUMP_SPIRV},
461 {"vmfaults", RADV_DEBUG_VM_FAULTS},
462 {"zerovram", RADV_DEBUG_ZERO_VRAM},
463 {"syncshaders", RADV_DEBUG_SYNC_SHADERS},
464 {"nosisched", RADV_DEBUG_NO_SISCHED},
465 {"preoptir", RADV_DEBUG_PREOPTIR},
466 {"nodynamicbounds", RADV_DEBUG_NO_DYNAMIC_BOUNDS},
467 {"nooutoforder", RADV_DEBUG_NO_OUT_OF_ORDER},
468 {"info", RADV_DEBUG_INFO},
469 {"errors", RADV_DEBUG_ERRORS},
470 {"startup", RADV_DEBUG_STARTUP},
471 {"checkir", RADV_DEBUG_CHECKIR},
472 {"nothreadllvm", RADV_DEBUG_NOTHREADLLVM},
473 {"nobinning", RADV_DEBUG_NOBINNING},
474 {"noloadstoreopt", RADV_DEBUG_NO_LOAD_STORE_OPT},
475 {"nongg", RADV_DEBUG_NO_NGG},
476 {"noshaderballot", RADV_DEBUG_NO_SHADER_BALLOT},
477 {"allentrypoints", RADV_DEBUG_ALL_ENTRYPOINTS},
478 {NULL, 0}
479 };
480
481 const char *
482 radv_get_debug_option_name(int id)
483 {
484 assert(id < ARRAY_SIZE(radv_debug_options) - 1);
485 return radv_debug_options[id].string;
486 }
487
488 static const struct debug_control radv_perftest_options[] = {
489 {"nobatchchain", RADV_PERFTEST_NO_BATCHCHAIN},
490 {"sisched", RADV_PERFTEST_SISCHED},
491 {"localbos", RADV_PERFTEST_LOCAL_BOS},
492 {"dccmsaa", RADV_PERFTEST_DCC_MSAA},
493 {"bolist", RADV_PERFTEST_BO_LIST},
494 {"shader_ballot", RADV_PERFTEST_SHADER_BALLOT},
495 {"tccompatcmask", RADV_PERFTEST_TC_COMPAT_CMASK},
496 {"cswave32", RADV_PERFTEST_CS_WAVE_32},
497 {"pswave32", RADV_PERFTEST_PS_WAVE_32},
498 {"gewave32", RADV_PERFTEST_GE_WAVE_32},
499 {NULL, 0}
500 };
501
502 const char *
503 radv_get_perftest_option_name(int id)
504 {
505 assert(id < ARRAY_SIZE(radv_perftest_options) - 1);
506 return radv_perftest_options[id].string;
507 }
508
509 static void
510 radv_handle_per_app_options(struct radv_instance *instance,
511 const VkApplicationInfo *info)
512 {
513 const char *name = info ? info->pApplicationName : NULL;
514
515 if (!name)
516 return;
517
518 if (!strcmp(name, "Talos - Linux - 32bit") ||
519 !strcmp(name, "Talos - Linux - 64bit")) {
520 if (!(instance->debug_flags & RADV_DEBUG_NO_SISCHED)) {
521 /* Force enable LLVM sisched for Talos because it looks
522 * safe and it gives few more FPS.
523 */
524 instance->perftest_flags |= RADV_PERFTEST_SISCHED;
525 }
526 } else if (!strcmp(name, "DOOM_VFR")) {
527 /* Work around a Doom VFR game bug */
528 instance->debug_flags |= RADV_DEBUG_NO_DYNAMIC_BOUNDS;
529 } else if (!strcmp(name, "MonsterHunterWorld.exe")) {
530 /* Workaround for a WaW hazard when LLVM moves/merges
531 * load/store memory operations.
532 * See https://reviews.llvm.org/D61313
533 */
534 if (HAVE_LLVM < 0x900)
535 instance->debug_flags |= RADV_DEBUG_NO_LOAD_STORE_OPT;
536 } else if (!strcmp(name, "Wolfenstein: Youngblood")) {
537 if (!(instance->debug_flags & RADV_DEBUG_NO_SHADER_BALLOT)) {
538 /* Force enable VK_AMD_shader_ballot because it looks
539 * safe and it gives a nice boost (+20% on Vega 56 at
540 * this time).
541 */
542 instance->perftest_flags |= RADV_PERFTEST_SHADER_BALLOT;
543 }
544 }
545 }
546
547 static int radv_get_instance_extension_index(const char *name)
548 {
549 for (unsigned i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; ++i) {
550 if (strcmp(name, radv_instance_extensions[i].extensionName) == 0)
551 return i;
552 }
553 return -1;
554 }
555
556 static const char radv_dri_options_xml[] =
557 DRI_CONF_BEGIN
558 DRI_CONF_SECTION_QUALITY
559 DRI_CONF_ADAPTIVE_SYNC("true")
560 DRI_CONF_SECTION_END
561 DRI_CONF_END;
562
563 static void radv_init_dri_options(struct radv_instance *instance)
564 {
565 driParseOptionInfo(&instance->available_dri_options, radv_dri_options_xml);
566 driParseConfigFiles(&instance->dri_options,
567 &instance->available_dri_options,
568 0, "radv", NULL);
569 }
570
571 VkResult radv_CreateInstance(
572 const VkInstanceCreateInfo* pCreateInfo,
573 const VkAllocationCallbacks* pAllocator,
574 VkInstance* pInstance)
575 {
576 struct radv_instance *instance;
577 VkResult result;
578
579 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
580
581 uint32_t client_version;
582 if (pCreateInfo->pApplicationInfo &&
583 pCreateInfo->pApplicationInfo->apiVersion != 0) {
584 client_version = pCreateInfo->pApplicationInfo->apiVersion;
585 } else {
586 client_version = VK_API_VERSION_1_0;
587 }
588
589 instance = vk_zalloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
590 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
591 if (!instance)
592 return vk_error(NULL, VK_ERROR_OUT_OF_HOST_MEMORY);
593
594 instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
595
596 if (pAllocator)
597 instance->alloc = *pAllocator;
598 else
599 instance->alloc = default_alloc;
600
601 instance->apiVersion = client_version;
602 instance->physicalDeviceCount = -1;
603
604 instance->debug_flags = parse_debug_string(getenv("RADV_DEBUG"),
605 radv_debug_options);
606
607 instance->perftest_flags = parse_debug_string(getenv("RADV_PERFTEST"),
608 radv_perftest_options);
609
610
611 if (instance->debug_flags & RADV_DEBUG_STARTUP)
612 radv_logi("Created an instance");
613
614 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
615 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
616 int index = radv_get_instance_extension_index(ext_name);
617
618 if (index < 0 || !radv_supported_instance_extensions.extensions[index]) {
619 vk_free2(&default_alloc, pAllocator, instance);
620 return vk_error(instance, VK_ERROR_EXTENSION_NOT_PRESENT);
621 }
622
623 instance->enabled_extensions.extensions[index] = true;
624 }
625
626 result = vk_debug_report_instance_init(&instance->debug_report_callbacks);
627 if (result != VK_SUCCESS) {
628 vk_free2(&default_alloc, pAllocator, instance);
629 return vk_error(instance, result);
630 }
631
632 _mesa_locale_init();
633 glsl_type_singleton_init_or_ref();
634
635 VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
636
637 radv_init_dri_options(instance);
638 radv_handle_per_app_options(instance, pCreateInfo->pApplicationInfo);
639
640 *pInstance = radv_instance_to_handle(instance);
641
642 return VK_SUCCESS;
643 }
644
645 void radv_DestroyInstance(
646 VkInstance _instance,
647 const VkAllocationCallbacks* pAllocator)
648 {
649 RADV_FROM_HANDLE(radv_instance, instance, _instance);
650
651 if (!instance)
652 return;
653
654 for (int i = 0; i < instance->physicalDeviceCount; ++i) {
655 radv_physical_device_finish(instance->physicalDevices + i);
656 }
657
658 VG(VALGRIND_DESTROY_MEMPOOL(instance));
659
660 glsl_type_singleton_decref();
661 _mesa_locale_fini();
662
663 driDestroyOptionCache(&instance->dri_options);
664 driDestroyOptionInfo(&instance->available_dri_options);
665
666 vk_debug_report_instance_destroy(&instance->debug_report_callbacks);
667
668 vk_free(&instance->alloc, instance);
669 }
670
671 static VkResult
672 radv_enumerate_devices(struct radv_instance *instance)
673 {
674 /* TODO: Check for more devices ? */
675 drmDevicePtr devices[8];
676 VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
677 int max_devices;
678
679 instance->physicalDeviceCount = 0;
680
681 max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
682
683 if (instance->debug_flags & RADV_DEBUG_STARTUP)
684 radv_logi("Found %d drm nodes", max_devices);
685
686 if (max_devices < 1)
687 return vk_error(instance, VK_ERROR_INCOMPATIBLE_DRIVER);
688
689 for (unsigned i = 0; i < (unsigned)max_devices; i++) {
690 if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
691 devices[i]->bustype == DRM_BUS_PCI &&
692 devices[i]->deviceinfo.pci->vendor_id == ATI_VENDOR_ID) {
693
694 result = radv_physical_device_init(instance->physicalDevices +
695 instance->physicalDeviceCount,
696 instance,
697 devices[i]);
698 if (result == VK_SUCCESS)
699 ++instance->physicalDeviceCount;
700 else if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
701 break;
702 }
703 }
704 drmFreeDevices(devices, max_devices);
705
706 return result;
707 }
708
709 VkResult radv_EnumeratePhysicalDevices(
710 VkInstance _instance,
711 uint32_t* pPhysicalDeviceCount,
712 VkPhysicalDevice* pPhysicalDevices)
713 {
714 RADV_FROM_HANDLE(radv_instance, instance, _instance);
715 VkResult result;
716
717 if (instance->physicalDeviceCount < 0) {
718 result = radv_enumerate_devices(instance);
719 if (result != VK_SUCCESS &&
720 result != VK_ERROR_INCOMPATIBLE_DRIVER)
721 return result;
722 }
723
724 if (!pPhysicalDevices) {
725 *pPhysicalDeviceCount = instance->physicalDeviceCount;
726 } else {
727 *pPhysicalDeviceCount = MIN2(*pPhysicalDeviceCount, instance->physicalDeviceCount);
728 for (unsigned i = 0; i < *pPhysicalDeviceCount; ++i)
729 pPhysicalDevices[i] = radv_physical_device_to_handle(instance->physicalDevices + i);
730 }
731
732 return *pPhysicalDeviceCount < instance->physicalDeviceCount ? VK_INCOMPLETE
733 : VK_SUCCESS;
734 }
735
736 VkResult radv_EnumeratePhysicalDeviceGroups(
737 VkInstance _instance,
738 uint32_t* pPhysicalDeviceGroupCount,
739 VkPhysicalDeviceGroupProperties* pPhysicalDeviceGroupProperties)
740 {
741 RADV_FROM_HANDLE(radv_instance, instance, _instance);
742 VkResult result;
743
744 if (instance->physicalDeviceCount < 0) {
745 result = radv_enumerate_devices(instance);
746 if (result != VK_SUCCESS &&
747 result != VK_ERROR_INCOMPATIBLE_DRIVER)
748 return result;
749 }
750
751 if (!pPhysicalDeviceGroupProperties) {
752 *pPhysicalDeviceGroupCount = instance->physicalDeviceCount;
753 } else {
754 *pPhysicalDeviceGroupCount = MIN2(*pPhysicalDeviceGroupCount, instance->physicalDeviceCount);
755 for (unsigned i = 0; i < *pPhysicalDeviceGroupCount; ++i) {
756 pPhysicalDeviceGroupProperties[i].physicalDeviceCount = 1;
757 pPhysicalDeviceGroupProperties[i].physicalDevices[0] = radv_physical_device_to_handle(instance->physicalDevices + i);
758 pPhysicalDeviceGroupProperties[i].subsetAllocation = false;
759 }
760 }
761 return *pPhysicalDeviceGroupCount < instance->physicalDeviceCount ? VK_INCOMPLETE
762 : VK_SUCCESS;
763 }
764
765 void radv_GetPhysicalDeviceFeatures(
766 VkPhysicalDevice physicalDevice,
767 VkPhysicalDeviceFeatures* pFeatures)
768 {
769 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
770 memset(pFeatures, 0, sizeof(*pFeatures));
771
772 *pFeatures = (VkPhysicalDeviceFeatures) {
773 .robustBufferAccess = true,
774 .fullDrawIndexUint32 = true,
775 .imageCubeArray = true,
776 .independentBlend = true,
777 .geometryShader = true,
778 .tessellationShader = true,
779 .sampleRateShading = true,
780 .dualSrcBlend = true,
781 .logicOp = true,
782 .multiDrawIndirect = true,
783 .drawIndirectFirstInstance = true,
784 .depthClamp = true,
785 .depthBiasClamp = true,
786 .fillModeNonSolid = true,
787 .depthBounds = true,
788 .wideLines = true,
789 .largePoints = true,
790 .alphaToOne = true,
791 .multiViewport = true,
792 .samplerAnisotropy = true,
793 .textureCompressionETC2 = radv_device_supports_etc(pdevice),
794 .textureCompressionASTC_LDR = false,
795 .textureCompressionBC = true,
796 .occlusionQueryPrecise = true,
797 .pipelineStatisticsQuery = true,
798 .vertexPipelineStoresAndAtomics = true,
799 .fragmentStoresAndAtomics = true,
800 .shaderTessellationAndGeometryPointSize = true,
801 .shaderImageGatherExtended = true,
802 .shaderStorageImageExtendedFormats = true,
803 .shaderStorageImageMultisample = pdevice->rad_info.chip_class >= GFX8,
804 .shaderUniformBufferArrayDynamicIndexing = true,
805 .shaderSampledImageArrayDynamicIndexing = true,
806 .shaderStorageBufferArrayDynamicIndexing = true,
807 .shaderStorageImageArrayDynamicIndexing = true,
808 .shaderStorageImageReadWithoutFormat = true,
809 .shaderStorageImageWriteWithoutFormat = true,
810 .shaderClipDistance = true,
811 .shaderCullDistance = true,
812 .shaderFloat64 = true,
813 .shaderInt64 = true,
814 .shaderInt16 = pdevice->rad_info.chip_class >= GFX9,
815 .sparseBinding = true,
816 .variableMultisampleRate = true,
817 .inheritedQueries = true,
818 };
819 }
820
821 void radv_GetPhysicalDeviceFeatures2(
822 VkPhysicalDevice physicalDevice,
823 VkPhysicalDeviceFeatures2 *pFeatures)
824 {
825 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
826 vk_foreach_struct(ext, pFeatures->pNext) {
827 switch (ext->sType) {
828 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTERS_FEATURES: {
829 VkPhysicalDeviceVariablePointersFeatures *features = (void *)ext;
830 features->variablePointersStorageBuffer = true;
831 features->variablePointers = true;
832 break;
833 }
834 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES: {
835 VkPhysicalDeviceMultiviewFeatures *features = (VkPhysicalDeviceMultiviewFeatures*)ext;
836 features->multiview = true;
837 features->multiviewGeometryShader = true;
838 features->multiviewTessellationShader = true;
839 break;
840 }
841 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES: {
842 VkPhysicalDeviceShaderDrawParametersFeatures *features =
843 (VkPhysicalDeviceShaderDrawParametersFeatures*)ext;
844 features->shaderDrawParameters = true;
845 break;
846 }
847 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_FEATURES: {
848 VkPhysicalDeviceProtectedMemoryFeatures *features =
849 (VkPhysicalDeviceProtectedMemoryFeatures*)ext;
850 features->protectedMemory = false;
851 break;
852 }
853 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES: {
854 VkPhysicalDevice16BitStorageFeatures *features =
855 (VkPhysicalDevice16BitStorageFeatures*)ext;
856 bool enabled = pdevice->rad_info.chip_class >= GFX8;
857 features->storageBuffer16BitAccess = enabled;
858 features->uniformAndStorageBuffer16BitAccess = enabled;
859 features->storagePushConstant16 = enabled;
860 features->storageInputOutput16 = enabled && HAVE_LLVM >= 0x900;
861 break;
862 }
863 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES: {
864 VkPhysicalDeviceSamplerYcbcrConversionFeatures *features =
865 (VkPhysicalDeviceSamplerYcbcrConversionFeatures*)ext;
866 features->samplerYcbcrConversion = true;
867 break;
868 }
869 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES_EXT: {
870 VkPhysicalDeviceDescriptorIndexingFeaturesEXT *features =
871 (VkPhysicalDeviceDescriptorIndexingFeaturesEXT*)ext;
872 features->shaderInputAttachmentArrayDynamicIndexing = true;
873 features->shaderUniformTexelBufferArrayDynamicIndexing = true;
874 features->shaderStorageTexelBufferArrayDynamicIndexing = true;
875 features->shaderUniformBufferArrayNonUniformIndexing = true;
876 features->shaderSampledImageArrayNonUniformIndexing = true;
877 features->shaderStorageBufferArrayNonUniformIndexing = true;
878 features->shaderStorageImageArrayNonUniformIndexing = true;
879 features->shaderInputAttachmentArrayNonUniformIndexing = true;
880 features->shaderUniformTexelBufferArrayNonUniformIndexing = true;
881 features->shaderStorageTexelBufferArrayNonUniformIndexing = true;
882 features->descriptorBindingUniformBufferUpdateAfterBind = true;
883 features->descriptorBindingSampledImageUpdateAfterBind = true;
884 features->descriptorBindingStorageImageUpdateAfterBind = true;
885 features->descriptorBindingStorageBufferUpdateAfterBind = true;
886 features->descriptorBindingUniformTexelBufferUpdateAfterBind = true;
887 features->descriptorBindingStorageTexelBufferUpdateAfterBind = true;
888 features->descriptorBindingUpdateUnusedWhilePending = true;
889 features->descriptorBindingPartiallyBound = true;
890 features->descriptorBindingVariableDescriptorCount = true;
891 features->runtimeDescriptorArray = true;
892 break;
893 }
894 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT: {
895 VkPhysicalDeviceConditionalRenderingFeaturesEXT *features =
896 (VkPhysicalDeviceConditionalRenderingFeaturesEXT*)ext;
897 features->conditionalRendering = true;
898 features->inheritedConditionalRendering = false;
899 break;
900 }
901 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT: {
902 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *features =
903 (VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT *)ext;
904 features->vertexAttributeInstanceRateDivisor = VK_TRUE;
905 features->vertexAttributeInstanceRateZeroDivisor = VK_TRUE;
906 break;
907 }
908 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_FEATURES_EXT: {
909 VkPhysicalDeviceTransformFeedbackFeaturesEXT *features =
910 (VkPhysicalDeviceTransformFeedbackFeaturesEXT*)ext;
911 features->transformFeedback = true;
912 features->geometryStreams = true;
913 break;
914 }
915 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT: {
916 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *features =
917 (VkPhysicalDeviceScalarBlockLayoutFeaturesEXT *)ext;
918 features->scalarBlockLayout = pdevice->rad_info.chip_class >= GFX7;
919 break;
920 }
921 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PRIORITY_FEATURES_EXT: {
922 VkPhysicalDeviceMemoryPriorityFeaturesEXT *features =
923 (VkPhysicalDeviceMemoryPriorityFeaturesEXT *)ext;
924 features->memoryPriority = VK_TRUE;
925 break;
926 }
927 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT: {
928 VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *features =
929 (VkPhysicalDeviceBufferDeviceAddressFeaturesEXT *)ext;
930 features->bufferDeviceAddress = true;
931 features->bufferDeviceAddressCaptureReplay = false;
932 features->bufferDeviceAddressMultiDevice = false;
933 break;
934 }
935 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT: {
936 VkPhysicalDeviceDepthClipEnableFeaturesEXT *features =
937 (VkPhysicalDeviceDepthClipEnableFeaturesEXT *)ext;
938 features->depthClipEnable = true;
939 break;
940 }
941 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_HOST_QUERY_RESET_FEATURES_EXT: {
942 VkPhysicalDeviceHostQueryResetFeaturesEXT *features =
943 (VkPhysicalDeviceHostQueryResetFeaturesEXT *)ext;
944 features->hostQueryReset = true;
945 break;
946 }
947 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR: {
948 VkPhysicalDevice8BitStorageFeaturesKHR *features =
949 (VkPhysicalDevice8BitStorageFeaturesKHR*)ext;
950 bool enabled = pdevice->rad_info.chip_class >= GFX8;
951 features->storageBuffer8BitAccess = enabled;
952 features->uniformAndStorageBuffer8BitAccess = enabled;
953 features->storagePushConstant8 = enabled;
954 break;
955 }
956 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR: {
957 VkPhysicalDeviceFloat16Int8FeaturesKHR *features =
958 (VkPhysicalDeviceFloat16Int8FeaturesKHR*)ext;
959 features->shaderFloat16 = pdevice->rad_info.chip_class >= GFX8;
960 features->shaderInt8 = true;
961 break;
962 }
963 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_ATOMIC_INT64_FEATURES_KHR: {
964 VkPhysicalDeviceShaderAtomicInt64FeaturesKHR *features =
965 (VkPhysicalDeviceShaderAtomicInt64FeaturesKHR *)ext;
966 features->shaderBufferInt64Atomics = HAVE_LLVM >= 0x0900;
967 features->shaderSharedInt64Atomics = HAVE_LLVM >= 0x0900;
968 break;
969 }
970 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_FEATURES_EXT: {
971 VkPhysicalDeviceInlineUniformBlockFeaturesEXT *features =
972 (VkPhysicalDeviceInlineUniformBlockFeaturesEXT *)ext;
973
974 features->inlineUniformBlock = true;
975 features->descriptorBindingInlineUniformBlockUpdateAfterBind = true;
976 break;
977 }
978 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV: {
979 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *features =
980 (VkPhysicalDeviceComputeShaderDerivativesFeaturesNV *)ext;
981 features->computeDerivativeGroupQuads = false;
982 features->computeDerivativeGroupLinear = true;
983 break;
984 }
985 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_YCBCR_IMAGE_ARRAYS_FEATURES_EXT: {
986 VkPhysicalDeviceYcbcrImageArraysFeaturesEXT *features =
987 (VkPhysicalDeviceYcbcrImageArraysFeaturesEXT*)ext;
988 features->ycbcrImageArrays = true;
989 break;
990 }
991 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_UNIFORM_BUFFER_STANDARD_LAYOUT_FEATURES_KHR: {
992 VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *features =
993 (VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR *)ext;
994 features->uniformBufferStandardLayout = true;
995 break;
996 }
997 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INDEX_TYPE_UINT8_FEATURES_EXT: {
998 VkPhysicalDeviceIndexTypeUint8FeaturesEXT *features =
999 (VkPhysicalDeviceIndexTypeUint8FeaturesEXT *)ext;
1000 features->indexTypeUint8 = pdevice->rad_info.chip_class >= GFX8;
1001 break;
1002 }
1003 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGELESS_FRAMEBUFFER_FEATURES_KHR: {
1004 VkPhysicalDeviceImagelessFramebufferFeaturesKHR *features =
1005 (VkPhysicalDeviceImagelessFramebufferFeaturesKHR *)ext;
1006 features->imagelessFramebuffer = true;
1007 break;
1008 }
1009 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR: {
1010 VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *features =
1011 (VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR *)ext;
1012 features->pipelineExecutableInfo = true;
1013 break;
1014 }
1015 default:
1016 break;
1017 }
1018 }
1019 return radv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
1020 }
1021
1022 void radv_GetPhysicalDeviceProperties(
1023 VkPhysicalDevice physicalDevice,
1024 VkPhysicalDeviceProperties* pProperties)
1025 {
1026 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1027 VkSampleCountFlags sample_counts = 0xf;
1028
1029 /* make sure that the entire descriptor set is addressable with a signed
1030 * 32-bit int. So the sum of all limits scaled by descriptor size has to
1031 * be at most 2 GiB. the combined image & samples object count as one of
1032 * both. This limit is for the pipeline layout, not for the set layout, but
1033 * there is no set limit, so we just set a pipeline limit. I don't think
1034 * any app is going to hit this soon. */
1035 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS) /
1036 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
1037 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
1038 32 /* sampler, largest when combined with image */ +
1039 64 /* sampled image */ +
1040 64 /* storage image */);
1041
1042 VkPhysicalDeviceLimits limits = {
1043 .maxImageDimension1D = (1 << 14),
1044 .maxImageDimension2D = (1 << 14),
1045 .maxImageDimension3D = (1 << 11),
1046 .maxImageDimensionCube = (1 << 14),
1047 .maxImageArrayLayers = (1 << 11),
1048 .maxTexelBufferElements = 128 * 1024 * 1024,
1049 .maxUniformBufferRange = UINT32_MAX,
1050 .maxStorageBufferRange = UINT32_MAX,
1051 .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
1052 .maxMemoryAllocationCount = UINT32_MAX,
1053 .maxSamplerAllocationCount = 64 * 1024,
1054 .bufferImageGranularity = 64, /* A cache line */
1055 .sparseAddressSpaceSize = 0xffffffffu, /* buffer max size */
1056 .maxBoundDescriptorSets = MAX_SETS,
1057 .maxPerStageDescriptorSamplers = max_descriptor_set_size,
1058 .maxPerStageDescriptorUniformBuffers = max_descriptor_set_size,
1059 .maxPerStageDescriptorStorageBuffers = max_descriptor_set_size,
1060 .maxPerStageDescriptorSampledImages = max_descriptor_set_size,
1061 .maxPerStageDescriptorStorageImages = max_descriptor_set_size,
1062 .maxPerStageDescriptorInputAttachments = max_descriptor_set_size,
1063 .maxPerStageResources = max_descriptor_set_size,
1064 .maxDescriptorSetSamplers = max_descriptor_set_size,
1065 .maxDescriptorSetUniformBuffers = max_descriptor_set_size,
1066 .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS,
1067 .maxDescriptorSetStorageBuffers = max_descriptor_set_size,
1068 .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS,
1069 .maxDescriptorSetSampledImages = max_descriptor_set_size,
1070 .maxDescriptorSetStorageImages = max_descriptor_set_size,
1071 .maxDescriptorSetInputAttachments = max_descriptor_set_size,
1072 .maxVertexInputAttributes = MAX_VERTEX_ATTRIBS,
1073 .maxVertexInputBindings = MAX_VBS,
1074 .maxVertexInputAttributeOffset = 2047,
1075 .maxVertexInputBindingStride = 2048,
1076 .maxVertexOutputComponents = 128,
1077 .maxTessellationGenerationLevel = 64,
1078 .maxTessellationPatchSize = 32,
1079 .maxTessellationControlPerVertexInputComponents = 128,
1080 .maxTessellationControlPerVertexOutputComponents = 128,
1081 .maxTessellationControlPerPatchOutputComponents = 120,
1082 .maxTessellationControlTotalOutputComponents = 4096,
1083 .maxTessellationEvaluationInputComponents = 128,
1084 .maxTessellationEvaluationOutputComponents = 128,
1085 .maxGeometryShaderInvocations = 127,
1086 .maxGeometryInputComponents = 64,
1087 .maxGeometryOutputComponents = 128,
1088 .maxGeometryOutputVertices = 256,
1089 .maxGeometryTotalOutputComponents = 1024,
1090 .maxFragmentInputComponents = 128,
1091 .maxFragmentOutputAttachments = 8,
1092 .maxFragmentDualSrcAttachments = 1,
1093 .maxFragmentCombinedOutputResources = 8,
1094 .maxComputeSharedMemorySize = 32768,
1095 .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
1096 .maxComputeWorkGroupInvocations = 2048,
1097 .maxComputeWorkGroupSize = {
1098 2048,
1099 2048,
1100 2048
1101 },
1102 .subPixelPrecisionBits = 8,
1103 .subTexelPrecisionBits = 8,
1104 .mipmapPrecisionBits = 8,
1105 .maxDrawIndexedIndexValue = UINT32_MAX,
1106 .maxDrawIndirectCount = UINT32_MAX,
1107 .maxSamplerLodBias = 16,
1108 .maxSamplerAnisotropy = 16,
1109 .maxViewports = MAX_VIEWPORTS,
1110 .maxViewportDimensions = { (1 << 14), (1 << 14) },
1111 .viewportBoundsRange = { INT16_MIN, INT16_MAX },
1112 .viewportSubPixelBits = 8,
1113 .minMemoryMapAlignment = 4096, /* A page */
1114 .minTexelBufferOffsetAlignment = 1,
1115 .minUniformBufferOffsetAlignment = 4,
1116 .minStorageBufferOffsetAlignment = 4,
1117 .minTexelOffset = -32,
1118 .maxTexelOffset = 31,
1119 .minTexelGatherOffset = -32,
1120 .maxTexelGatherOffset = 31,
1121 .minInterpolationOffset = -2,
1122 .maxInterpolationOffset = 2,
1123 .subPixelInterpolationOffsetBits = 8,
1124 .maxFramebufferWidth = (1 << 14),
1125 .maxFramebufferHeight = (1 << 14),
1126 .maxFramebufferLayers = (1 << 10),
1127 .framebufferColorSampleCounts = sample_counts,
1128 .framebufferDepthSampleCounts = sample_counts,
1129 .framebufferStencilSampleCounts = sample_counts,
1130 .framebufferNoAttachmentsSampleCounts = sample_counts,
1131 .maxColorAttachments = MAX_RTS,
1132 .sampledImageColorSampleCounts = sample_counts,
1133 .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
1134 .sampledImageDepthSampleCounts = sample_counts,
1135 .sampledImageStencilSampleCounts = sample_counts,
1136 .storageImageSampleCounts = pdevice->rad_info.chip_class >= GFX8 ? sample_counts : VK_SAMPLE_COUNT_1_BIT,
1137 .maxSampleMaskWords = 1,
1138 .timestampComputeAndGraphics = true,
1139 .timestampPeriod = 1000000.0 / pdevice->rad_info.clock_crystal_freq,
1140 .maxClipDistances = 8,
1141 .maxCullDistances = 8,
1142 .maxCombinedClipAndCullDistances = 8,
1143 .discreteQueuePriorities = 2,
1144 .pointSizeRange = { 0.0, 8192.0 },
1145 .lineWidthRange = { 0.0, 7.9921875 },
1146 .pointSizeGranularity = (1.0 / 8.0),
1147 .lineWidthGranularity = (1.0 / 128.0),
1148 .strictLines = false, /* FINISHME */
1149 .standardSampleLocations = true,
1150 .optimalBufferCopyOffsetAlignment = 128,
1151 .optimalBufferCopyRowPitchAlignment = 128,
1152 .nonCoherentAtomSize = 64,
1153 };
1154
1155 *pProperties = (VkPhysicalDeviceProperties) {
1156 .apiVersion = radv_physical_device_api_version(pdevice),
1157 .driverVersion = vk_get_driver_version(),
1158 .vendorID = ATI_VENDOR_ID,
1159 .deviceID = pdevice->rad_info.pci_id,
1160 .deviceType = pdevice->rad_info.has_dedicated_vram ? VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU : VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
1161 .limits = limits,
1162 .sparseProperties = {0},
1163 };
1164
1165 strcpy(pProperties->deviceName, pdevice->name);
1166 memcpy(pProperties->pipelineCacheUUID, pdevice->cache_uuid, VK_UUID_SIZE);
1167 }
1168
1169 void radv_GetPhysicalDeviceProperties2(
1170 VkPhysicalDevice physicalDevice,
1171 VkPhysicalDeviceProperties2 *pProperties)
1172 {
1173 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1174 radv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
1175
1176 vk_foreach_struct(ext, pProperties->pNext) {
1177 switch (ext->sType) {
1178 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
1179 VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
1180 (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
1181 properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
1182 break;
1183 }
1184 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES: {
1185 VkPhysicalDeviceIDProperties *properties = (VkPhysicalDeviceIDProperties*)ext;
1186 memcpy(properties->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
1187 memcpy(properties->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
1188 properties->deviceLUIDValid = false;
1189 break;
1190 }
1191 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES: {
1192 VkPhysicalDeviceMultiviewProperties *properties = (VkPhysicalDeviceMultiviewProperties*)ext;
1193 properties->maxMultiviewViewCount = MAX_VIEWS;
1194 properties->maxMultiviewInstanceIndex = INT_MAX;
1195 break;
1196 }
1197 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES: {
1198 VkPhysicalDevicePointClippingProperties *properties =
1199 (VkPhysicalDevicePointClippingProperties*)ext;
1200 properties->pointClippingBehavior = VK_POINT_CLIPPING_BEHAVIOR_ALL_CLIP_PLANES;
1201 break;
1202 }
1203 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT: {
1204 VkPhysicalDeviceDiscardRectanglePropertiesEXT *properties =
1205 (VkPhysicalDeviceDiscardRectanglePropertiesEXT*)ext;
1206 properties->maxDiscardRectangles = MAX_DISCARD_RECTANGLES;
1207 break;
1208 }
1209 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT: {
1210 VkPhysicalDeviceExternalMemoryHostPropertiesEXT *properties =
1211 (VkPhysicalDeviceExternalMemoryHostPropertiesEXT *) ext;
1212 properties->minImportedHostPointerAlignment = 4096;
1213 break;
1214 }
1215 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES: {
1216 VkPhysicalDeviceSubgroupProperties *properties =
1217 (VkPhysicalDeviceSubgroupProperties*)ext;
1218 properties->subgroupSize = 64;
1219 properties->supportedStages = VK_SHADER_STAGE_ALL;
1220 properties->supportedOperations =
1221 VK_SUBGROUP_FEATURE_BASIC_BIT |
1222 VK_SUBGROUP_FEATURE_BALLOT_BIT |
1223 VK_SUBGROUP_FEATURE_QUAD_BIT |
1224 VK_SUBGROUP_FEATURE_VOTE_BIT;
1225 if (pdevice->rad_info.chip_class >= GFX8) {
1226 properties->supportedOperations |=
1227 VK_SUBGROUP_FEATURE_ARITHMETIC_BIT |
1228 VK_SUBGROUP_FEATURE_SHUFFLE_BIT |
1229 VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT;
1230 }
1231 properties->quadOperationsInAllStages = true;
1232 break;
1233 }
1234 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_3_PROPERTIES: {
1235 VkPhysicalDeviceMaintenance3Properties *properties =
1236 (VkPhysicalDeviceMaintenance3Properties*)ext;
1237 /* Make sure everything is addressable by a signed 32-bit int, and
1238 * our largest descriptors are 96 bytes. */
1239 properties->maxPerSetDescriptors = (1ull << 31) / 96;
1240 /* Our buffer size fields allow only this much */
1241 properties->maxMemoryAllocationSize = 0xFFFFFFFFull;
1242 break;
1243 }
1244 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT: {
1245 VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *properties =
1246 (VkPhysicalDeviceSamplerFilterMinmaxPropertiesEXT *)ext;
1247 /* GFX6-8 only support single channel min/max filter. */
1248 properties->filterMinmaxImageComponentMapping = pdevice->rad_info.chip_class >= GFX9;
1249 properties->filterMinmaxSingleComponentFormats = true;
1250 break;
1251 }
1252 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_AMD: {
1253 VkPhysicalDeviceShaderCorePropertiesAMD *properties =
1254 (VkPhysicalDeviceShaderCorePropertiesAMD *)ext;
1255
1256 /* Shader engines. */
1257 properties->shaderEngineCount =
1258 pdevice->rad_info.max_se;
1259 properties->shaderArraysPerEngineCount =
1260 pdevice->rad_info.max_sh_per_se;
1261 properties->computeUnitsPerShaderArray =
1262 pdevice->rad_info.num_good_cu_per_sh;
1263 properties->simdPerComputeUnit = 4;
1264 properties->wavefrontsPerSimd =
1265 pdevice->rad_info.family == CHIP_TONGA ||
1266 pdevice->rad_info.family == CHIP_ICELAND ||
1267 pdevice->rad_info.family == CHIP_POLARIS10 ||
1268 pdevice->rad_info.family == CHIP_POLARIS11 ||
1269 pdevice->rad_info.family == CHIP_POLARIS12 ||
1270 pdevice->rad_info.family == CHIP_VEGAM ? 8 : 10;
1271 properties->wavefrontSize = 64;
1272
1273 /* SGPR. */
1274 properties->sgprsPerSimd =
1275 ac_get_num_physical_sgprs(pdevice->rad_info.chip_class);
1276 properties->minSgprAllocation =
1277 pdevice->rad_info.chip_class >= GFX8 ? 16 : 8;
1278 properties->maxSgprAllocation =
1279 pdevice->rad_info.family == CHIP_TONGA ||
1280 pdevice->rad_info.family == CHIP_ICELAND ? 96 : 104;
1281 properties->sgprAllocationGranularity =
1282 pdevice->rad_info.chip_class >= GFX8 ? 16 : 8;
1283
1284 /* VGPR. */
1285 properties->vgprsPerSimd = RADV_NUM_PHYSICAL_VGPRS;
1286 properties->minVgprAllocation = 4;
1287 properties->maxVgprAllocation = 256;
1288 properties->vgprAllocationGranularity = 4;
1289 break;
1290 }
1291 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_CORE_PROPERTIES_2_AMD: {
1292 VkPhysicalDeviceShaderCoreProperties2AMD *properties =
1293 (VkPhysicalDeviceShaderCoreProperties2AMD *)ext;
1294
1295 properties->shaderCoreFeatures = 0;
1296 properties->activeComputeUnitCount =
1297 pdevice->rad_info.num_good_compute_units;
1298 break;
1299 }
1300 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT: {
1301 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *properties =
1302 (VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT *)ext;
1303 properties->maxVertexAttribDivisor = UINT32_MAX;
1304 break;
1305 }
1306 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_PROPERTIES_EXT: {
1307 VkPhysicalDeviceDescriptorIndexingPropertiesEXT *properties =
1308 (VkPhysicalDeviceDescriptorIndexingPropertiesEXT*)ext;
1309 properties->maxUpdateAfterBindDescriptorsInAllPools = UINT32_MAX / 64;
1310 properties->shaderUniformBufferArrayNonUniformIndexingNative = false;
1311 properties->shaderSampledImageArrayNonUniformIndexingNative = false;
1312 properties->shaderStorageBufferArrayNonUniformIndexingNative = false;
1313 properties->shaderStorageImageArrayNonUniformIndexingNative = false;
1314 properties->shaderInputAttachmentArrayNonUniformIndexingNative = false;
1315 properties->robustBufferAccessUpdateAfterBind = false;
1316 properties->quadDivergentImplicitLod = false;
1317
1318 size_t max_descriptor_set_size = ((1ull << 31) - 16 * MAX_DYNAMIC_BUFFERS -
1319 MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_INLINE_UNIFORM_BLOCK_COUNT) /
1320 (32 /* uniform buffer, 32 due to potential space wasted on alignment */ +
1321 32 /* storage buffer, 32 due to potential space wasted on alignment */ +
1322 32 /* sampler, largest when combined with image */ +
1323 64 /* sampled image */ +
1324 64 /* storage image */);
1325 properties->maxPerStageDescriptorUpdateAfterBindSamplers = max_descriptor_set_size;
1326 properties->maxPerStageDescriptorUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1327 properties->maxPerStageDescriptorUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1328 properties->maxPerStageDescriptorUpdateAfterBindSampledImages = max_descriptor_set_size;
1329 properties->maxPerStageDescriptorUpdateAfterBindStorageImages = max_descriptor_set_size;
1330 properties->maxPerStageDescriptorUpdateAfterBindInputAttachments = max_descriptor_set_size;
1331 properties->maxPerStageUpdateAfterBindResources = max_descriptor_set_size;
1332 properties->maxDescriptorSetUpdateAfterBindSamplers = max_descriptor_set_size;
1333 properties->maxDescriptorSetUpdateAfterBindUniformBuffers = max_descriptor_set_size;
1334 properties->maxDescriptorSetUpdateAfterBindUniformBuffersDynamic = MAX_DYNAMIC_UNIFORM_BUFFERS;
1335 properties->maxDescriptorSetUpdateAfterBindStorageBuffers = max_descriptor_set_size;
1336 properties->maxDescriptorSetUpdateAfterBindStorageBuffersDynamic = MAX_DYNAMIC_STORAGE_BUFFERS;
1337 properties->maxDescriptorSetUpdateAfterBindSampledImages = max_descriptor_set_size;
1338 properties->maxDescriptorSetUpdateAfterBindStorageImages = max_descriptor_set_size;
1339 properties->maxDescriptorSetUpdateAfterBindInputAttachments = max_descriptor_set_size;
1340 break;
1341 }
1342 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROTECTED_MEMORY_PROPERTIES: {
1343 VkPhysicalDeviceProtectedMemoryProperties *properties =
1344 (VkPhysicalDeviceProtectedMemoryProperties *)ext;
1345 properties->protectedNoFault = false;
1346 break;
1347 }
1348 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT: {
1349 VkPhysicalDeviceConservativeRasterizationPropertiesEXT *properties =
1350 (VkPhysicalDeviceConservativeRasterizationPropertiesEXT *)ext;
1351 properties->primitiveOverestimationSize = 0;
1352 properties->maxExtraPrimitiveOverestimationSize = 0;
1353 properties->extraPrimitiveOverestimationSizeGranularity = 0;
1354 properties->primitiveUnderestimation = VK_FALSE;
1355 properties->conservativePointAndLineRasterization = VK_FALSE;
1356 properties->degenerateTrianglesRasterized = VK_FALSE;
1357 properties->degenerateLinesRasterized = VK_FALSE;
1358 properties->fullyCoveredFragmentShaderInputVariable = VK_FALSE;
1359 properties->conservativeRasterizationPostDepthCoverage = VK_FALSE;
1360 break;
1361 }
1362 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT: {
1363 VkPhysicalDevicePCIBusInfoPropertiesEXT *properties =
1364 (VkPhysicalDevicePCIBusInfoPropertiesEXT *)ext;
1365 properties->pciDomain = pdevice->bus_info.domain;
1366 properties->pciBus = pdevice->bus_info.bus;
1367 properties->pciDevice = pdevice->bus_info.dev;
1368 properties->pciFunction = pdevice->bus_info.func;
1369 break;
1370 }
1371 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR: {
1372 VkPhysicalDeviceDriverPropertiesKHR *driver_props =
1373 (VkPhysicalDeviceDriverPropertiesKHR *) ext;
1374
1375 driver_props->driverID = VK_DRIVER_ID_MESA_RADV_KHR;
1376 snprintf(driver_props->driverName, VK_MAX_DRIVER_NAME_SIZE_KHR, "radv");
1377 snprintf(driver_props->driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR,
1378 "Mesa " PACKAGE_VERSION MESA_GIT_SHA1
1379 " (LLVM " MESA_LLVM_VERSION_STRING ")");
1380
1381 driver_props->conformanceVersion = (VkConformanceVersionKHR) {
1382 .major = 1,
1383 .minor = 1,
1384 .subminor = 2,
1385 .patch = 0,
1386 };
1387 break;
1388 }
1389 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TRANSFORM_FEEDBACK_PROPERTIES_EXT: {
1390 VkPhysicalDeviceTransformFeedbackPropertiesEXT *properties =
1391 (VkPhysicalDeviceTransformFeedbackPropertiesEXT *)ext;
1392 properties->maxTransformFeedbackStreams = MAX_SO_STREAMS;
1393 properties->maxTransformFeedbackBuffers = MAX_SO_BUFFERS;
1394 properties->maxTransformFeedbackBufferSize = UINT32_MAX;
1395 properties->maxTransformFeedbackStreamDataSize = 512;
1396 properties->maxTransformFeedbackBufferDataSize = UINT32_MAX;
1397 properties->maxTransformFeedbackBufferDataStride = 512;
1398 properties->transformFeedbackQueries = true;
1399 properties->transformFeedbackStreamsLinesTriangles = true;
1400 properties->transformFeedbackRasterizationStreamSelect = false;
1401 properties->transformFeedbackDraw = true;
1402 break;
1403 }
1404 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_INLINE_UNIFORM_BLOCK_PROPERTIES_EXT: {
1405 VkPhysicalDeviceInlineUniformBlockPropertiesEXT *props =
1406 (VkPhysicalDeviceInlineUniformBlockPropertiesEXT *)ext;
1407
1408 props->maxInlineUniformBlockSize = MAX_INLINE_UNIFORM_BLOCK_SIZE;
1409 props->maxPerStageDescriptorInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_SETS;
1410 props->maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_SIZE * MAX_SETS;
1411 props->maxDescriptorSetInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_COUNT;
1412 props->maxDescriptorSetUpdateAfterBindInlineUniformBlocks = MAX_INLINE_UNIFORM_BLOCK_COUNT;
1413 break;
1414 }
1415 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLE_LOCATIONS_PROPERTIES_EXT: {
1416 VkPhysicalDeviceSampleLocationsPropertiesEXT *properties =
1417 (VkPhysicalDeviceSampleLocationsPropertiesEXT *)ext;
1418 properties->sampleLocationSampleCounts = VK_SAMPLE_COUNT_2_BIT |
1419 VK_SAMPLE_COUNT_4_BIT |
1420 VK_SAMPLE_COUNT_8_BIT;
1421 properties->maxSampleLocationGridSize = (VkExtent2D){ 2 , 2 };
1422 properties->sampleLocationCoordinateRange[0] = 0.0f;
1423 properties->sampleLocationCoordinateRange[1] = 0.9375f;
1424 properties->sampleLocationSubPixelBits = 4;
1425 properties->variableSampleLocations = VK_FALSE;
1426 break;
1427 }
1428 case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_STENCIL_RESOLVE_PROPERTIES_KHR: {
1429 VkPhysicalDeviceDepthStencilResolvePropertiesKHR *properties =
1430 (VkPhysicalDeviceDepthStencilResolvePropertiesKHR *)ext;
1431
1432 /* We support all of the depth resolve modes */
1433 properties->supportedDepthResolveModes =
1434 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1435 VK_RESOLVE_MODE_AVERAGE_BIT_KHR |
1436 VK_RESOLVE_MODE_MIN_BIT_KHR |
1437 VK_RESOLVE_MODE_MAX_BIT_KHR;
1438
1439 /* Average doesn't make sense for stencil so we don't support that */
1440 properties->supportedStencilResolveModes =
1441 VK_RESOLVE_MODE_SAMPLE_ZERO_BIT_KHR |
1442 VK_RESOLVE_MODE_MIN_BIT_KHR |
1443 VK_RESOLVE_MODE_MAX_BIT_KHR;
1444
1445 properties->independentResolveNone = VK_TRUE;
1446 properties->independentResolve = VK_TRUE;
1447 break;
1448 }
1449 default:
1450 break;
1451 }
1452 }
1453 }
1454
1455 static void radv_get_physical_device_queue_family_properties(
1456 struct radv_physical_device* pdevice,
1457 uint32_t* pCount,
1458 VkQueueFamilyProperties** pQueueFamilyProperties)
1459 {
1460 int num_queue_families = 1;
1461 int idx;
1462 if (pdevice->rad_info.num_compute_rings > 0 &&
1463 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE))
1464 num_queue_families++;
1465
1466 if (pQueueFamilyProperties == NULL) {
1467 *pCount = num_queue_families;
1468 return;
1469 }
1470
1471 if (!*pCount)
1472 return;
1473
1474 idx = 0;
1475 if (*pCount >= 1) {
1476 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
1477 .queueFlags = VK_QUEUE_GRAPHICS_BIT |
1478 VK_QUEUE_COMPUTE_BIT |
1479 VK_QUEUE_TRANSFER_BIT |
1480 VK_QUEUE_SPARSE_BINDING_BIT,
1481 .queueCount = 1,
1482 .timestampValidBits = 64,
1483 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
1484 };
1485 idx++;
1486 }
1487
1488 if (pdevice->rad_info.num_compute_rings > 0 &&
1489 !(pdevice->instance->debug_flags & RADV_DEBUG_NO_COMPUTE_QUEUE)) {
1490 if (*pCount > idx) {
1491 *pQueueFamilyProperties[idx] = (VkQueueFamilyProperties) {
1492 .queueFlags = VK_QUEUE_COMPUTE_BIT |
1493 VK_QUEUE_TRANSFER_BIT |
1494 VK_QUEUE_SPARSE_BINDING_BIT,
1495 .queueCount = pdevice->rad_info.num_compute_rings,
1496 .timestampValidBits = 64,
1497 .minImageTransferGranularity = (VkExtent3D) { 1, 1, 1 },
1498 };
1499 idx++;
1500 }
1501 }
1502 *pCount = idx;
1503 }
1504
1505 void radv_GetPhysicalDeviceQueueFamilyProperties(
1506 VkPhysicalDevice physicalDevice,
1507 uint32_t* pCount,
1508 VkQueueFamilyProperties* pQueueFamilyProperties)
1509 {
1510 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1511 if (!pQueueFamilyProperties) {
1512 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
1513 return;
1514 }
1515 VkQueueFamilyProperties *properties[] = {
1516 pQueueFamilyProperties + 0,
1517 pQueueFamilyProperties + 1,
1518 pQueueFamilyProperties + 2,
1519 };
1520 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
1521 assert(*pCount <= 3);
1522 }
1523
1524 void radv_GetPhysicalDeviceQueueFamilyProperties2(
1525 VkPhysicalDevice physicalDevice,
1526 uint32_t* pCount,
1527 VkQueueFamilyProperties2 *pQueueFamilyProperties)
1528 {
1529 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
1530 if (!pQueueFamilyProperties) {
1531 radv_get_physical_device_queue_family_properties(pdevice, pCount, NULL);
1532 return;
1533 }
1534 VkQueueFamilyProperties *properties[] = {
1535 &pQueueFamilyProperties[0].queueFamilyProperties,
1536 &pQueueFamilyProperties[1].queueFamilyProperties,
1537 &pQueueFamilyProperties[2].queueFamilyProperties,
1538 };
1539 radv_get_physical_device_queue_family_properties(pdevice, pCount, properties);
1540 assert(*pCount <= 3);
1541 }
1542
1543 void radv_GetPhysicalDeviceMemoryProperties(
1544 VkPhysicalDevice physicalDevice,
1545 VkPhysicalDeviceMemoryProperties *pMemoryProperties)
1546 {
1547 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
1548
1549 *pMemoryProperties = physical_device->memory_properties;
1550 }
1551
1552 static void
1553 radv_get_memory_budget_properties(VkPhysicalDevice physicalDevice,
1554 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memoryBudget)
1555 {
1556 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
1557 VkPhysicalDeviceMemoryProperties *memory_properties = &device->memory_properties;
1558 uint64_t visible_vram_size = radv_get_visible_vram_size(device);
1559 uint64_t vram_size = radv_get_vram_size(device);
1560 uint64_t gtt_size = device->rad_info.gart_size;
1561 uint64_t heap_budget, heap_usage;
1562
1563 /* For all memory heaps, the computation of budget is as follow:
1564 * heap_budget = heap_size - global_heap_usage + app_heap_usage
1565 *
1566 * The Vulkan spec 1.1.97 says that the budget should include any
1567 * currently allocated device memory.
1568 *
1569 * Note that the application heap usages are not really accurate (eg.
1570 * in presence of shared buffers).
1571 */
1572 for (int i = 0; i < device->memory_properties.memoryTypeCount; i++) {
1573 uint32_t heap_index = device->memory_properties.memoryTypes[i].heapIndex;
1574
1575 switch (device->mem_type_indices[i]) {
1576 case RADV_MEM_TYPE_VRAM:
1577 heap_usage = device->ws->query_value(device->ws,
1578 RADEON_ALLOCATED_VRAM);
1579
1580 heap_budget = vram_size -
1581 device->ws->query_value(device->ws, RADEON_VRAM_USAGE) +
1582 heap_usage;
1583
1584 memoryBudget->heapBudget[heap_index] = heap_budget;
1585 memoryBudget->heapUsage[heap_index] = heap_usage;
1586 break;
1587 case RADV_MEM_TYPE_VRAM_CPU_ACCESS:
1588 heap_usage = device->ws->query_value(device->ws,
1589 RADEON_ALLOCATED_VRAM_VIS);
1590
1591 heap_budget = visible_vram_size -
1592 device->ws->query_value(device->ws, RADEON_VRAM_VIS_USAGE) +
1593 heap_usage;
1594
1595 memoryBudget->heapBudget[heap_index] = heap_budget;
1596 memoryBudget->heapUsage[heap_index] = heap_usage;
1597 break;
1598 case RADV_MEM_TYPE_GTT_WRITE_COMBINE:
1599 heap_usage = device->ws->query_value(device->ws,
1600 RADEON_ALLOCATED_GTT);
1601
1602 heap_budget = gtt_size -
1603 device->ws->query_value(device->ws, RADEON_GTT_USAGE) +
1604 heap_usage;
1605
1606 memoryBudget->heapBudget[heap_index] = heap_budget;
1607 memoryBudget->heapUsage[heap_index] = heap_usage;
1608 break;
1609 default:
1610 break;
1611 }
1612 }
1613
1614 /* The heapBudget and heapUsage values must be zero for array elements
1615 * greater than or equal to
1616 * VkPhysicalDeviceMemoryProperties::memoryHeapCount.
1617 */
1618 for (uint32_t i = memory_properties->memoryHeapCount; i < VK_MAX_MEMORY_HEAPS; i++) {
1619 memoryBudget->heapBudget[i] = 0;
1620 memoryBudget->heapUsage[i] = 0;
1621 }
1622 }
1623
1624 void radv_GetPhysicalDeviceMemoryProperties2(
1625 VkPhysicalDevice physicalDevice,
1626 VkPhysicalDeviceMemoryProperties2 *pMemoryProperties)
1627 {
1628 radv_GetPhysicalDeviceMemoryProperties(physicalDevice,
1629 &pMemoryProperties->memoryProperties);
1630
1631 VkPhysicalDeviceMemoryBudgetPropertiesEXT *memory_budget =
1632 vk_find_struct(pMemoryProperties->pNext,
1633 PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT);
1634 if (memory_budget)
1635 radv_get_memory_budget_properties(physicalDevice, memory_budget);
1636 }
1637
1638 VkResult radv_GetMemoryHostPointerPropertiesEXT(
1639 VkDevice _device,
1640 VkExternalMemoryHandleTypeFlagBits handleType,
1641 const void *pHostPointer,
1642 VkMemoryHostPointerPropertiesEXT *pMemoryHostPointerProperties)
1643 {
1644 RADV_FROM_HANDLE(radv_device, device, _device);
1645
1646 switch (handleType)
1647 {
1648 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT: {
1649 const struct radv_physical_device *physical_device = device->physical_device;
1650 uint32_t memoryTypeBits = 0;
1651 for (int i = 0; i < physical_device->memory_properties.memoryTypeCount; i++) {
1652 if (physical_device->mem_type_indices[i] == RADV_MEM_TYPE_GTT_CACHED) {
1653 memoryTypeBits = (1 << i);
1654 break;
1655 }
1656 }
1657 pMemoryHostPointerProperties->memoryTypeBits = memoryTypeBits;
1658 return VK_SUCCESS;
1659 }
1660 default:
1661 return VK_ERROR_INVALID_EXTERNAL_HANDLE;
1662 }
1663 }
1664
1665 static enum radeon_ctx_priority
1666 radv_get_queue_global_priority(const VkDeviceQueueGlobalPriorityCreateInfoEXT *pObj)
1667 {
1668 /* Default to MEDIUM when a specific global priority isn't requested */
1669 if (!pObj)
1670 return RADEON_CTX_PRIORITY_MEDIUM;
1671
1672 switch(pObj->globalPriority) {
1673 case VK_QUEUE_GLOBAL_PRIORITY_REALTIME_EXT:
1674 return RADEON_CTX_PRIORITY_REALTIME;
1675 case VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT:
1676 return RADEON_CTX_PRIORITY_HIGH;
1677 case VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT:
1678 return RADEON_CTX_PRIORITY_MEDIUM;
1679 case VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT:
1680 return RADEON_CTX_PRIORITY_LOW;
1681 default:
1682 unreachable("Illegal global priority value");
1683 return RADEON_CTX_PRIORITY_INVALID;
1684 }
1685 }
1686
1687 static int
1688 radv_queue_init(struct radv_device *device, struct radv_queue *queue,
1689 uint32_t queue_family_index, int idx,
1690 VkDeviceQueueCreateFlags flags,
1691 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority)
1692 {
1693 queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1694 queue->device = device;
1695 queue->queue_family_index = queue_family_index;
1696 queue->queue_idx = idx;
1697 queue->priority = radv_get_queue_global_priority(global_priority);
1698 queue->flags = flags;
1699
1700 queue->hw_ctx = device->ws->ctx_create(device->ws, queue->priority);
1701 if (!queue->hw_ctx)
1702 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1703
1704 return VK_SUCCESS;
1705 }
1706
1707 static void
1708 radv_queue_finish(struct radv_queue *queue)
1709 {
1710 if (queue->hw_ctx)
1711 queue->device->ws->ctx_destroy(queue->hw_ctx);
1712
1713 if (queue->initial_full_flush_preamble_cs)
1714 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
1715 if (queue->initial_preamble_cs)
1716 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
1717 if (queue->continue_preamble_cs)
1718 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
1719 if (queue->descriptor_bo)
1720 queue->device->ws->buffer_destroy(queue->descriptor_bo);
1721 if (queue->scratch_bo)
1722 queue->device->ws->buffer_destroy(queue->scratch_bo);
1723 if (queue->esgs_ring_bo)
1724 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
1725 if (queue->gsvs_ring_bo)
1726 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
1727 if (queue->tess_rings_bo)
1728 queue->device->ws->buffer_destroy(queue->tess_rings_bo);
1729 if (queue->compute_scratch_bo)
1730 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
1731 }
1732
1733 static void
1734 radv_bo_list_init(struct radv_bo_list *bo_list)
1735 {
1736 pthread_mutex_init(&bo_list->mutex, NULL);
1737 bo_list->list.count = bo_list->capacity = 0;
1738 bo_list->list.bos = NULL;
1739 }
1740
1741 static void
1742 radv_bo_list_finish(struct radv_bo_list *bo_list)
1743 {
1744 free(bo_list->list.bos);
1745 pthread_mutex_destroy(&bo_list->mutex);
1746 }
1747
1748 static VkResult radv_bo_list_add(struct radv_device *device,
1749 struct radeon_winsys_bo *bo)
1750 {
1751 struct radv_bo_list *bo_list = &device->bo_list;
1752
1753 if (bo->is_local)
1754 return VK_SUCCESS;
1755
1756 if (unlikely(!device->use_global_bo_list))
1757 return VK_SUCCESS;
1758
1759 pthread_mutex_lock(&bo_list->mutex);
1760 if (bo_list->list.count == bo_list->capacity) {
1761 unsigned capacity = MAX2(4, bo_list->capacity * 2);
1762 void *data = realloc(bo_list->list.bos, capacity * sizeof(struct radeon_winsys_bo*));
1763
1764 if (!data) {
1765 pthread_mutex_unlock(&bo_list->mutex);
1766 return VK_ERROR_OUT_OF_HOST_MEMORY;
1767 }
1768
1769 bo_list->list.bos = (struct radeon_winsys_bo**)data;
1770 bo_list->capacity = capacity;
1771 }
1772
1773 bo_list->list.bos[bo_list->list.count++] = bo;
1774 pthread_mutex_unlock(&bo_list->mutex);
1775 return VK_SUCCESS;
1776 }
1777
1778 static void radv_bo_list_remove(struct radv_device *device,
1779 struct radeon_winsys_bo *bo)
1780 {
1781 struct radv_bo_list *bo_list = &device->bo_list;
1782
1783 if (bo->is_local)
1784 return;
1785
1786 if (unlikely(!device->use_global_bo_list))
1787 return;
1788
1789 pthread_mutex_lock(&bo_list->mutex);
1790 for(unsigned i = 0; i < bo_list->list.count; ++i) {
1791 if (bo_list->list.bos[i] == bo) {
1792 bo_list->list.bos[i] = bo_list->list.bos[bo_list->list.count - 1];
1793 --bo_list->list.count;
1794 break;
1795 }
1796 }
1797 pthread_mutex_unlock(&bo_list->mutex);
1798 }
1799
1800 static void
1801 radv_device_init_gs_info(struct radv_device *device)
1802 {
1803 device->gs_table_depth = ac_get_gs_table_depth(device->physical_device->rad_info.chip_class,
1804 device->physical_device->rad_info.family);
1805 }
1806
1807 static int radv_get_device_extension_index(const char *name)
1808 {
1809 for (unsigned i = 0; i < RADV_DEVICE_EXTENSION_COUNT; ++i) {
1810 if (strcmp(name, radv_device_extensions[i].extensionName) == 0)
1811 return i;
1812 }
1813 return -1;
1814 }
1815
1816 static int
1817 radv_get_int_debug_option(const char *name, int default_value)
1818 {
1819 const char *str;
1820 int result;
1821
1822 str = getenv(name);
1823 if (!str) {
1824 result = default_value;
1825 } else {
1826 char *endptr;
1827
1828 result = strtol(str, &endptr, 0);
1829 if (str == endptr) {
1830 /* No digits founs. */
1831 result = default_value;
1832 }
1833 }
1834
1835 return result;
1836 }
1837
1838 VkResult radv_CreateDevice(
1839 VkPhysicalDevice physicalDevice,
1840 const VkDeviceCreateInfo* pCreateInfo,
1841 const VkAllocationCallbacks* pAllocator,
1842 VkDevice* pDevice)
1843 {
1844 RADV_FROM_HANDLE(radv_physical_device, physical_device, physicalDevice);
1845 VkResult result;
1846 struct radv_device *device;
1847
1848 bool keep_shader_info = false;
1849
1850 /* Check enabled features */
1851 if (pCreateInfo->pEnabledFeatures) {
1852 VkPhysicalDeviceFeatures supported_features;
1853 radv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
1854 VkBool32 *supported_feature = (VkBool32 *)&supported_features;
1855 VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
1856 unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
1857 for (uint32_t i = 0; i < num_features; i++) {
1858 if (enabled_feature[i] && !supported_feature[i])
1859 return vk_error(physical_device->instance, VK_ERROR_FEATURE_NOT_PRESENT);
1860 }
1861 }
1862
1863 device = vk_zalloc2(&physical_device->instance->alloc, pAllocator,
1864 sizeof(*device), 8,
1865 VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1866 if (!device)
1867 return vk_error(physical_device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
1868
1869 device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
1870 device->instance = physical_device->instance;
1871 device->physical_device = physical_device;
1872
1873 device->ws = physical_device->ws;
1874 if (pAllocator)
1875 device->alloc = *pAllocator;
1876 else
1877 device->alloc = physical_device->instance->alloc;
1878
1879 for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
1880 const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
1881 int index = radv_get_device_extension_index(ext_name);
1882 if (index < 0 || !physical_device->supported_extensions.extensions[index]) {
1883 vk_free(&device->alloc, device);
1884 return vk_error(physical_device->instance, VK_ERROR_EXTENSION_NOT_PRESENT);
1885 }
1886
1887 device->enabled_extensions.extensions[index] = true;
1888 }
1889
1890 keep_shader_info = device->enabled_extensions.AMD_shader_info;
1891
1892 /* With update after bind we can't attach bo's to the command buffer
1893 * from the descriptor set anymore, so we have to use a global BO list.
1894 */
1895 device->use_global_bo_list =
1896 (device->instance->perftest_flags & RADV_PERFTEST_BO_LIST) ||
1897 device->enabled_extensions.EXT_descriptor_indexing ||
1898 device->enabled_extensions.EXT_buffer_device_address;
1899
1900 device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
1901 pCreateInfo->pEnabledFeatures->robustBufferAccess;
1902
1903 mtx_init(&device->shader_slab_mutex, mtx_plain);
1904 list_inithead(&device->shader_slabs);
1905
1906 radv_bo_list_init(&device->bo_list);
1907
1908 for (unsigned i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
1909 const VkDeviceQueueCreateInfo *queue_create = &pCreateInfo->pQueueCreateInfos[i];
1910 uint32_t qfi = queue_create->queueFamilyIndex;
1911 const VkDeviceQueueGlobalPriorityCreateInfoEXT *global_priority =
1912 vk_find_struct_const(queue_create->pNext, DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT);
1913
1914 assert(!global_priority || device->physical_device->rad_info.has_ctx_priority);
1915
1916 device->queues[qfi] = vk_alloc(&device->alloc,
1917 queue_create->queueCount * sizeof(struct radv_queue), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
1918 if (!device->queues[qfi]) {
1919 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1920 goto fail;
1921 }
1922
1923 memset(device->queues[qfi], 0, queue_create->queueCount * sizeof(struct radv_queue));
1924
1925 device->queue_count[qfi] = queue_create->queueCount;
1926
1927 for (unsigned q = 0; q < queue_create->queueCount; q++) {
1928 result = radv_queue_init(device, &device->queues[qfi][q],
1929 qfi, q, queue_create->flags,
1930 global_priority);
1931 if (result != VK_SUCCESS)
1932 goto fail;
1933 }
1934 }
1935
1936 device->pbb_allowed = device->physical_device->rad_info.chip_class >= GFX9 &&
1937 !(device->instance->debug_flags & RADV_DEBUG_NOBINNING);
1938
1939 device->dfsm_allowed = device->pbb_allowed &&
1940 (device->physical_device->rad_info.family == CHIP_RAVEN ||
1941 device->physical_device->rad_info.family == CHIP_RAVEN2 ||
1942 device->physical_device->rad_info.family == CHIP_RENOIR);
1943
1944 #ifdef ANDROID
1945 device->always_use_syncobj = device->physical_device->rad_info.has_syncobj_wait_for_submit;
1946 #endif
1947
1948 /* The maximum number of scratch waves. Scratch space isn't divided
1949 * evenly between CUs. The number is only a function of the number of CUs.
1950 * We can decrease the constant to decrease the scratch buffer size.
1951 *
1952 * sctx->scratch_waves must be >= the maximum possible size of
1953 * 1 threadgroup, so that the hw doesn't hang from being unable
1954 * to start any.
1955 *
1956 * The recommended value is 4 per CU at most. Higher numbers don't
1957 * bring much benefit, but they still occupy chip resources (think
1958 * async compute). I've seen ~2% performance difference between 4 and 32.
1959 */
1960 uint32_t max_threads_per_block = 2048;
1961 device->scratch_waves = MAX2(32 * physical_device->rad_info.num_good_compute_units,
1962 max_threads_per_block / 64);
1963
1964 device->dispatch_initiator = S_00B800_COMPUTE_SHADER_EN(1) |
1965 S_00B800_CS_W32_EN(device->physical_device->cs_wave_size == 32);
1966
1967 if (device->physical_device->rad_info.chip_class >= GFX7) {
1968 /* If the KMD allows it (there is a KMD hw register for it),
1969 * allow launching waves out-of-order.
1970 */
1971 device->dispatch_initiator |= S_00B800_ORDER_MODE(1);
1972 }
1973
1974 radv_device_init_gs_info(device);
1975
1976 device->tess_offchip_block_dw_size =
1977 device->physical_device->rad_info.family == CHIP_HAWAII ? 4096 : 8192;
1978
1979 if (getenv("RADV_TRACE_FILE")) {
1980 const char *filename = getenv("RADV_TRACE_FILE");
1981
1982 keep_shader_info = true;
1983
1984 if (!radv_init_trace(device))
1985 goto fail;
1986
1987 fprintf(stderr, "*****************************************************************************\n");
1988 fprintf(stderr, "* WARNING: RADV_TRACE_FILE is costly and should only be used for debugging! *\n");
1989 fprintf(stderr, "*****************************************************************************\n");
1990
1991 fprintf(stderr, "Trace file will be dumped to %s\n", filename);
1992 radv_dump_enabled_options(device, stderr);
1993 }
1994
1995 device->keep_shader_info = keep_shader_info;
1996
1997 result = radv_device_init_meta(device);
1998 if (result != VK_SUCCESS)
1999 goto fail;
2000
2001 radv_device_init_msaa(device);
2002
2003 for (int family = 0; family < RADV_MAX_QUEUE_FAMILIES; ++family) {
2004 device->empty_cs[family] = device->ws->cs_create(device->ws, family);
2005 switch (family) {
2006 case RADV_QUEUE_GENERAL:
2007 /* Since amdgpu version 3.6.0, CONTEXT_CONTROL is emitted by the kernel */
2008 if (device->physical_device->rad_info.drm_minor < 6) {
2009 radeon_emit(device->empty_cs[family], PKT3(PKT3_CONTEXT_CONTROL, 1, 0));
2010 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_LOAD_ENABLE(1));
2011 radeon_emit(device->empty_cs[family], CONTEXT_CONTROL_SHADOW_ENABLE(1));
2012 }
2013 break;
2014 case RADV_QUEUE_COMPUTE:
2015 radeon_emit(device->empty_cs[family], PKT3(PKT3_NOP, 0, 0));
2016 radeon_emit(device->empty_cs[family], 0);
2017 break;
2018 }
2019 device->ws->cs_finalize(device->empty_cs[family]);
2020 }
2021
2022 if (device->physical_device->rad_info.chip_class >= GFX7)
2023 cik_create_gfx_config(device);
2024
2025 VkPipelineCacheCreateInfo ci;
2026 ci.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
2027 ci.pNext = NULL;
2028 ci.flags = 0;
2029 ci.pInitialData = NULL;
2030 ci.initialDataSize = 0;
2031 VkPipelineCache pc;
2032 result = radv_CreatePipelineCache(radv_device_to_handle(device),
2033 &ci, NULL, &pc);
2034 if (result != VK_SUCCESS)
2035 goto fail_meta;
2036
2037 device->mem_cache = radv_pipeline_cache_from_handle(pc);
2038
2039 device->force_aniso =
2040 MIN2(16, radv_get_int_debug_option("RADV_TEX_ANISO", -1));
2041 if (device->force_aniso >= 0) {
2042 fprintf(stderr, "radv: Forcing anisotropy filter to %ix\n",
2043 1 << util_logbase2(device->force_aniso));
2044 }
2045
2046 *pDevice = radv_device_to_handle(device);
2047 return VK_SUCCESS;
2048
2049 fail_meta:
2050 radv_device_finish_meta(device);
2051 fail:
2052 radv_bo_list_finish(&device->bo_list);
2053
2054 if (device->trace_bo)
2055 device->ws->buffer_destroy(device->trace_bo);
2056
2057 if (device->gfx_init)
2058 device->ws->buffer_destroy(device->gfx_init);
2059
2060 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2061 for (unsigned q = 0; q < device->queue_count[i]; q++)
2062 radv_queue_finish(&device->queues[i][q]);
2063 if (device->queue_count[i])
2064 vk_free(&device->alloc, device->queues[i]);
2065 }
2066
2067 vk_free(&device->alloc, device);
2068 return result;
2069 }
2070
2071 void radv_DestroyDevice(
2072 VkDevice _device,
2073 const VkAllocationCallbacks* pAllocator)
2074 {
2075 RADV_FROM_HANDLE(radv_device, device, _device);
2076
2077 if (!device)
2078 return;
2079
2080 if (device->trace_bo)
2081 device->ws->buffer_destroy(device->trace_bo);
2082
2083 if (device->gfx_init)
2084 device->ws->buffer_destroy(device->gfx_init);
2085
2086 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
2087 for (unsigned q = 0; q < device->queue_count[i]; q++)
2088 radv_queue_finish(&device->queues[i][q]);
2089 if (device->queue_count[i])
2090 vk_free(&device->alloc, device->queues[i]);
2091 if (device->empty_cs[i])
2092 device->ws->cs_destroy(device->empty_cs[i]);
2093 }
2094 radv_device_finish_meta(device);
2095
2096 VkPipelineCache pc = radv_pipeline_cache_to_handle(device->mem_cache);
2097 radv_DestroyPipelineCache(radv_device_to_handle(device), pc, NULL);
2098
2099 radv_destroy_shader_slabs(device);
2100
2101 radv_bo_list_finish(&device->bo_list);
2102 vk_free(&device->alloc, device);
2103 }
2104
2105 VkResult radv_EnumerateInstanceLayerProperties(
2106 uint32_t* pPropertyCount,
2107 VkLayerProperties* pProperties)
2108 {
2109 if (pProperties == NULL) {
2110 *pPropertyCount = 0;
2111 return VK_SUCCESS;
2112 }
2113
2114 /* None supported at this time */
2115 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
2116 }
2117
2118 VkResult radv_EnumerateDeviceLayerProperties(
2119 VkPhysicalDevice physicalDevice,
2120 uint32_t* pPropertyCount,
2121 VkLayerProperties* pProperties)
2122 {
2123 if (pProperties == NULL) {
2124 *pPropertyCount = 0;
2125 return VK_SUCCESS;
2126 }
2127
2128 /* None supported at this time */
2129 return vk_error(NULL, VK_ERROR_LAYER_NOT_PRESENT);
2130 }
2131
2132 void radv_GetDeviceQueue2(
2133 VkDevice _device,
2134 const VkDeviceQueueInfo2* pQueueInfo,
2135 VkQueue* pQueue)
2136 {
2137 RADV_FROM_HANDLE(radv_device, device, _device);
2138 struct radv_queue *queue;
2139
2140 queue = &device->queues[pQueueInfo->queueFamilyIndex][pQueueInfo->queueIndex];
2141 if (pQueueInfo->flags != queue->flags) {
2142 /* From the Vulkan 1.1.70 spec:
2143 *
2144 * "The queue returned by vkGetDeviceQueue2 must have the same
2145 * flags value from this structure as that used at device
2146 * creation time in a VkDeviceQueueCreateInfo instance. If no
2147 * matching flags were specified at device creation time then
2148 * pQueue will return VK_NULL_HANDLE."
2149 */
2150 *pQueue = VK_NULL_HANDLE;
2151 return;
2152 }
2153
2154 *pQueue = radv_queue_to_handle(queue);
2155 }
2156
2157 void radv_GetDeviceQueue(
2158 VkDevice _device,
2159 uint32_t queueFamilyIndex,
2160 uint32_t queueIndex,
2161 VkQueue* pQueue)
2162 {
2163 const VkDeviceQueueInfo2 info = (VkDeviceQueueInfo2) {
2164 .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2,
2165 .queueFamilyIndex = queueFamilyIndex,
2166 .queueIndex = queueIndex
2167 };
2168
2169 radv_GetDeviceQueue2(_device, &info, pQueue);
2170 }
2171
2172 static void
2173 fill_geom_tess_rings(struct radv_queue *queue,
2174 uint32_t *map,
2175 bool add_sample_positions,
2176 uint32_t esgs_ring_size,
2177 struct radeon_winsys_bo *esgs_ring_bo,
2178 uint32_t gsvs_ring_size,
2179 struct radeon_winsys_bo *gsvs_ring_bo,
2180 uint32_t tess_factor_ring_size,
2181 uint32_t tess_offchip_ring_offset,
2182 uint32_t tess_offchip_ring_size,
2183 struct radeon_winsys_bo *tess_rings_bo)
2184 {
2185 uint32_t *desc = &map[4];
2186
2187 if (esgs_ring_bo) {
2188 uint64_t esgs_va = radv_buffer_get_va(esgs_ring_bo);
2189
2190 /* stride 0, num records - size, add tid, swizzle, elsize4,
2191 index stride 64 */
2192 desc[0] = esgs_va;
2193 desc[1] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32) |
2194 S_008F04_SWIZZLE_ENABLE(true);
2195 desc[2] = esgs_ring_size;
2196 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2197 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2198 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2199 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2200 S_008F0C_INDEX_STRIDE(3) |
2201 S_008F0C_ADD_TID_ENABLE(1);
2202
2203 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2204 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2205 S_008F0C_OOB_SELECT(2) |
2206 S_008F0C_RESOURCE_LEVEL(1);
2207 } else {
2208 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2209 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2210 S_008F0C_ELEMENT_SIZE(1);
2211 }
2212
2213 /* GS entry for ES->GS ring */
2214 /* stride 0, num records - size, elsize0,
2215 index stride 0 */
2216 desc[4] = esgs_va;
2217 desc[5] = S_008F04_BASE_ADDRESS_HI(esgs_va >> 32);
2218 desc[6] = esgs_ring_size;
2219 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2220 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2221 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2222 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2223
2224 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2225 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2226 S_008F0C_OOB_SELECT(2) |
2227 S_008F0C_RESOURCE_LEVEL(1);
2228 } else {
2229 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2230 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2231 }
2232 }
2233
2234 desc += 8;
2235
2236 if (gsvs_ring_bo) {
2237 uint64_t gsvs_va = radv_buffer_get_va(gsvs_ring_bo);
2238
2239 /* VS entry for GS->VS ring */
2240 /* stride 0, num records - size, elsize0,
2241 index stride 0 */
2242 desc[0] = gsvs_va;
2243 desc[1] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32);
2244 desc[2] = gsvs_ring_size;
2245 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2246 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2247 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2248 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2249
2250 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2251 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2252 S_008F0C_OOB_SELECT(2) |
2253 S_008F0C_RESOURCE_LEVEL(1);
2254 } else {
2255 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2256 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2257 }
2258
2259 /* stride gsvs_itemsize, num records 64
2260 elsize 4, index stride 16 */
2261 /* shader will patch stride and desc[2] */
2262 desc[4] = gsvs_va;
2263 desc[5] = S_008F04_BASE_ADDRESS_HI(gsvs_va >> 32) |
2264 S_008F04_SWIZZLE_ENABLE(1);
2265 desc[6] = 0;
2266 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2267 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2268 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2269 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W) |
2270 S_008F0C_INDEX_STRIDE(1) |
2271 S_008F0C_ADD_TID_ENABLE(true);
2272
2273 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2274 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2275 S_008F0C_OOB_SELECT(2) |
2276 S_008F0C_RESOURCE_LEVEL(1);
2277 } else {
2278 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2279 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32) |
2280 S_008F0C_ELEMENT_SIZE(1);
2281 }
2282
2283 }
2284
2285 desc += 8;
2286
2287 if (tess_rings_bo) {
2288 uint64_t tess_va = radv_buffer_get_va(tess_rings_bo);
2289 uint64_t tess_offchip_va = tess_va + tess_offchip_ring_offset;
2290
2291 desc[0] = tess_va;
2292 desc[1] = S_008F04_BASE_ADDRESS_HI(tess_va >> 32);
2293 desc[2] = tess_factor_ring_size;
2294 desc[3] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2295 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2296 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2297 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2298
2299 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2300 desc[3] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2301 S_008F0C_OOB_SELECT(3) |
2302 S_008F0C_RESOURCE_LEVEL(1);
2303 } else {
2304 desc[3] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2305 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2306 }
2307
2308 desc[4] = tess_offchip_va;
2309 desc[5] = S_008F04_BASE_ADDRESS_HI(tess_offchip_va >> 32);
2310 desc[6] = tess_offchip_ring_size;
2311 desc[7] = S_008F0C_DST_SEL_X(V_008F0C_SQ_SEL_X) |
2312 S_008F0C_DST_SEL_Y(V_008F0C_SQ_SEL_Y) |
2313 S_008F0C_DST_SEL_Z(V_008F0C_SQ_SEL_Z) |
2314 S_008F0C_DST_SEL_W(V_008F0C_SQ_SEL_W);
2315
2316 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2317 desc[7] |= S_008F0C_FORMAT(V_008F0C_IMG_FORMAT_32_FLOAT) |
2318 S_008F0C_OOB_SELECT(3) |
2319 S_008F0C_RESOURCE_LEVEL(1);
2320 } else {
2321 desc[7] |= S_008F0C_NUM_FORMAT(V_008F0C_BUF_NUM_FORMAT_FLOAT) |
2322 S_008F0C_DATA_FORMAT(V_008F0C_BUF_DATA_FORMAT_32);
2323 }
2324 }
2325
2326 desc += 8;
2327
2328 if (add_sample_positions) {
2329 /* add sample positions after all rings */
2330 memcpy(desc, queue->device->sample_locations_1x, 8);
2331 desc += 2;
2332 memcpy(desc, queue->device->sample_locations_2x, 16);
2333 desc += 4;
2334 memcpy(desc, queue->device->sample_locations_4x, 32);
2335 desc += 8;
2336 memcpy(desc, queue->device->sample_locations_8x, 64);
2337 }
2338 }
2339
2340 static unsigned
2341 radv_get_hs_offchip_param(struct radv_device *device, uint32_t *max_offchip_buffers_p)
2342 {
2343 bool double_offchip_buffers = device->physical_device->rad_info.chip_class >= GFX7 &&
2344 device->physical_device->rad_info.family != CHIP_CARRIZO &&
2345 device->physical_device->rad_info.family != CHIP_STONEY;
2346 unsigned max_offchip_buffers_per_se = double_offchip_buffers ? 128 : 64;
2347 unsigned max_offchip_buffers;
2348 unsigned offchip_granularity;
2349 unsigned hs_offchip_param;
2350
2351 /*
2352 * Per RadeonSI:
2353 * This must be one less than the maximum number due to a hw limitation.
2354 * Various hardware bugs need thGFX7
2355 *
2356 * Per AMDVLK:
2357 * Vega10 should limit max_offchip_buffers to 508 (4 * 127).
2358 * Gfx7 should limit max_offchip_buffers to 508
2359 * Gfx6 should limit max_offchip_buffers to 126 (2 * 63)
2360 *
2361 * Follow AMDVLK here.
2362 */
2363 if (device->physical_device->rad_info.chip_class >= GFX10) {
2364 max_offchip_buffers_per_se = 256;
2365 } else if (device->physical_device->rad_info.family == CHIP_VEGA10 ||
2366 device->physical_device->rad_info.chip_class == GFX7 ||
2367 device->physical_device->rad_info.chip_class == GFX6)
2368 --max_offchip_buffers_per_se;
2369
2370 max_offchip_buffers = max_offchip_buffers_per_se *
2371 device->physical_device->rad_info.max_se;
2372
2373 /* Hawaii has a bug with offchip buffers > 256 that can be worked
2374 * around by setting 4K granularity.
2375 */
2376 if (device->tess_offchip_block_dw_size == 4096) {
2377 assert(device->physical_device->rad_info.family == CHIP_HAWAII);
2378 offchip_granularity = V_03093C_X_4K_DWORDS;
2379 } else {
2380 assert(device->tess_offchip_block_dw_size == 8192);
2381 offchip_granularity = V_03093C_X_8K_DWORDS;
2382 }
2383
2384 switch (device->physical_device->rad_info.chip_class) {
2385 case GFX6:
2386 max_offchip_buffers = MIN2(max_offchip_buffers, 126);
2387 break;
2388 case GFX7:
2389 case GFX8:
2390 case GFX9:
2391 max_offchip_buffers = MIN2(max_offchip_buffers, 508);
2392 break;
2393 case GFX10:
2394 break;
2395 default:
2396 break;
2397 }
2398
2399 *max_offchip_buffers_p = max_offchip_buffers;
2400 if (device->physical_device->rad_info.chip_class >= GFX7) {
2401 if (device->physical_device->rad_info.chip_class >= GFX8)
2402 --max_offchip_buffers;
2403 hs_offchip_param =
2404 S_03093C_OFFCHIP_BUFFERING(max_offchip_buffers) |
2405 S_03093C_OFFCHIP_GRANULARITY(offchip_granularity);
2406 } else {
2407 hs_offchip_param =
2408 S_0089B0_OFFCHIP_BUFFERING(max_offchip_buffers);
2409 }
2410 return hs_offchip_param;
2411 }
2412
2413 static void
2414 radv_emit_gs_ring_sizes(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2415 struct radeon_winsys_bo *esgs_ring_bo,
2416 uint32_t esgs_ring_size,
2417 struct radeon_winsys_bo *gsvs_ring_bo,
2418 uint32_t gsvs_ring_size)
2419 {
2420 if (!esgs_ring_bo && !gsvs_ring_bo)
2421 return;
2422
2423 if (esgs_ring_bo)
2424 radv_cs_add_buffer(queue->device->ws, cs, esgs_ring_bo);
2425
2426 if (gsvs_ring_bo)
2427 radv_cs_add_buffer(queue->device->ws, cs, gsvs_ring_bo);
2428
2429 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
2430 radeon_set_uconfig_reg_seq(cs, R_030900_VGT_ESGS_RING_SIZE, 2);
2431 radeon_emit(cs, esgs_ring_size >> 8);
2432 radeon_emit(cs, gsvs_ring_size >> 8);
2433 } else {
2434 radeon_set_config_reg_seq(cs, R_0088C8_VGT_ESGS_RING_SIZE, 2);
2435 radeon_emit(cs, esgs_ring_size >> 8);
2436 radeon_emit(cs, gsvs_ring_size >> 8);
2437 }
2438 }
2439
2440 static void
2441 radv_emit_tess_factor_ring(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2442 unsigned hs_offchip_param, unsigned tf_ring_size,
2443 struct radeon_winsys_bo *tess_rings_bo)
2444 {
2445 uint64_t tf_va;
2446
2447 if (!tess_rings_bo)
2448 return;
2449
2450 tf_va = radv_buffer_get_va(tess_rings_bo);
2451
2452 radv_cs_add_buffer(queue->device->ws, cs, tess_rings_bo);
2453
2454 if (queue->device->physical_device->rad_info.chip_class >= GFX7) {
2455 radeon_set_uconfig_reg(cs, R_030938_VGT_TF_RING_SIZE,
2456 S_030938_SIZE(tf_ring_size / 4));
2457 radeon_set_uconfig_reg(cs, R_030940_VGT_TF_MEMORY_BASE,
2458 tf_va >> 8);
2459
2460 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2461 radeon_set_uconfig_reg(cs, R_030984_VGT_TF_MEMORY_BASE_HI_UMD,
2462 S_030984_BASE_HI(tf_va >> 40));
2463 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
2464 radeon_set_uconfig_reg(cs, R_030944_VGT_TF_MEMORY_BASE_HI,
2465 S_030944_BASE_HI(tf_va >> 40));
2466 }
2467 radeon_set_uconfig_reg(cs, R_03093C_VGT_HS_OFFCHIP_PARAM,
2468 hs_offchip_param);
2469 } else {
2470 radeon_set_config_reg(cs, R_008988_VGT_TF_RING_SIZE,
2471 S_008988_SIZE(tf_ring_size / 4));
2472 radeon_set_config_reg(cs, R_0089B8_VGT_TF_MEMORY_BASE,
2473 tf_va >> 8);
2474 radeon_set_config_reg(cs, R_0089B0_VGT_HS_OFFCHIP_PARAM,
2475 hs_offchip_param);
2476 }
2477 }
2478
2479 static void
2480 radv_emit_compute_scratch(struct radv_queue *queue, struct radeon_cmdbuf *cs,
2481 struct radeon_winsys_bo *compute_scratch_bo)
2482 {
2483 uint64_t scratch_va;
2484
2485 if (!compute_scratch_bo)
2486 return;
2487
2488 scratch_va = radv_buffer_get_va(compute_scratch_bo);
2489
2490 radv_cs_add_buffer(queue->device->ws, cs, compute_scratch_bo);
2491
2492 radeon_set_sh_reg_seq(cs, R_00B900_COMPUTE_USER_DATA_0, 2);
2493 radeon_emit(cs, scratch_va);
2494 radeon_emit(cs, S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
2495 S_008F04_SWIZZLE_ENABLE(1));
2496 }
2497
2498 static void
2499 radv_emit_global_shader_pointers(struct radv_queue *queue,
2500 struct radeon_cmdbuf *cs,
2501 struct radeon_winsys_bo *descriptor_bo)
2502 {
2503 uint64_t va;
2504
2505 if (!descriptor_bo)
2506 return;
2507
2508 va = radv_buffer_get_va(descriptor_bo);
2509
2510 radv_cs_add_buffer(queue->device->ws, cs, descriptor_bo);
2511
2512 if (queue->device->physical_device->rad_info.chip_class >= GFX10) {
2513 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2514 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2515 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
2516 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
2517
2518 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2519 radv_emit_shader_pointer(queue->device, cs, regs[i],
2520 va, true);
2521 }
2522 } else if (queue->device->physical_device->rad_info.chip_class == GFX9) {
2523 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2524 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2525 R_00B208_SPI_SHADER_USER_DATA_ADDR_LO_GS,
2526 R_00B408_SPI_SHADER_USER_DATA_ADDR_LO_HS};
2527
2528 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2529 radv_emit_shader_pointer(queue->device, cs, regs[i],
2530 va, true);
2531 }
2532 } else {
2533 uint32_t regs[] = {R_00B030_SPI_SHADER_USER_DATA_PS_0,
2534 R_00B130_SPI_SHADER_USER_DATA_VS_0,
2535 R_00B230_SPI_SHADER_USER_DATA_GS_0,
2536 R_00B330_SPI_SHADER_USER_DATA_ES_0,
2537 R_00B430_SPI_SHADER_USER_DATA_HS_0,
2538 R_00B530_SPI_SHADER_USER_DATA_LS_0};
2539
2540 for (int i = 0; i < ARRAY_SIZE(regs); ++i) {
2541 radv_emit_shader_pointer(queue->device, cs, regs[i],
2542 va, true);
2543 }
2544 }
2545 }
2546
2547 static void
2548 radv_init_graphics_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
2549 {
2550 struct radv_device *device = queue->device;
2551
2552 if (device->gfx_init) {
2553 uint64_t va = radv_buffer_get_va(device->gfx_init);
2554
2555 radeon_emit(cs, PKT3(PKT3_INDIRECT_BUFFER_CIK, 2, 0));
2556 radeon_emit(cs, va);
2557 radeon_emit(cs, va >> 32);
2558 radeon_emit(cs, device->gfx_init_size_dw & 0xffff);
2559
2560 radv_cs_add_buffer(device->ws, cs, device->gfx_init);
2561 } else {
2562 struct radv_physical_device *physical_device = device->physical_device;
2563 si_emit_graphics(physical_device, cs);
2564 }
2565 }
2566
2567 static void
2568 radv_init_compute_state(struct radeon_cmdbuf *cs, struct radv_queue *queue)
2569 {
2570 struct radv_physical_device *physical_device = queue->device->physical_device;
2571 si_emit_compute(physical_device, cs);
2572 }
2573
2574 static VkResult
2575 radv_get_preamble_cs(struct radv_queue *queue,
2576 uint32_t scratch_size,
2577 uint32_t compute_scratch_size,
2578 uint32_t esgs_ring_size,
2579 uint32_t gsvs_ring_size,
2580 bool needs_tess_rings,
2581 bool needs_sample_positions,
2582 struct radeon_cmdbuf **initial_full_flush_preamble_cs,
2583 struct radeon_cmdbuf **initial_preamble_cs,
2584 struct radeon_cmdbuf **continue_preamble_cs)
2585 {
2586 struct radeon_winsys_bo *scratch_bo = NULL;
2587 struct radeon_winsys_bo *descriptor_bo = NULL;
2588 struct radeon_winsys_bo *compute_scratch_bo = NULL;
2589 struct radeon_winsys_bo *esgs_ring_bo = NULL;
2590 struct radeon_winsys_bo *gsvs_ring_bo = NULL;
2591 struct radeon_winsys_bo *tess_rings_bo = NULL;
2592 struct radeon_cmdbuf *dest_cs[3] = {0};
2593 bool add_tess_rings = false, add_sample_positions = false;
2594 unsigned tess_factor_ring_size = 0, tess_offchip_ring_size = 0;
2595 unsigned max_offchip_buffers;
2596 unsigned hs_offchip_param = 0;
2597 unsigned tess_offchip_ring_offset;
2598 uint32_t ring_bo_flags = RADEON_FLAG_NO_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING;
2599 if (!queue->has_tess_rings) {
2600 if (needs_tess_rings)
2601 add_tess_rings = true;
2602 }
2603 if (!queue->has_sample_positions) {
2604 if (needs_sample_positions)
2605 add_sample_positions = true;
2606 }
2607 tess_factor_ring_size = 32768 * queue->device->physical_device->rad_info.max_se;
2608 hs_offchip_param = radv_get_hs_offchip_param(queue->device,
2609 &max_offchip_buffers);
2610 tess_offchip_ring_offset = align(tess_factor_ring_size, 64 * 1024);
2611 tess_offchip_ring_size = max_offchip_buffers *
2612 queue->device->tess_offchip_block_dw_size * 4;
2613
2614 if (scratch_size <= queue->scratch_size &&
2615 compute_scratch_size <= queue->compute_scratch_size &&
2616 esgs_ring_size <= queue->esgs_ring_size &&
2617 gsvs_ring_size <= queue->gsvs_ring_size &&
2618 !add_tess_rings && !add_sample_positions &&
2619 queue->initial_preamble_cs) {
2620 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
2621 *initial_preamble_cs = queue->initial_preamble_cs;
2622 *continue_preamble_cs = queue->continue_preamble_cs;
2623 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
2624 *continue_preamble_cs = NULL;
2625 return VK_SUCCESS;
2626 }
2627
2628 if (scratch_size > queue->scratch_size) {
2629 scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
2630 scratch_size,
2631 4096,
2632 RADEON_DOMAIN_VRAM,
2633 ring_bo_flags,
2634 RADV_BO_PRIORITY_SCRATCH);
2635 if (!scratch_bo)
2636 goto fail;
2637 } else
2638 scratch_bo = queue->scratch_bo;
2639
2640 if (compute_scratch_size > queue->compute_scratch_size) {
2641 compute_scratch_bo = queue->device->ws->buffer_create(queue->device->ws,
2642 compute_scratch_size,
2643 4096,
2644 RADEON_DOMAIN_VRAM,
2645 ring_bo_flags,
2646 RADV_BO_PRIORITY_SCRATCH);
2647 if (!compute_scratch_bo)
2648 goto fail;
2649
2650 } else
2651 compute_scratch_bo = queue->compute_scratch_bo;
2652
2653 if (esgs_ring_size > queue->esgs_ring_size) {
2654 esgs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
2655 esgs_ring_size,
2656 4096,
2657 RADEON_DOMAIN_VRAM,
2658 ring_bo_flags,
2659 RADV_BO_PRIORITY_SCRATCH);
2660 if (!esgs_ring_bo)
2661 goto fail;
2662 } else {
2663 esgs_ring_bo = queue->esgs_ring_bo;
2664 esgs_ring_size = queue->esgs_ring_size;
2665 }
2666
2667 if (gsvs_ring_size > queue->gsvs_ring_size) {
2668 gsvs_ring_bo = queue->device->ws->buffer_create(queue->device->ws,
2669 gsvs_ring_size,
2670 4096,
2671 RADEON_DOMAIN_VRAM,
2672 ring_bo_flags,
2673 RADV_BO_PRIORITY_SCRATCH);
2674 if (!gsvs_ring_bo)
2675 goto fail;
2676 } else {
2677 gsvs_ring_bo = queue->gsvs_ring_bo;
2678 gsvs_ring_size = queue->gsvs_ring_size;
2679 }
2680
2681 if (add_tess_rings) {
2682 tess_rings_bo = queue->device->ws->buffer_create(queue->device->ws,
2683 tess_offchip_ring_offset + tess_offchip_ring_size,
2684 256,
2685 RADEON_DOMAIN_VRAM,
2686 ring_bo_flags,
2687 RADV_BO_PRIORITY_SCRATCH);
2688 if (!tess_rings_bo)
2689 goto fail;
2690 } else {
2691 tess_rings_bo = queue->tess_rings_bo;
2692 }
2693
2694 if (scratch_bo != queue->scratch_bo ||
2695 esgs_ring_bo != queue->esgs_ring_bo ||
2696 gsvs_ring_bo != queue->gsvs_ring_bo ||
2697 tess_rings_bo != queue->tess_rings_bo ||
2698 add_sample_positions) {
2699 uint32_t size = 0;
2700 if (gsvs_ring_bo || esgs_ring_bo ||
2701 tess_rings_bo || add_sample_positions) {
2702 size = 112; /* 2 dword + 2 padding + 4 dword * 6 */
2703 if (add_sample_positions)
2704 size += 128; /* 64+32+16+8 = 120 bytes */
2705 }
2706 else if (scratch_bo)
2707 size = 8; /* 2 dword */
2708
2709 descriptor_bo = queue->device->ws->buffer_create(queue->device->ws,
2710 size,
2711 4096,
2712 RADEON_DOMAIN_VRAM,
2713 RADEON_FLAG_CPU_ACCESS |
2714 RADEON_FLAG_NO_INTERPROCESS_SHARING |
2715 RADEON_FLAG_READ_ONLY,
2716 RADV_BO_PRIORITY_DESCRIPTOR);
2717 if (!descriptor_bo)
2718 goto fail;
2719 } else
2720 descriptor_bo = queue->descriptor_bo;
2721
2722 if (descriptor_bo != queue->descriptor_bo) {
2723 uint32_t *map = (uint32_t*)queue->device->ws->buffer_map(descriptor_bo);
2724
2725 if (scratch_bo) {
2726 uint64_t scratch_va = radv_buffer_get_va(scratch_bo);
2727 uint32_t rsrc1 = S_008F04_BASE_ADDRESS_HI(scratch_va >> 32) |
2728 S_008F04_SWIZZLE_ENABLE(1);
2729 map[0] = scratch_va;
2730 map[1] = rsrc1;
2731 }
2732
2733 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo || add_sample_positions)
2734 fill_geom_tess_rings(queue, map, add_sample_positions,
2735 esgs_ring_size, esgs_ring_bo,
2736 gsvs_ring_size, gsvs_ring_bo,
2737 tess_factor_ring_size,
2738 tess_offchip_ring_offset,
2739 tess_offchip_ring_size,
2740 tess_rings_bo);
2741
2742 queue->device->ws->buffer_unmap(descriptor_bo);
2743 }
2744
2745 for(int i = 0; i < 3; ++i) {
2746 struct radeon_cmdbuf *cs = NULL;
2747 cs = queue->device->ws->cs_create(queue->device->ws,
2748 queue->queue_family_index ? RING_COMPUTE : RING_GFX);
2749 if (!cs)
2750 goto fail;
2751
2752 dest_cs[i] = cs;
2753
2754 if (scratch_bo)
2755 radv_cs_add_buffer(queue->device->ws, cs, scratch_bo);
2756
2757 /* Emit initial configuration. */
2758 switch (queue->queue_family_index) {
2759 case RADV_QUEUE_GENERAL:
2760 radv_init_graphics_state(cs, queue);
2761 break;
2762 case RADV_QUEUE_COMPUTE:
2763 radv_init_compute_state(cs, queue);
2764 break;
2765 case RADV_QUEUE_TRANSFER:
2766 break;
2767 }
2768
2769 if (esgs_ring_bo || gsvs_ring_bo || tess_rings_bo) {
2770 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
2771 radeon_emit(cs, EVENT_TYPE(V_028A90_VS_PARTIAL_FLUSH) | EVENT_INDEX(4));
2772
2773 radeon_emit(cs, PKT3(PKT3_EVENT_WRITE, 0, 0));
2774 radeon_emit(cs, EVENT_TYPE(V_028A90_VGT_FLUSH) | EVENT_INDEX(0));
2775 }
2776
2777 radv_emit_gs_ring_sizes(queue, cs, esgs_ring_bo, esgs_ring_size,
2778 gsvs_ring_bo, gsvs_ring_size);
2779 radv_emit_tess_factor_ring(queue, cs, hs_offchip_param,
2780 tess_factor_ring_size, tess_rings_bo);
2781 radv_emit_global_shader_pointers(queue, cs, descriptor_bo);
2782 radv_emit_compute_scratch(queue, cs, compute_scratch_bo);
2783
2784 if (i == 0) {
2785 si_cs_emit_cache_flush(cs,
2786 queue->device->physical_device->rad_info.chip_class,
2787 NULL, 0,
2788 queue->queue_family_index == RING_COMPUTE &&
2789 queue->device->physical_device->rad_info.chip_class >= GFX7,
2790 (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)) |
2791 RADV_CMD_FLAG_INV_ICACHE |
2792 RADV_CMD_FLAG_INV_SCACHE |
2793 RADV_CMD_FLAG_INV_VCACHE |
2794 RADV_CMD_FLAG_INV_L2 |
2795 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
2796 } else if (i == 1) {
2797 si_cs_emit_cache_flush(cs,
2798 queue->device->physical_device->rad_info.chip_class,
2799 NULL, 0,
2800 queue->queue_family_index == RING_COMPUTE &&
2801 queue->device->physical_device->rad_info.chip_class >= GFX7,
2802 RADV_CMD_FLAG_INV_ICACHE |
2803 RADV_CMD_FLAG_INV_SCACHE |
2804 RADV_CMD_FLAG_INV_VCACHE |
2805 RADV_CMD_FLAG_INV_L2 |
2806 RADV_CMD_FLAG_START_PIPELINE_STATS, 0);
2807 }
2808
2809 if (!queue->device->ws->cs_finalize(cs))
2810 goto fail;
2811 }
2812
2813 if (queue->initial_full_flush_preamble_cs)
2814 queue->device->ws->cs_destroy(queue->initial_full_flush_preamble_cs);
2815
2816 if (queue->initial_preamble_cs)
2817 queue->device->ws->cs_destroy(queue->initial_preamble_cs);
2818
2819 if (queue->continue_preamble_cs)
2820 queue->device->ws->cs_destroy(queue->continue_preamble_cs);
2821
2822 queue->initial_full_flush_preamble_cs = dest_cs[0];
2823 queue->initial_preamble_cs = dest_cs[1];
2824 queue->continue_preamble_cs = dest_cs[2];
2825
2826 if (scratch_bo != queue->scratch_bo) {
2827 if (queue->scratch_bo)
2828 queue->device->ws->buffer_destroy(queue->scratch_bo);
2829 queue->scratch_bo = scratch_bo;
2830 queue->scratch_size = scratch_size;
2831 }
2832
2833 if (compute_scratch_bo != queue->compute_scratch_bo) {
2834 if (queue->compute_scratch_bo)
2835 queue->device->ws->buffer_destroy(queue->compute_scratch_bo);
2836 queue->compute_scratch_bo = compute_scratch_bo;
2837 queue->compute_scratch_size = compute_scratch_size;
2838 }
2839
2840 if (esgs_ring_bo != queue->esgs_ring_bo) {
2841 if (queue->esgs_ring_bo)
2842 queue->device->ws->buffer_destroy(queue->esgs_ring_bo);
2843 queue->esgs_ring_bo = esgs_ring_bo;
2844 queue->esgs_ring_size = esgs_ring_size;
2845 }
2846
2847 if (gsvs_ring_bo != queue->gsvs_ring_bo) {
2848 if (queue->gsvs_ring_bo)
2849 queue->device->ws->buffer_destroy(queue->gsvs_ring_bo);
2850 queue->gsvs_ring_bo = gsvs_ring_bo;
2851 queue->gsvs_ring_size = gsvs_ring_size;
2852 }
2853
2854 if (tess_rings_bo != queue->tess_rings_bo) {
2855 queue->tess_rings_bo = tess_rings_bo;
2856 queue->has_tess_rings = true;
2857 }
2858
2859 if (descriptor_bo != queue->descriptor_bo) {
2860 if (queue->descriptor_bo)
2861 queue->device->ws->buffer_destroy(queue->descriptor_bo);
2862
2863 queue->descriptor_bo = descriptor_bo;
2864 }
2865
2866 if (add_sample_positions)
2867 queue->has_sample_positions = true;
2868
2869 *initial_full_flush_preamble_cs = queue->initial_full_flush_preamble_cs;
2870 *initial_preamble_cs = queue->initial_preamble_cs;
2871 *continue_preamble_cs = queue->continue_preamble_cs;
2872 if (!scratch_size && !compute_scratch_size && !esgs_ring_size && !gsvs_ring_size)
2873 *continue_preamble_cs = NULL;
2874 return VK_SUCCESS;
2875 fail:
2876 for (int i = 0; i < ARRAY_SIZE(dest_cs); ++i)
2877 if (dest_cs[i])
2878 queue->device->ws->cs_destroy(dest_cs[i]);
2879 if (descriptor_bo && descriptor_bo != queue->descriptor_bo)
2880 queue->device->ws->buffer_destroy(descriptor_bo);
2881 if (scratch_bo && scratch_bo != queue->scratch_bo)
2882 queue->device->ws->buffer_destroy(scratch_bo);
2883 if (compute_scratch_bo && compute_scratch_bo != queue->compute_scratch_bo)
2884 queue->device->ws->buffer_destroy(compute_scratch_bo);
2885 if (esgs_ring_bo && esgs_ring_bo != queue->esgs_ring_bo)
2886 queue->device->ws->buffer_destroy(esgs_ring_bo);
2887 if (gsvs_ring_bo && gsvs_ring_bo != queue->gsvs_ring_bo)
2888 queue->device->ws->buffer_destroy(gsvs_ring_bo);
2889 if (tess_rings_bo && tess_rings_bo != queue->tess_rings_bo)
2890 queue->device->ws->buffer_destroy(tess_rings_bo);
2891 return vk_error(queue->device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
2892 }
2893
2894 static VkResult radv_alloc_sem_counts(struct radv_instance *instance,
2895 struct radv_winsys_sem_counts *counts,
2896 int num_sems,
2897 const VkSemaphore *sems,
2898 VkFence _fence,
2899 bool reset_temp)
2900 {
2901 int syncobj_idx = 0, sem_idx = 0;
2902
2903 if (num_sems == 0 && _fence == VK_NULL_HANDLE)
2904 return VK_SUCCESS;
2905
2906 for (uint32_t i = 0; i < num_sems; i++) {
2907 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
2908
2909 if (sem->temp_syncobj || sem->syncobj)
2910 counts->syncobj_count++;
2911 else
2912 counts->sem_count++;
2913 }
2914
2915 if (_fence != VK_NULL_HANDLE) {
2916 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2917 if (fence->temp_syncobj || fence->syncobj)
2918 counts->syncobj_count++;
2919 }
2920
2921 if (counts->syncobj_count) {
2922 counts->syncobj = (uint32_t *)malloc(sizeof(uint32_t) * counts->syncobj_count);
2923 if (!counts->syncobj)
2924 return vk_error(instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2925 }
2926
2927 if (counts->sem_count) {
2928 counts->sem = (struct radeon_winsys_sem **)malloc(sizeof(struct radeon_winsys_sem *) * counts->sem_count);
2929 if (!counts->sem) {
2930 free(counts->syncobj);
2931 return vk_error(instance, VK_ERROR_OUT_OF_HOST_MEMORY);
2932 }
2933 }
2934
2935 for (uint32_t i = 0; i < num_sems; i++) {
2936 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
2937
2938 if (sem->temp_syncobj) {
2939 counts->syncobj[syncobj_idx++] = sem->temp_syncobj;
2940 }
2941 else if (sem->syncobj)
2942 counts->syncobj[syncobj_idx++] = sem->syncobj;
2943 else {
2944 assert(sem->sem);
2945 counts->sem[sem_idx++] = sem->sem;
2946 }
2947 }
2948
2949 if (_fence != VK_NULL_HANDLE) {
2950 RADV_FROM_HANDLE(radv_fence, fence, _fence);
2951 if (fence->temp_syncobj)
2952 counts->syncobj[syncobj_idx++] = fence->temp_syncobj;
2953 else if (fence->syncobj)
2954 counts->syncobj[syncobj_idx++] = fence->syncobj;
2955 }
2956
2957 return VK_SUCCESS;
2958 }
2959
2960 static void
2961 radv_free_sem_info(struct radv_winsys_sem_info *sem_info)
2962 {
2963 free(sem_info->wait.syncobj);
2964 free(sem_info->wait.sem);
2965 free(sem_info->signal.syncobj);
2966 free(sem_info->signal.sem);
2967 }
2968
2969
2970 static void radv_free_temp_syncobjs(struct radv_device *device,
2971 int num_sems,
2972 const VkSemaphore *sems)
2973 {
2974 for (uint32_t i = 0; i < num_sems; i++) {
2975 RADV_FROM_HANDLE(radv_semaphore, sem, sems[i]);
2976
2977 if (sem->temp_syncobj) {
2978 device->ws->destroy_syncobj(device->ws, sem->temp_syncobj);
2979 sem->temp_syncobj = 0;
2980 }
2981 }
2982 }
2983
2984 static VkResult
2985 radv_alloc_sem_info(struct radv_instance *instance,
2986 struct radv_winsys_sem_info *sem_info,
2987 int num_wait_sems,
2988 const VkSemaphore *wait_sems,
2989 int num_signal_sems,
2990 const VkSemaphore *signal_sems,
2991 VkFence fence)
2992 {
2993 VkResult ret;
2994 memset(sem_info, 0, sizeof(*sem_info));
2995
2996 ret = radv_alloc_sem_counts(instance, &sem_info->wait, num_wait_sems, wait_sems, VK_NULL_HANDLE, true);
2997 if (ret)
2998 return ret;
2999 ret = radv_alloc_sem_counts(instance, &sem_info->signal, num_signal_sems, signal_sems, fence, false);
3000 if (ret)
3001 radv_free_sem_info(sem_info);
3002
3003 /* caller can override these */
3004 sem_info->cs_emit_wait = true;
3005 sem_info->cs_emit_signal = true;
3006 return ret;
3007 }
3008
3009 /* Signals fence as soon as all the work currently put on queue is done. */
3010 static VkResult radv_signal_fence(struct radv_queue *queue,
3011 struct radv_fence *fence)
3012 {
3013 int ret;
3014 VkResult result;
3015 struct radv_winsys_sem_info sem_info;
3016
3017 result = radv_alloc_sem_info(queue->device->instance, &sem_info, 0, NULL, 0, NULL,
3018 radv_fence_to_handle(fence));
3019 if (result != VK_SUCCESS)
3020 return result;
3021
3022 ret = queue->device->ws->cs_submit(queue->hw_ctx, queue->queue_idx,
3023 &queue->device->empty_cs[queue->queue_family_index],
3024 1, NULL, NULL, &sem_info, NULL,
3025 false, fence->fence);
3026 radv_free_sem_info(&sem_info);
3027
3028 if (ret)
3029 return vk_error(queue->device->instance, VK_ERROR_DEVICE_LOST);
3030
3031 return VK_SUCCESS;
3032 }
3033
3034 VkResult radv_QueueSubmit(
3035 VkQueue _queue,
3036 uint32_t submitCount,
3037 const VkSubmitInfo* pSubmits,
3038 VkFence _fence)
3039 {
3040 RADV_FROM_HANDLE(radv_queue, queue, _queue);
3041 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3042 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
3043 struct radeon_winsys_ctx *ctx = queue->hw_ctx;
3044 int ret;
3045 uint32_t max_cs_submission = queue->device->trace_bo ? 1 : RADV_MAX_IBS_PER_SUBMIT;
3046 uint32_t scratch_size = 0;
3047 uint32_t compute_scratch_size = 0;
3048 uint32_t esgs_ring_size = 0, gsvs_ring_size = 0;
3049 struct radeon_cmdbuf *initial_preamble_cs = NULL, *initial_flush_preamble_cs = NULL, *continue_preamble_cs = NULL;
3050 VkResult result;
3051 bool fence_emitted = false;
3052 bool tess_rings_needed = false;
3053 bool sample_positions_needed = false;
3054
3055 /* Do this first so failing to allocate scratch buffers can't result in
3056 * partially executed submissions. */
3057 for (uint32_t i = 0; i < submitCount; i++) {
3058 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
3059 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
3060 pSubmits[i].pCommandBuffers[j]);
3061
3062 scratch_size = MAX2(scratch_size, cmd_buffer->scratch_size_needed);
3063 compute_scratch_size = MAX2(compute_scratch_size,
3064 cmd_buffer->compute_scratch_size_needed);
3065 esgs_ring_size = MAX2(esgs_ring_size, cmd_buffer->esgs_ring_size_needed);
3066 gsvs_ring_size = MAX2(gsvs_ring_size, cmd_buffer->gsvs_ring_size_needed);
3067 tess_rings_needed |= cmd_buffer->tess_rings_needed;
3068 sample_positions_needed |= cmd_buffer->sample_positions_needed;
3069 }
3070 }
3071
3072 result = radv_get_preamble_cs(queue, scratch_size, compute_scratch_size,
3073 esgs_ring_size, gsvs_ring_size, tess_rings_needed,
3074 sample_positions_needed, &initial_flush_preamble_cs,
3075 &initial_preamble_cs, &continue_preamble_cs);
3076 if (result != VK_SUCCESS)
3077 return result;
3078
3079 for (uint32_t i = 0; i < submitCount; i++) {
3080 struct radeon_cmdbuf **cs_array;
3081 bool do_flush = !i || pSubmits[i].pWaitDstStageMask;
3082 bool can_patch = true;
3083 uint32_t advance;
3084 struct radv_winsys_sem_info sem_info;
3085
3086 result = radv_alloc_sem_info(queue->device->instance,
3087 &sem_info,
3088 pSubmits[i].waitSemaphoreCount,
3089 pSubmits[i].pWaitSemaphores,
3090 pSubmits[i].signalSemaphoreCount,
3091 pSubmits[i].pSignalSemaphores,
3092 _fence);
3093 if (result != VK_SUCCESS)
3094 return result;
3095
3096 if (!pSubmits[i].commandBufferCount) {
3097 if (pSubmits[i].waitSemaphoreCount || pSubmits[i].signalSemaphoreCount) {
3098 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx,
3099 &queue->device->empty_cs[queue->queue_family_index],
3100 1, NULL, NULL,
3101 &sem_info, NULL,
3102 false, base_fence);
3103 if (ret) {
3104 radv_loge("failed to submit CS %d\n", i);
3105 abort();
3106 }
3107 fence_emitted = true;
3108 }
3109 radv_free_sem_info(&sem_info);
3110 continue;
3111 }
3112
3113 cs_array = malloc(sizeof(struct radeon_cmdbuf *) *
3114 (pSubmits[i].commandBufferCount));
3115
3116 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j++) {
3117 RADV_FROM_HANDLE(radv_cmd_buffer, cmd_buffer,
3118 pSubmits[i].pCommandBuffers[j]);
3119 assert(cmd_buffer->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY);
3120
3121 cs_array[j] = cmd_buffer->cs;
3122 if ((cmd_buffer->usage_flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT))
3123 can_patch = false;
3124
3125 cmd_buffer->status = RADV_CMD_BUFFER_STATUS_PENDING;
3126 }
3127
3128 for (uint32_t j = 0; j < pSubmits[i].commandBufferCount; j += advance) {
3129 struct radeon_cmdbuf *initial_preamble = (do_flush && !j) ? initial_flush_preamble_cs : initial_preamble_cs;
3130 const struct radv_winsys_bo_list *bo_list = NULL;
3131
3132 advance = MIN2(max_cs_submission,
3133 pSubmits[i].commandBufferCount - j);
3134
3135 if (queue->device->trace_bo)
3136 *queue->device->trace_id_ptr = 0;
3137
3138 sem_info.cs_emit_wait = j == 0;
3139 sem_info.cs_emit_signal = j + advance == pSubmits[i].commandBufferCount;
3140
3141 if (unlikely(queue->device->use_global_bo_list)) {
3142 pthread_mutex_lock(&queue->device->bo_list.mutex);
3143 bo_list = &queue->device->bo_list.list;
3144 }
3145
3146 ret = queue->device->ws->cs_submit(ctx, queue->queue_idx, cs_array + j,
3147 advance, initial_preamble, continue_preamble_cs,
3148 &sem_info, bo_list,
3149 can_patch, base_fence);
3150
3151 if (unlikely(queue->device->use_global_bo_list))
3152 pthread_mutex_unlock(&queue->device->bo_list.mutex);
3153
3154 if (ret) {
3155 radv_loge("failed to submit CS %d\n", i);
3156 abort();
3157 }
3158 fence_emitted = true;
3159 if (queue->device->trace_bo) {
3160 radv_check_gpu_hangs(queue, cs_array[j]);
3161 }
3162 }
3163
3164 radv_free_temp_syncobjs(queue->device,
3165 pSubmits[i].waitSemaphoreCount,
3166 pSubmits[i].pWaitSemaphores);
3167 radv_free_sem_info(&sem_info);
3168 free(cs_array);
3169 }
3170
3171 if (fence) {
3172 if (!fence_emitted) {
3173 result = radv_signal_fence(queue, fence);
3174 if (result != VK_SUCCESS)
3175 return result;
3176 }
3177 }
3178
3179 return VK_SUCCESS;
3180 }
3181
3182 VkResult radv_QueueWaitIdle(
3183 VkQueue _queue)
3184 {
3185 RADV_FROM_HANDLE(radv_queue, queue, _queue);
3186
3187 queue->device->ws->ctx_wait_idle(queue->hw_ctx,
3188 radv_queue_family_to_ring(queue->queue_family_index),
3189 queue->queue_idx);
3190 return VK_SUCCESS;
3191 }
3192
3193 VkResult radv_DeviceWaitIdle(
3194 VkDevice _device)
3195 {
3196 RADV_FROM_HANDLE(radv_device, device, _device);
3197
3198 for (unsigned i = 0; i < RADV_MAX_QUEUE_FAMILIES; i++) {
3199 for (unsigned q = 0; q < device->queue_count[i]; q++) {
3200 radv_QueueWaitIdle(radv_queue_to_handle(&device->queues[i][q]));
3201 }
3202 }
3203 return VK_SUCCESS;
3204 }
3205
3206 VkResult radv_EnumerateInstanceExtensionProperties(
3207 const char* pLayerName,
3208 uint32_t* pPropertyCount,
3209 VkExtensionProperties* pProperties)
3210 {
3211 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
3212
3213 for (int i = 0; i < RADV_INSTANCE_EXTENSION_COUNT; i++) {
3214 if (radv_supported_instance_extensions.extensions[i]) {
3215 vk_outarray_append(&out, prop) {
3216 *prop = radv_instance_extensions[i];
3217 }
3218 }
3219 }
3220
3221 return vk_outarray_status(&out);
3222 }
3223
3224 VkResult radv_EnumerateDeviceExtensionProperties(
3225 VkPhysicalDevice physicalDevice,
3226 const char* pLayerName,
3227 uint32_t* pPropertyCount,
3228 VkExtensionProperties* pProperties)
3229 {
3230 RADV_FROM_HANDLE(radv_physical_device, device, physicalDevice);
3231 VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);
3232
3233 for (int i = 0; i < RADV_DEVICE_EXTENSION_COUNT; i++) {
3234 if (device->supported_extensions.extensions[i]) {
3235 vk_outarray_append(&out, prop) {
3236 *prop = radv_device_extensions[i];
3237 }
3238 }
3239 }
3240
3241 return vk_outarray_status(&out);
3242 }
3243
3244 PFN_vkVoidFunction radv_GetInstanceProcAddr(
3245 VkInstance _instance,
3246 const char* pName)
3247 {
3248 RADV_FROM_HANDLE(radv_instance, instance, _instance);
3249 bool unchecked = instance ? instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS : false;
3250
3251 if (unchecked) {
3252 return radv_lookup_entrypoint_unchecked(pName);
3253 } else {
3254 return radv_lookup_entrypoint_checked(pName,
3255 instance ? instance->apiVersion : 0,
3256 instance ? &instance->enabled_extensions : NULL,
3257 NULL);
3258 }
3259 }
3260
3261 /* The loader wants us to expose a second GetInstanceProcAddr function
3262 * to work around certain LD_PRELOAD issues seen in apps.
3263 */
3264 PUBLIC
3265 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
3266 VkInstance instance,
3267 const char* pName);
3268
3269 PUBLIC
3270 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
3271 VkInstance instance,
3272 const char* pName)
3273 {
3274 return radv_GetInstanceProcAddr(instance, pName);
3275 }
3276
3277 PUBLIC
3278 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
3279 VkInstance _instance,
3280 const char* pName);
3281
3282 PUBLIC
3283 VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetPhysicalDeviceProcAddr(
3284 VkInstance _instance,
3285 const char* pName)
3286 {
3287 RADV_FROM_HANDLE(radv_instance, instance, _instance);
3288
3289 return radv_lookup_physical_device_entrypoint_checked(pName,
3290 instance ? instance->apiVersion : 0,
3291 instance ? &instance->enabled_extensions : NULL);
3292 }
3293
3294 PFN_vkVoidFunction radv_GetDeviceProcAddr(
3295 VkDevice _device,
3296 const char* pName)
3297 {
3298 RADV_FROM_HANDLE(radv_device, device, _device);
3299 bool unchecked = device ? device->instance->debug_flags & RADV_DEBUG_ALL_ENTRYPOINTS : false;
3300
3301 if (unchecked) {
3302 return radv_lookup_entrypoint_unchecked(pName);
3303 } else {
3304 return radv_lookup_entrypoint_checked(pName,
3305 device->instance->apiVersion,
3306 &device->instance->enabled_extensions,
3307 &device->enabled_extensions);
3308 }
3309 }
3310
3311 bool radv_get_memory_fd(struct radv_device *device,
3312 struct radv_device_memory *memory,
3313 int *pFD)
3314 {
3315 struct radeon_bo_metadata metadata;
3316
3317 if (memory->image) {
3318 radv_init_metadata(device, memory->image, &metadata);
3319 device->ws->buffer_set_metadata(memory->bo, &metadata);
3320 }
3321
3322 return device->ws->buffer_get_fd(device->ws, memory->bo,
3323 pFD);
3324 }
3325
3326 static VkResult radv_alloc_memory(struct radv_device *device,
3327 const VkMemoryAllocateInfo* pAllocateInfo,
3328 const VkAllocationCallbacks* pAllocator,
3329 VkDeviceMemory* pMem)
3330 {
3331 struct radv_device_memory *mem;
3332 VkResult result;
3333 enum radeon_bo_domain domain;
3334 uint32_t flags = 0;
3335 enum radv_mem_type mem_type_index = device->physical_device->mem_type_indices[pAllocateInfo->memoryTypeIndex];
3336
3337 assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
3338
3339 if (pAllocateInfo->allocationSize == 0) {
3340 /* Apparently, this is allowed */
3341 *pMem = VK_NULL_HANDLE;
3342 return VK_SUCCESS;
3343 }
3344
3345 const VkImportMemoryFdInfoKHR *import_info =
3346 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
3347 const VkMemoryDedicatedAllocateInfo *dedicate_info =
3348 vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);
3349 const VkExportMemoryAllocateInfo *export_info =
3350 vk_find_struct_const(pAllocateInfo->pNext, EXPORT_MEMORY_ALLOCATE_INFO);
3351 const VkImportMemoryHostPointerInfoEXT *host_ptr_info =
3352 vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_HOST_POINTER_INFO_EXT);
3353
3354 const struct wsi_memory_allocate_info *wsi_info =
3355 vk_find_struct_const(pAllocateInfo->pNext, WSI_MEMORY_ALLOCATE_INFO_MESA);
3356
3357 mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
3358 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3359 if (mem == NULL)
3360 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3361
3362 if (wsi_info && wsi_info->implicit_sync)
3363 flags |= RADEON_FLAG_IMPLICIT_SYNC;
3364
3365 if (dedicate_info) {
3366 mem->image = radv_image_from_handle(dedicate_info->image);
3367 mem->buffer = radv_buffer_from_handle(dedicate_info->buffer);
3368 } else {
3369 mem->image = NULL;
3370 mem->buffer = NULL;
3371 }
3372
3373 float priority_float = 0.5;
3374 const struct VkMemoryPriorityAllocateInfoEXT *priority_ext =
3375 vk_find_struct_const(pAllocateInfo->pNext,
3376 MEMORY_PRIORITY_ALLOCATE_INFO_EXT);
3377 if (priority_ext)
3378 priority_float = priority_ext->priority;
3379
3380 unsigned priority = MIN2(RADV_BO_PRIORITY_APPLICATION_MAX - 1,
3381 (int)(priority_float * RADV_BO_PRIORITY_APPLICATION_MAX));
3382
3383 mem->user_ptr = NULL;
3384
3385 if (import_info) {
3386 assert(import_info->handleType ==
3387 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
3388 import_info->handleType ==
3389 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
3390 mem->bo = device->ws->buffer_from_fd(device->ws, import_info->fd,
3391 priority, NULL, NULL);
3392 if (!mem->bo) {
3393 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
3394 goto fail;
3395 } else {
3396 close(import_info->fd);
3397 }
3398 } else if (host_ptr_info) {
3399 assert(host_ptr_info->handleType == VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT);
3400 assert(mem_type_index == RADV_MEM_TYPE_GTT_CACHED);
3401 mem->bo = device->ws->buffer_from_ptr(device->ws, host_ptr_info->pHostPointer,
3402 pAllocateInfo->allocationSize,
3403 priority);
3404 if (!mem->bo) {
3405 result = VK_ERROR_INVALID_EXTERNAL_HANDLE;
3406 goto fail;
3407 } else {
3408 mem->user_ptr = host_ptr_info->pHostPointer;
3409 }
3410 } else {
3411 uint64_t alloc_size = align_u64(pAllocateInfo->allocationSize, 4096);
3412 if (mem_type_index == RADV_MEM_TYPE_GTT_WRITE_COMBINE ||
3413 mem_type_index == RADV_MEM_TYPE_GTT_CACHED)
3414 domain = RADEON_DOMAIN_GTT;
3415 else
3416 domain = RADEON_DOMAIN_VRAM;
3417
3418 if (mem_type_index == RADV_MEM_TYPE_VRAM)
3419 flags |= RADEON_FLAG_NO_CPU_ACCESS;
3420 else
3421 flags |= RADEON_FLAG_CPU_ACCESS;
3422
3423 if (mem_type_index == RADV_MEM_TYPE_GTT_WRITE_COMBINE)
3424 flags |= RADEON_FLAG_GTT_WC;
3425
3426 if (!dedicate_info && !import_info && (!export_info || !export_info->handleTypes)) {
3427 flags |= RADEON_FLAG_NO_INTERPROCESS_SHARING;
3428 if (device->use_global_bo_list) {
3429 flags |= RADEON_FLAG_PREFER_LOCAL_BO;
3430 }
3431 }
3432
3433 mem->bo = device->ws->buffer_create(device->ws, alloc_size, device->physical_device->rad_info.max_alignment,
3434 domain, flags, priority);
3435
3436 if (!mem->bo) {
3437 result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
3438 goto fail;
3439 }
3440 mem->type_index = mem_type_index;
3441 }
3442
3443 result = radv_bo_list_add(device, mem->bo);
3444 if (result != VK_SUCCESS)
3445 goto fail_bo;
3446
3447 *pMem = radv_device_memory_to_handle(mem);
3448
3449 return VK_SUCCESS;
3450
3451 fail_bo:
3452 device->ws->buffer_destroy(mem->bo);
3453 fail:
3454 vk_free2(&device->alloc, pAllocator, mem);
3455
3456 return result;
3457 }
3458
3459 VkResult radv_AllocateMemory(
3460 VkDevice _device,
3461 const VkMemoryAllocateInfo* pAllocateInfo,
3462 const VkAllocationCallbacks* pAllocator,
3463 VkDeviceMemory* pMem)
3464 {
3465 RADV_FROM_HANDLE(radv_device, device, _device);
3466 return radv_alloc_memory(device, pAllocateInfo, pAllocator, pMem);
3467 }
3468
3469 void radv_FreeMemory(
3470 VkDevice _device,
3471 VkDeviceMemory _mem,
3472 const VkAllocationCallbacks* pAllocator)
3473 {
3474 RADV_FROM_HANDLE(radv_device, device, _device);
3475 RADV_FROM_HANDLE(radv_device_memory, mem, _mem);
3476
3477 if (mem == NULL)
3478 return;
3479
3480 radv_bo_list_remove(device, mem->bo);
3481 device->ws->buffer_destroy(mem->bo);
3482 mem->bo = NULL;
3483
3484 vk_free2(&device->alloc, pAllocator, mem);
3485 }
3486
3487 VkResult radv_MapMemory(
3488 VkDevice _device,
3489 VkDeviceMemory _memory,
3490 VkDeviceSize offset,
3491 VkDeviceSize size,
3492 VkMemoryMapFlags flags,
3493 void** ppData)
3494 {
3495 RADV_FROM_HANDLE(radv_device, device, _device);
3496 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
3497
3498 if (mem == NULL) {
3499 *ppData = NULL;
3500 return VK_SUCCESS;
3501 }
3502
3503 if (mem->user_ptr)
3504 *ppData = mem->user_ptr;
3505 else
3506 *ppData = device->ws->buffer_map(mem->bo);
3507
3508 if (*ppData) {
3509 *ppData += offset;
3510 return VK_SUCCESS;
3511 }
3512
3513 return vk_error(device->instance, VK_ERROR_MEMORY_MAP_FAILED);
3514 }
3515
3516 void radv_UnmapMemory(
3517 VkDevice _device,
3518 VkDeviceMemory _memory)
3519 {
3520 RADV_FROM_HANDLE(radv_device, device, _device);
3521 RADV_FROM_HANDLE(radv_device_memory, mem, _memory);
3522
3523 if (mem == NULL)
3524 return;
3525
3526 if (mem->user_ptr == NULL)
3527 device->ws->buffer_unmap(mem->bo);
3528 }
3529
3530 VkResult radv_FlushMappedMemoryRanges(
3531 VkDevice _device,
3532 uint32_t memoryRangeCount,
3533 const VkMappedMemoryRange* pMemoryRanges)
3534 {
3535 return VK_SUCCESS;
3536 }
3537
3538 VkResult radv_InvalidateMappedMemoryRanges(
3539 VkDevice _device,
3540 uint32_t memoryRangeCount,
3541 const VkMappedMemoryRange* pMemoryRanges)
3542 {
3543 return VK_SUCCESS;
3544 }
3545
3546 void radv_GetBufferMemoryRequirements(
3547 VkDevice _device,
3548 VkBuffer _buffer,
3549 VkMemoryRequirements* pMemoryRequirements)
3550 {
3551 RADV_FROM_HANDLE(radv_device, device, _device);
3552 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
3553
3554 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
3555
3556 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
3557 pMemoryRequirements->alignment = 4096;
3558 else
3559 pMemoryRequirements->alignment = 16;
3560
3561 pMemoryRequirements->size = align64(buffer->size, pMemoryRequirements->alignment);
3562 }
3563
3564 void radv_GetBufferMemoryRequirements2(
3565 VkDevice device,
3566 const VkBufferMemoryRequirementsInfo2 *pInfo,
3567 VkMemoryRequirements2 *pMemoryRequirements)
3568 {
3569 radv_GetBufferMemoryRequirements(device, pInfo->buffer,
3570 &pMemoryRequirements->memoryRequirements);
3571 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
3572 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3573 switch (ext->sType) {
3574 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3575 VkMemoryDedicatedRequirements *req =
3576 (VkMemoryDedicatedRequirements *) ext;
3577 req->requiresDedicatedAllocation = buffer->shareable;
3578 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
3579 break;
3580 }
3581 default:
3582 break;
3583 }
3584 }
3585 }
3586
3587 void radv_GetImageMemoryRequirements(
3588 VkDevice _device,
3589 VkImage _image,
3590 VkMemoryRequirements* pMemoryRequirements)
3591 {
3592 RADV_FROM_HANDLE(radv_device, device, _device);
3593 RADV_FROM_HANDLE(radv_image, image, _image);
3594
3595 pMemoryRequirements->memoryTypeBits = (1u << device->physical_device->memory_properties.memoryTypeCount) - 1;
3596
3597 pMemoryRequirements->size = image->size;
3598 pMemoryRequirements->alignment = image->alignment;
3599 }
3600
3601 void radv_GetImageMemoryRequirements2(
3602 VkDevice device,
3603 const VkImageMemoryRequirementsInfo2 *pInfo,
3604 VkMemoryRequirements2 *pMemoryRequirements)
3605 {
3606 radv_GetImageMemoryRequirements(device, pInfo->image,
3607 &pMemoryRequirements->memoryRequirements);
3608
3609 RADV_FROM_HANDLE(radv_image, image, pInfo->image);
3610
3611 vk_foreach_struct(ext, pMemoryRequirements->pNext) {
3612 switch (ext->sType) {
3613 case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS: {
3614 VkMemoryDedicatedRequirements *req =
3615 (VkMemoryDedicatedRequirements *) ext;
3616 req->requiresDedicatedAllocation = image->shareable;
3617 req->prefersDedicatedAllocation = req->requiresDedicatedAllocation;
3618 break;
3619 }
3620 default:
3621 break;
3622 }
3623 }
3624 }
3625
3626 void radv_GetImageSparseMemoryRequirements(
3627 VkDevice device,
3628 VkImage image,
3629 uint32_t* pSparseMemoryRequirementCount,
3630 VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
3631 {
3632 stub();
3633 }
3634
3635 void radv_GetImageSparseMemoryRequirements2(
3636 VkDevice device,
3637 const VkImageSparseMemoryRequirementsInfo2 *pInfo,
3638 uint32_t* pSparseMemoryRequirementCount,
3639 VkSparseImageMemoryRequirements2 *pSparseMemoryRequirements)
3640 {
3641 stub();
3642 }
3643
3644 void radv_GetDeviceMemoryCommitment(
3645 VkDevice device,
3646 VkDeviceMemory memory,
3647 VkDeviceSize* pCommittedMemoryInBytes)
3648 {
3649 *pCommittedMemoryInBytes = 0;
3650 }
3651
3652 VkResult radv_BindBufferMemory2(VkDevice device,
3653 uint32_t bindInfoCount,
3654 const VkBindBufferMemoryInfo *pBindInfos)
3655 {
3656 for (uint32_t i = 0; i < bindInfoCount; ++i) {
3657 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
3658 RADV_FROM_HANDLE(radv_buffer, buffer, pBindInfos[i].buffer);
3659
3660 if (mem) {
3661 buffer->bo = mem->bo;
3662 buffer->offset = pBindInfos[i].memoryOffset;
3663 } else {
3664 buffer->bo = NULL;
3665 }
3666 }
3667 return VK_SUCCESS;
3668 }
3669
3670 VkResult radv_BindBufferMemory(
3671 VkDevice device,
3672 VkBuffer buffer,
3673 VkDeviceMemory memory,
3674 VkDeviceSize memoryOffset)
3675 {
3676 const VkBindBufferMemoryInfo info = {
3677 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
3678 .buffer = buffer,
3679 .memory = memory,
3680 .memoryOffset = memoryOffset
3681 };
3682
3683 return radv_BindBufferMemory2(device, 1, &info);
3684 }
3685
3686 VkResult radv_BindImageMemory2(VkDevice device,
3687 uint32_t bindInfoCount,
3688 const VkBindImageMemoryInfo *pBindInfos)
3689 {
3690 for (uint32_t i = 0; i < bindInfoCount; ++i) {
3691 RADV_FROM_HANDLE(radv_device_memory, mem, pBindInfos[i].memory);
3692 RADV_FROM_HANDLE(radv_image, image, pBindInfos[i].image);
3693
3694 if (mem) {
3695 image->bo = mem->bo;
3696 image->offset = pBindInfos[i].memoryOffset;
3697 } else {
3698 image->bo = NULL;
3699 image->offset = 0;
3700 }
3701 }
3702 return VK_SUCCESS;
3703 }
3704
3705
3706 VkResult radv_BindImageMemory(
3707 VkDevice device,
3708 VkImage image,
3709 VkDeviceMemory memory,
3710 VkDeviceSize memoryOffset)
3711 {
3712 const VkBindImageMemoryInfo info = {
3713 .sType = VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO,
3714 .image = image,
3715 .memory = memory,
3716 .memoryOffset = memoryOffset
3717 };
3718
3719 return radv_BindImageMemory2(device, 1, &info);
3720 }
3721
3722
3723 static void
3724 radv_sparse_buffer_bind_memory(struct radv_device *device,
3725 const VkSparseBufferMemoryBindInfo *bind)
3726 {
3727 RADV_FROM_HANDLE(radv_buffer, buffer, bind->buffer);
3728
3729 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3730 struct radv_device_memory *mem = NULL;
3731
3732 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3733 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3734
3735 device->ws->buffer_virtual_bind(buffer->bo,
3736 bind->pBinds[i].resourceOffset,
3737 bind->pBinds[i].size,
3738 mem ? mem->bo : NULL,
3739 bind->pBinds[i].memoryOffset);
3740 }
3741 }
3742
3743 static void
3744 radv_sparse_image_opaque_bind_memory(struct radv_device *device,
3745 const VkSparseImageOpaqueMemoryBindInfo *bind)
3746 {
3747 RADV_FROM_HANDLE(radv_image, image, bind->image);
3748
3749 for (uint32_t i = 0; i < bind->bindCount; ++i) {
3750 struct radv_device_memory *mem = NULL;
3751
3752 if (bind->pBinds[i].memory != VK_NULL_HANDLE)
3753 mem = radv_device_memory_from_handle(bind->pBinds[i].memory);
3754
3755 device->ws->buffer_virtual_bind(image->bo,
3756 bind->pBinds[i].resourceOffset,
3757 bind->pBinds[i].size,
3758 mem ? mem->bo : NULL,
3759 bind->pBinds[i].memoryOffset);
3760 }
3761 }
3762
3763 VkResult radv_QueueBindSparse(
3764 VkQueue _queue,
3765 uint32_t bindInfoCount,
3766 const VkBindSparseInfo* pBindInfo,
3767 VkFence _fence)
3768 {
3769 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3770 RADV_FROM_HANDLE(radv_queue, queue, _queue);
3771 struct radeon_winsys_fence *base_fence = fence ? fence->fence : NULL;
3772 bool fence_emitted = false;
3773 VkResult result;
3774 int ret;
3775
3776 for (uint32_t i = 0; i < bindInfoCount; ++i) {
3777 struct radv_winsys_sem_info sem_info;
3778 for (uint32_t j = 0; j < pBindInfo[i].bufferBindCount; ++j) {
3779 radv_sparse_buffer_bind_memory(queue->device,
3780 pBindInfo[i].pBufferBinds + j);
3781 }
3782
3783 for (uint32_t j = 0; j < pBindInfo[i].imageOpaqueBindCount; ++j) {
3784 radv_sparse_image_opaque_bind_memory(queue->device,
3785 pBindInfo[i].pImageOpaqueBinds + j);
3786 }
3787
3788 VkResult result;
3789 result = radv_alloc_sem_info(queue->device->instance,
3790 &sem_info,
3791 pBindInfo[i].waitSemaphoreCount,
3792 pBindInfo[i].pWaitSemaphores,
3793 pBindInfo[i].signalSemaphoreCount,
3794 pBindInfo[i].pSignalSemaphores,
3795 _fence);
3796 if (result != VK_SUCCESS)
3797 return result;
3798
3799 if (pBindInfo[i].waitSemaphoreCount || pBindInfo[i].signalSemaphoreCount) {
3800 ret = queue->device->ws->cs_submit(queue->hw_ctx, queue->queue_idx,
3801 &queue->device->empty_cs[queue->queue_family_index],
3802 1, NULL, NULL,
3803 &sem_info, NULL,
3804 false, base_fence);
3805 if (ret) {
3806 radv_loge("failed to submit CS %d\n", i);
3807 abort();
3808 }
3809
3810 fence_emitted = true;
3811 }
3812
3813 radv_free_sem_info(&sem_info);
3814
3815 }
3816
3817 if (fence) {
3818 if (!fence_emitted) {
3819 result = radv_signal_fence(queue, fence);
3820 if (result != VK_SUCCESS)
3821 return result;
3822 }
3823 }
3824
3825 return VK_SUCCESS;
3826 }
3827
3828 VkResult radv_CreateFence(
3829 VkDevice _device,
3830 const VkFenceCreateInfo* pCreateInfo,
3831 const VkAllocationCallbacks* pAllocator,
3832 VkFence* pFence)
3833 {
3834 RADV_FROM_HANDLE(radv_device, device, _device);
3835 const VkExportFenceCreateInfo *export =
3836 vk_find_struct_const(pCreateInfo->pNext, EXPORT_FENCE_CREATE_INFO);
3837 VkExternalFenceHandleTypeFlags handleTypes =
3838 export ? export->handleTypes : 0;
3839
3840 struct radv_fence *fence = vk_alloc2(&device->alloc, pAllocator,
3841 sizeof(*fence), 8,
3842 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
3843
3844 if (!fence)
3845 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3846
3847 fence->fence_wsi = NULL;
3848 fence->temp_syncobj = 0;
3849 if (device->always_use_syncobj || handleTypes) {
3850 int ret = device->ws->create_syncobj(device->ws, &fence->syncobj);
3851 if (ret) {
3852 vk_free2(&device->alloc, pAllocator, fence);
3853 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3854 }
3855 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) {
3856 device->ws->signal_syncobj(device->ws, fence->syncobj);
3857 }
3858 fence->fence = NULL;
3859 } else {
3860 fence->fence = device->ws->create_fence();
3861 if (!fence->fence) {
3862 vk_free2(&device->alloc, pAllocator, fence);
3863 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3864 }
3865 fence->syncobj = 0;
3866 if (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT)
3867 device->ws->signal_fence(fence->fence);
3868 }
3869
3870 *pFence = radv_fence_to_handle(fence);
3871
3872 return VK_SUCCESS;
3873 }
3874
3875 void radv_DestroyFence(
3876 VkDevice _device,
3877 VkFence _fence,
3878 const VkAllocationCallbacks* pAllocator)
3879 {
3880 RADV_FROM_HANDLE(radv_device, device, _device);
3881 RADV_FROM_HANDLE(radv_fence, fence, _fence);
3882
3883 if (!fence)
3884 return;
3885
3886 if (fence->temp_syncobj)
3887 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
3888 if (fence->syncobj)
3889 device->ws->destroy_syncobj(device->ws, fence->syncobj);
3890 if (fence->fence)
3891 device->ws->destroy_fence(fence->fence);
3892 if (fence->fence_wsi)
3893 fence->fence_wsi->destroy(fence->fence_wsi);
3894 vk_free2(&device->alloc, pAllocator, fence);
3895 }
3896
3897
3898 uint64_t radv_get_current_time(void)
3899 {
3900 struct timespec tv;
3901 clock_gettime(CLOCK_MONOTONIC, &tv);
3902 return tv.tv_nsec + tv.tv_sec*1000000000ull;
3903 }
3904
3905 static uint64_t radv_get_absolute_timeout(uint64_t timeout)
3906 {
3907 uint64_t current_time = radv_get_current_time();
3908
3909 timeout = MIN2(UINT64_MAX - current_time, timeout);
3910
3911 return current_time + timeout;
3912 }
3913
3914
3915 static bool radv_all_fences_plain_and_submitted(struct radv_device *device,
3916 uint32_t fenceCount, const VkFence *pFences)
3917 {
3918 for (uint32_t i = 0; i < fenceCount; ++i) {
3919 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3920 if (fence->fence == NULL || fence->syncobj ||
3921 fence->temp_syncobj || fence->fence_wsi ||
3922 (!device->ws->is_fence_waitable(fence->fence)))
3923 return false;
3924 }
3925 return true;
3926 }
3927
3928 static bool radv_all_fences_syncobj(uint32_t fenceCount, const VkFence *pFences)
3929 {
3930 for (uint32_t i = 0; i < fenceCount; ++i) {
3931 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3932 if (fence->syncobj == 0 && fence->temp_syncobj == 0)
3933 return false;
3934 }
3935 return true;
3936 }
3937
3938 VkResult radv_WaitForFences(
3939 VkDevice _device,
3940 uint32_t fenceCount,
3941 const VkFence* pFences,
3942 VkBool32 waitAll,
3943 uint64_t timeout)
3944 {
3945 RADV_FROM_HANDLE(radv_device, device, _device);
3946 timeout = radv_get_absolute_timeout(timeout);
3947
3948 if (device->always_use_syncobj &&
3949 radv_all_fences_syncobj(fenceCount, pFences))
3950 {
3951 uint32_t *handles = malloc(sizeof(uint32_t) * fenceCount);
3952 if (!handles)
3953 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3954
3955 for (uint32_t i = 0; i < fenceCount; ++i) {
3956 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3957 handles[i] = fence->temp_syncobj ? fence->temp_syncobj : fence->syncobj;
3958 }
3959
3960 bool success = device->ws->wait_syncobj(device->ws, handles, fenceCount, waitAll, timeout);
3961
3962 free(handles);
3963 return success ? VK_SUCCESS : VK_TIMEOUT;
3964 }
3965
3966 if (!waitAll && fenceCount > 1) {
3967 /* Not doing this by default for waitAll, due to needing to allocate twice. */
3968 if (device->physical_device->rad_info.drm_minor >= 10 && radv_all_fences_plain_and_submitted(device, fenceCount, pFences)) {
3969 uint32_t wait_count = 0;
3970 struct radeon_winsys_fence **fences = malloc(sizeof(struct radeon_winsys_fence *) * fenceCount);
3971 if (!fences)
3972 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
3973
3974 for (uint32_t i = 0; i < fenceCount; ++i) {
3975 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
3976
3977 if (device->ws->fence_wait(device->ws, fence->fence, false, 0)) {
3978 free(fences);
3979 return VK_SUCCESS;
3980 }
3981
3982 fences[wait_count++] = fence->fence;
3983 }
3984
3985 bool success = device->ws->fences_wait(device->ws, fences, wait_count,
3986 waitAll, timeout - radv_get_current_time());
3987
3988 free(fences);
3989 return success ? VK_SUCCESS : VK_TIMEOUT;
3990 }
3991
3992 while(radv_get_current_time() <= timeout) {
3993 for (uint32_t i = 0; i < fenceCount; ++i) {
3994 if (radv_GetFenceStatus(_device, pFences[i]) == VK_SUCCESS)
3995 return VK_SUCCESS;
3996 }
3997 }
3998 return VK_TIMEOUT;
3999 }
4000
4001 for (uint32_t i = 0; i < fenceCount; ++i) {
4002 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4003 bool expired = false;
4004
4005 if (fence->temp_syncobj) {
4006 if (!device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, timeout))
4007 return VK_TIMEOUT;
4008 continue;
4009 }
4010
4011 if (fence->syncobj) {
4012 if (!device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, timeout))
4013 return VK_TIMEOUT;
4014 continue;
4015 }
4016
4017 if (fence->fence) {
4018 if (!device->ws->is_fence_waitable(fence->fence)) {
4019 while(!device->ws->is_fence_waitable(fence->fence) &&
4020 radv_get_current_time() <= timeout)
4021 /* Do nothing */;
4022 }
4023
4024 expired = device->ws->fence_wait(device->ws,
4025 fence->fence,
4026 true, timeout);
4027 if (!expired)
4028 return VK_TIMEOUT;
4029 }
4030
4031 if (fence->fence_wsi) {
4032 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, timeout);
4033 if (result != VK_SUCCESS)
4034 return result;
4035 }
4036 }
4037
4038 return VK_SUCCESS;
4039 }
4040
4041 VkResult radv_ResetFences(VkDevice _device,
4042 uint32_t fenceCount,
4043 const VkFence *pFences)
4044 {
4045 RADV_FROM_HANDLE(radv_device, device, _device);
4046
4047 for (unsigned i = 0; i < fenceCount; ++i) {
4048 RADV_FROM_HANDLE(radv_fence, fence, pFences[i]);
4049 if (fence->fence)
4050 device->ws->reset_fence(fence->fence);
4051
4052 /* Per spec, we first restore the permanent payload, and then reset, so
4053 * having a temp syncobj should not skip resetting the permanent syncobj. */
4054 if (fence->temp_syncobj) {
4055 device->ws->destroy_syncobj(device->ws, fence->temp_syncobj);
4056 fence->temp_syncobj = 0;
4057 }
4058
4059 if (fence->syncobj) {
4060 device->ws->reset_syncobj(device->ws, fence->syncobj);
4061 }
4062 }
4063
4064 return VK_SUCCESS;
4065 }
4066
4067 VkResult radv_GetFenceStatus(VkDevice _device, VkFence _fence)
4068 {
4069 RADV_FROM_HANDLE(radv_device, device, _device);
4070 RADV_FROM_HANDLE(radv_fence, fence, _fence);
4071
4072 if (fence->temp_syncobj) {
4073 bool success = device->ws->wait_syncobj(device->ws, &fence->temp_syncobj, 1, true, 0);
4074 return success ? VK_SUCCESS : VK_NOT_READY;
4075 }
4076
4077 if (fence->syncobj) {
4078 bool success = device->ws->wait_syncobj(device->ws, &fence->syncobj, 1, true, 0);
4079 return success ? VK_SUCCESS : VK_NOT_READY;
4080 }
4081
4082 if (fence->fence) {
4083 if (!device->ws->fence_wait(device->ws, fence->fence, false, 0))
4084 return VK_NOT_READY;
4085 }
4086 if (fence->fence_wsi) {
4087 VkResult result = fence->fence_wsi->wait(fence->fence_wsi, 0);
4088
4089 if (result != VK_SUCCESS) {
4090 if (result == VK_TIMEOUT)
4091 return VK_NOT_READY;
4092 return result;
4093 }
4094 }
4095 return VK_SUCCESS;
4096 }
4097
4098
4099 // Queue semaphore functions
4100
4101 VkResult radv_CreateSemaphore(
4102 VkDevice _device,
4103 const VkSemaphoreCreateInfo* pCreateInfo,
4104 const VkAllocationCallbacks* pAllocator,
4105 VkSemaphore* pSemaphore)
4106 {
4107 RADV_FROM_HANDLE(radv_device, device, _device);
4108 const VkExportSemaphoreCreateInfo *export =
4109 vk_find_struct_const(pCreateInfo->pNext, EXPORT_SEMAPHORE_CREATE_INFO);
4110 VkExternalSemaphoreHandleTypeFlags handleTypes =
4111 export ? export->handleTypes : 0;
4112
4113 struct radv_semaphore *sem = vk_alloc2(&device->alloc, pAllocator,
4114 sizeof(*sem), 8,
4115 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4116 if (!sem)
4117 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4118
4119 sem->temp_syncobj = 0;
4120 /* create a syncobject if we are going to export this semaphore */
4121 if (device->always_use_syncobj || handleTypes) {
4122 assert (device->physical_device->rad_info.has_syncobj);
4123 int ret = device->ws->create_syncobj(device->ws, &sem->syncobj);
4124 if (ret) {
4125 vk_free2(&device->alloc, pAllocator, sem);
4126 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4127 }
4128 sem->sem = NULL;
4129 } else {
4130 sem->sem = device->ws->create_sem(device->ws);
4131 if (!sem->sem) {
4132 vk_free2(&device->alloc, pAllocator, sem);
4133 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4134 }
4135 sem->syncobj = 0;
4136 }
4137
4138 *pSemaphore = radv_semaphore_to_handle(sem);
4139 return VK_SUCCESS;
4140 }
4141
4142 void radv_DestroySemaphore(
4143 VkDevice _device,
4144 VkSemaphore _semaphore,
4145 const VkAllocationCallbacks* pAllocator)
4146 {
4147 RADV_FROM_HANDLE(radv_device, device, _device);
4148 RADV_FROM_HANDLE(radv_semaphore, sem, _semaphore);
4149 if (!_semaphore)
4150 return;
4151
4152 if (sem->syncobj)
4153 device->ws->destroy_syncobj(device->ws, sem->syncobj);
4154 else
4155 device->ws->destroy_sem(sem->sem);
4156 vk_free2(&device->alloc, pAllocator, sem);
4157 }
4158
4159 VkResult radv_CreateEvent(
4160 VkDevice _device,
4161 const VkEventCreateInfo* pCreateInfo,
4162 const VkAllocationCallbacks* pAllocator,
4163 VkEvent* pEvent)
4164 {
4165 RADV_FROM_HANDLE(radv_device, device, _device);
4166 struct radv_event *event = vk_alloc2(&device->alloc, pAllocator,
4167 sizeof(*event), 8,
4168 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4169
4170 if (!event)
4171 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4172
4173 event->bo = device->ws->buffer_create(device->ws, 8, 8,
4174 RADEON_DOMAIN_GTT,
4175 RADEON_FLAG_VA_UNCACHED | RADEON_FLAG_CPU_ACCESS | RADEON_FLAG_NO_INTERPROCESS_SHARING,
4176 RADV_BO_PRIORITY_FENCE);
4177 if (!event->bo) {
4178 vk_free2(&device->alloc, pAllocator, event);
4179 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4180 }
4181
4182 event->map = (uint64_t*)device->ws->buffer_map(event->bo);
4183
4184 *pEvent = radv_event_to_handle(event);
4185
4186 return VK_SUCCESS;
4187 }
4188
4189 void radv_DestroyEvent(
4190 VkDevice _device,
4191 VkEvent _event,
4192 const VkAllocationCallbacks* pAllocator)
4193 {
4194 RADV_FROM_HANDLE(radv_device, device, _device);
4195 RADV_FROM_HANDLE(radv_event, event, _event);
4196
4197 if (!event)
4198 return;
4199 device->ws->buffer_destroy(event->bo);
4200 vk_free2(&device->alloc, pAllocator, event);
4201 }
4202
4203 VkResult radv_GetEventStatus(
4204 VkDevice _device,
4205 VkEvent _event)
4206 {
4207 RADV_FROM_HANDLE(radv_event, event, _event);
4208
4209 if (*event->map == 1)
4210 return VK_EVENT_SET;
4211 return VK_EVENT_RESET;
4212 }
4213
4214 VkResult radv_SetEvent(
4215 VkDevice _device,
4216 VkEvent _event)
4217 {
4218 RADV_FROM_HANDLE(radv_event, event, _event);
4219 *event->map = 1;
4220
4221 return VK_SUCCESS;
4222 }
4223
4224 VkResult radv_ResetEvent(
4225 VkDevice _device,
4226 VkEvent _event)
4227 {
4228 RADV_FROM_HANDLE(radv_event, event, _event);
4229 *event->map = 0;
4230
4231 return VK_SUCCESS;
4232 }
4233
4234 VkResult radv_CreateBuffer(
4235 VkDevice _device,
4236 const VkBufferCreateInfo* pCreateInfo,
4237 const VkAllocationCallbacks* pAllocator,
4238 VkBuffer* pBuffer)
4239 {
4240 RADV_FROM_HANDLE(radv_device, device, _device);
4241 struct radv_buffer *buffer;
4242
4243 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
4244
4245 buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
4246 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4247 if (buffer == NULL)
4248 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4249
4250 buffer->size = pCreateInfo->size;
4251 buffer->usage = pCreateInfo->usage;
4252 buffer->bo = NULL;
4253 buffer->offset = 0;
4254 buffer->flags = pCreateInfo->flags;
4255
4256 buffer->shareable = vk_find_struct_const(pCreateInfo->pNext,
4257 EXTERNAL_MEMORY_BUFFER_CREATE_INFO) != NULL;
4258
4259 if (pCreateInfo->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) {
4260 buffer->bo = device->ws->buffer_create(device->ws,
4261 align64(buffer->size, 4096),
4262 4096, 0, RADEON_FLAG_VIRTUAL,
4263 RADV_BO_PRIORITY_VIRTUAL);
4264 if (!buffer->bo) {
4265 vk_free2(&device->alloc, pAllocator, buffer);
4266 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
4267 }
4268 }
4269
4270 *pBuffer = radv_buffer_to_handle(buffer);
4271
4272 return VK_SUCCESS;
4273 }
4274
4275 void radv_DestroyBuffer(
4276 VkDevice _device,
4277 VkBuffer _buffer,
4278 const VkAllocationCallbacks* pAllocator)
4279 {
4280 RADV_FROM_HANDLE(radv_device, device, _device);
4281 RADV_FROM_HANDLE(radv_buffer, buffer, _buffer);
4282
4283 if (!buffer)
4284 return;
4285
4286 if (buffer->flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)
4287 device->ws->buffer_destroy(buffer->bo);
4288
4289 vk_free2(&device->alloc, pAllocator, buffer);
4290 }
4291
4292 VkDeviceAddress radv_GetBufferDeviceAddressEXT(
4293 VkDevice device,
4294 const VkBufferDeviceAddressInfoEXT* pInfo)
4295 {
4296 RADV_FROM_HANDLE(radv_buffer, buffer, pInfo->buffer);
4297 return radv_buffer_get_va(buffer->bo) + buffer->offset;
4298 }
4299
4300
4301 static inline unsigned
4302 si_tile_mode_index(const struct radv_image_plane *plane, unsigned level, bool stencil)
4303 {
4304 if (stencil)
4305 return plane->surface.u.legacy.stencil_tiling_index[level];
4306 else
4307 return plane->surface.u.legacy.tiling_index[level];
4308 }
4309
4310 static uint32_t radv_surface_max_layer_count(struct radv_image_view *iview)
4311 {
4312 return iview->type == VK_IMAGE_VIEW_TYPE_3D ? iview->extent.depth : (iview->base_layer + iview->layer_count);
4313 }
4314
4315 static uint32_t
4316 radv_init_dcc_control_reg(struct radv_device *device,
4317 struct radv_image_view *iview)
4318 {
4319 unsigned max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_256B;
4320 unsigned min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_32B;
4321 unsigned max_compressed_block_size;
4322 unsigned independent_128b_blocks;
4323 unsigned independent_64b_blocks;
4324
4325 if (!radv_dcc_enabled(iview->image, iview->base_mip))
4326 return 0;
4327
4328 if (!device->physical_device->rad_info.has_dedicated_vram) {
4329 /* amdvlk: [min-compressed-block-size] should be set to 32 for
4330 * dGPU and 64 for APU because all of our APUs to date use
4331 * DIMMs which have a request granularity size of 64B while all
4332 * other chips have a 32B request size.
4333 */
4334 min_compressed_block_size = V_028C78_MIN_BLOCK_SIZE_64B;
4335 }
4336
4337 if (device->physical_device->rad_info.chip_class >= GFX10) {
4338 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
4339 independent_64b_blocks = 0;
4340 independent_128b_blocks = 1;
4341 } else {
4342 independent_128b_blocks = 0;
4343
4344 if (iview->image->info.samples > 1) {
4345 if (iview->image->planes[0].surface.bpe == 1)
4346 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
4347 else if (iview->image->planes[0].surface.bpe == 2)
4348 max_uncompressed_block_size = V_028C78_MAX_BLOCK_SIZE_128B;
4349 }
4350
4351 if (iview->image->usage & (VK_IMAGE_USAGE_SAMPLED_BIT |
4352 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
4353 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {
4354 /* If this DCC image is potentially going to be used in texture
4355 * fetches, we need some special settings.
4356 */
4357 independent_64b_blocks = 1;
4358 max_compressed_block_size = V_028C78_MAX_BLOCK_SIZE_64B;
4359 } else {
4360 /* MAX_UNCOMPRESSED_BLOCK_SIZE must be >=
4361 * MAX_COMPRESSED_BLOCK_SIZE. Set MAX_COMPRESSED_BLOCK_SIZE as
4362 * big as possible for better compression state.
4363 */
4364 independent_64b_blocks = 0;
4365 max_compressed_block_size = max_uncompressed_block_size;
4366 }
4367 }
4368
4369 return S_028C78_MAX_UNCOMPRESSED_BLOCK_SIZE(max_uncompressed_block_size) |
4370 S_028C78_MAX_COMPRESSED_BLOCK_SIZE(max_compressed_block_size) |
4371 S_028C78_MIN_COMPRESSED_BLOCK_SIZE(min_compressed_block_size) |
4372 S_028C78_INDEPENDENT_64B_BLOCKS(independent_64b_blocks) |
4373 S_028C78_INDEPENDENT_128B_BLOCKS(independent_128b_blocks);
4374 }
4375
4376 void
4377 radv_initialise_color_surface(struct radv_device *device,
4378 struct radv_color_buffer_info *cb,
4379 struct radv_image_view *iview)
4380 {
4381 const struct vk_format_description *desc;
4382 unsigned ntype, format, swap, endian;
4383 unsigned blend_clamp = 0, blend_bypass = 0;
4384 uint64_t va;
4385 const struct radv_image_plane *plane = &iview->image->planes[iview->plane_id];
4386 const struct radeon_surf *surf = &plane->surface;
4387
4388 desc = vk_format_description(iview->vk_format);
4389
4390 memset(cb, 0, sizeof(*cb));
4391
4392 /* Intensity is implemented as Red, so treat it that way. */
4393 cb->cb_color_attrib = S_028C74_FORCE_DST_ALPHA_1(desc->swizzle[3] == VK_SWIZZLE_1);
4394
4395 va = radv_buffer_get_va(iview->bo) + iview->image->offset + plane->offset;
4396
4397 cb->cb_color_base = va >> 8;
4398
4399 if (device->physical_device->rad_info.chip_class >= GFX9) {
4400 struct gfx9_surf_meta_flags meta;
4401 if (iview->image->dcc_offset)
4402 meta = surf->u.gfx9.dcc;
4403 else
4404 meta = surf->u.gfx9.cmask;
4405
4406 if (device->physical_device->rad_info.chip_class >= GFX10) {
4407 cb->cb_color_attrib3 |= S_028EE0_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
4408 S_028EE0_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
4409 S_028EE0_CMASK_PIPE_ALIGNED(surf->u.gfx9.cmask.pipe_aligned) |
4410 S_028EE0_DCC_PIPE_ALIGNED(surf->u.gfx9.dcc.pipe_aligned);
4411 } else {
4412 cb->cb_color_attrib |= S_028C74_COLOR_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
4413 S_028C74_FMASK_SW_MODE(surf->u.gfx9.fmask.swizzle_mode) |
4414 S_028C74_RB_ALIGNED(meta.rb_aligned) |
4415 S_028C74_PIPE_ALIGNED(meta.pipe_aligned);
4416 cb->cb_mrt_epitch = S_0287A0_EPITCH(surf->u.gfx9.surf.epitch);
4417 }
4418
4419 cb->cb_color_base += surf->u.gfx9.surf_offset >> 8;
4420 cb->cb_color_base |= surf->tile_swizzle;
4421 } else {
4422 const struct legacy_surf_level *level_info = &surf->u.legacy.level[iview->base_mip];
4423 unsigned pitch_tile_max, slice_tile_max, tile_mode_index;
4424
4425 cb->cb_color_base += level_info->offset >> 8;
4426 if (level_info->mode == RADEON_SURF_MODE_2D)
4427 cb->cb_color_base |= surf->tile_swizzle;
4428
4429 pitch_tile_max = level_info->nblk_x / 8 - 1;
4430 slice_tile_max = (level_info->nblk_x * level_info->nblk_y) / 64 - 1;
4431 tile_mode_index = si_tile_mode_index(plane, iview->base_mip, false);
4432
4433 cb->cb_color_pitch = S_028C64_TILE_MAX(pitch_tile_max);
4434 cb->cb_color_slice = S_028C68_TILE_MAX(slice_tile_max);
4435 cb->cb_color_cmask_slice = surf->u.legacy.cmask_slice_tile_max;
4436
4437 cb->cb_color_attrib |= S_028C74_TILE_MODE_INDEX(tile_mode_index);
4438
4439 if (radv_image_has_fmask(iview->image)) {
4440 if (device->physical_device->rad_info.chip_class >= GFX7)
4441 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(surf->u.legacy.fmask.pitch_in_pixels / 8 - 1);
4442 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(surf->u.legacy.fmask.tiling_index);
4443 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(surf->u.legacy.fmask.slice_tile_max);
4444 } else {
4445 /* This must be set for fast clear to work without FMASK. */
4446 if (device->physical_device->rad_info.chip_class >= GFX7)
4447 cb->cb_color_pitch |= S_028C64_FMASK_TILE_MAX(pitch_tile_max);
4448 cb->cb_color_attrib |= S_028C74_FMASK_TILE_MODE_INDEX(tile_mode_index);
4449 cb->cb_color_fmask_slice = S_028C88_TILE_MAX(slice_tile_max);
4450 }
4451 }
4452
4453 /* CMASK variables */
4454 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4455 va += iview->image->cmask_offset;
4456 cb->cb_color_cmask = va >> 8;
4457
4458 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4459 va += iview->image->dcc_offset;
4460
4461 if (radv_dcc_enabled(iview->image, iview->base_mip) &&
4462 device->physical_device->rad_info.chip_class <= GFX8)
4463 va += plane->surface.u.legacy.level[iview->base_mip].dcc_offset;
4464
4465 unsigned dcc_tile_swizzle = surf->tile_swizzle;
4466 dcc_tile_swizzle &= (surf->dcc_alignment - 1) >> 8;
4467
4468 cb->cb_dcc_base = va >> 8;
4469 cb->cb_dcc_base |= dcc_tile_swizzle;
4470
4471 /* GFX10 field has the same base shift as the GFX6 field. */
4472 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
4473 cb->cb_color_view = S_028C6C_SLICE_START(iview->base_layer) |
4474 S_028C6C_SLICE_MAX_GFX10(max_slice);
4475
4476 if (iview->image->info.samples > 1) {
4477 unsigned log_samples = util_logbase2(iview->image->info.samples);
4478
4479 cb->cb_color_attrib |= S_028C74_NUM_SAMPLES(log_samples) |
4480 S_028C74_NUM_FRAGMENTS(log_samples);
4481 }
4482
4483 if (radv_image_has_fmask(iview->image)) {
4484 va = radv_buffer_get_va(iview->bo) + iview->image->offset + iview->image->fmask_offset;
4485 cb->cb_color_fmask = va >> 8;
4486 cb->cb_color_fmask |= surf->fmask_tile_swizzle;
4487 } else {
4488 cb->cb_color_fmask = cb->cb_color_base;
4489 }
4490
4491 ntype = radv_translate_color_numformat(iview->vk_format,
4492 desc,
4493 vk_format_get_first_non_void_channel(iview->vk_format));
4494 format = radv_translate_colorformat(iview->vk_format);
4495 if (format == V_028C70_COLOR_INVALID || ntype == ~0u)
4496 radv_finishme("Illegal color\n");
4497 swap = radv_translate_colorswap(iview->vk_format, false);
4498 endian = radv_colorformat_endian_swap(format);
4499
4500 /* blend clamp should be set for all NORM/SRGB types */
4501 if (ntype == V_028C70_NUMBER_UNORM ||
4502 ntype == V_028C70_NUMBER_SNORM ||
4503 ntype == V_028C70_NUMBER_SRGB)
4504 blend_clamp = 1;
4505
4506 /* set blend bypass according to docs if SINT/UINT or
4507 8/24 COLOR variants */
4508 if (ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT ||
4509 format == V_028C70_COLOR_8_24 || format == V_028C70_COLOR_24_8 ||
4510 format == V_028C70_COLOR_X24_8_32_FLOAT) {
4511 blend_clamp = 0;
4512 blend_bypass = 1;
4513 }
4514 #if 0
4515 if ((ntype == V_028C70_NUMBER_UINT || ntype == V_028C70_NUMBER_SINT) &&
4516 (format == V_028C70_COLOR_8 ||
4517 format == V_028C70_COLOR_8_8 ||
4518 format == V_028C70_COLOR_8_8_8_8))
4519 ->color_is_int8 = true;
4520 #endif
4521 cb->cb_color_info = S_028C70_FORMAT(format) |
4522 S_028C70_COMP_SWAP(swap) |
4523 S_028C70_BLEND_CLAMP(blend_clamp) |
4524 S_028C70_BLEND_BYPASS(blend_bypass) |
4525 S_028C70_SIMPLE_FLOAT(1) |
4526 S_028C70_ROUND_MODE(ntype != V_028C70_NUMBER_UNORM &&
4527 ntype != V_028C70_NUMBER_SNORM &&
4528 ntype != V_028C70_NUMBER_SRGB &&
4529 format != V_028C70_COLOR_8_24 &&
4530 format != V_028C70_COLOR_24_8) |
4531 S_028C70_NUMBER_TYPE(ntype) |
4532 S_028C70_ENDIAN(endian);
4533 if (radv_image_has_fmask(iview->image)) {
4534 cb->cb_color_info |= S_028C70_COMPRESSION(1);
4535 if (device->physical_device->rad_info.chip_class == GFX6) {
4536 unsigned fmask_bankh = util_logbase2(surf->u.legacy.fmask.bankh);
4537 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(fmask_bankh);
4538 }
4539
4540 if (radv_image_is_tc_compat_cmask(iview->image)) {
4541 /* Allow the texture block to read FMASK directly
4542 * without decompressing it. This bit must be cleared
4543 * when performing FMASK_DECOMPRESS or DCC_COMPRESS,
4544 * otherwise the operation doesn't happen.
4545 */
4546 cb->cb_color_info |= S_028C70_FMASK_COMPRESS_1FRAG_ONLY(1);
4547
4548 /* Set CMASK into a tiling format that allows the
4549 * texture block to read it.
4550 */
4551 cb->cb_color_info |= S_028C70_CMASK_ADDR_TYPE(2);
4552 }
4553 }
4554
4555 if (radv_image_has_cmask(iview->image) &&
4556 !(device->instance->debug_flags & RADV_DEBUG_NO_FAST_CLEARS))
4557 cb->cb_color_info |= S_028C70_FAST_CLEAR(1);
4558
4559 if (radv_dcc_enabled(iview->image, iview->base_mip))
4560 cb->cb_color_info |= S_028C70_DCC_ENABLE(1);
4561
4562 cb->cb_dcc_control = radv_init_dcc_control_reg(device, iview);
4563
4564 /* This must be set for fast clear to work without FMASK. */
4565 if (!radv_image_has_fmask(iview->image) &&
4566 device->physical_device->rad_info.chip_class == GFX6) {
4567 unsigned bankh = util_logbase2(surf->u.legacy.bankh);
4568 cb->cb_color_attrib |= S_028C74_FMASK_BANK_HEIGHT(bankh);
4569 }
4570
4571 if (device->physical_device->rad_info.chip_class >= GFX9) {
4572 const struct vk_format_description *format_desc = vk_format_description(iview->image->vk_format);
4573
4574 unsigned mip0_depth = iview->image->type == VK_IMAGE_TYPE_3D ?
4575 (iview->extent.depth - 1) : (iview->image->info.array_size - 1);
4576 unsigned width = iview->extent.width / (iview->plane_id ? format_desc->width_divisor : 1);
4577 unsigned height = iview->extent.height / (iview->plane_id ? format_desc->height_divisor : 1);
4578
4579 if (device->physical_device->rad_info.chip_class >= GFX10) {
4580 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX10(iview->base_mip);
4581
4582 cb->cb_color_attrib3 |= S_028EE0_MIP0_DEPTH(mip0_depth) |
4583 S_028EE0_RESOURCE_TYPE(surf->u.gfx9.resource_type) |
4584 S_028EE0_RESOURCE_LEVEL(1);
4585 } else {
4586 cb->cb_color_view |= S_028C6C_MIP_LEVEL_GFX9(iview->base_mip);
4587 cb->cb_color_attrib |= S_028C74_MIP0_DEPTH(mip0_depth) |
4588 S_028C74_RESOURCE_TYPE(surf->u.gfx9.resource_type);
4589 }
4590
4591 cb->cb_color_attrib2 = S_028C68_MIP0_WIDTH(width - 1) |
4592 S_028C68_MIP0_HEIGHT(height - 1) |
4593 S_028C68_MAX_MIP(iview->image->info.levels - 1);
4594 }
4595 }
4596
4597 static unsigned
4598 radv_calc_decompress_on_z_planes(struct radv_device *device,
4599 struct radv_image_view *iview)
4600 {
4601 unsigned max_zplanes = 0;
4602
4603 assert(radv_image_is_tc_compat_htile(iview->image));
4604
4605 if (device->physical_device->rad_info.chip_class >= GFX9) {
4606 /* Default value for 32-bit depth surfaces. */
4607 max_zplanes = 4;
4608
4609 if (iview->vk_format == VK_FORMAT_D16_UNORM &&
4610 iview->image->info.samples > 1)
4611 max_zplanes = 2;
4612
4613 max_zplanes = max_zplanes + 1;
4614 } else {
4615 if (iview->vk_format == VK_FORMAT_D16_UNORM) {
4616 /* Do not enable Z plane compression for 16-bit depth
4617 * surfaces because isn't supported on GFX8. Only
4618 * 32-bit depth surfaces are supported by the hardware.
4619 * This allows to maintain shader compatibility and to
4620 * reduce the number of depth decompressions.
4621 */
4622 max_zplanes = 1;
4623 } else {
4624 if (iview->image->info.samples <= 1)
4625 max_zplanes = 5;
4626 else if (iview->image->info.samples <= 4)
4627 max_zplanes = 3;
4628 else
4629 max_zplanes = 2;
4630 }
4631 }
4632
4633 return max_zplanes;
4634 }
4635
4636 void
4637 radv_initialise_ds_surface(struct radv_device *device,
4638 struct radv_ds_buffer_info *ds,
4639 struct radv_image_view *iview)
4640 {
4641 unsigned level = iview->base_mip;
4642 unsigned format, stencil_format;
4643 uint64_t va, s_offs, z_offs;
4644 bool stencil_only = false;
4645 const struct radv_image_plane *plane = &iview->image->planes[0];
4646 const struct radeon_surf *surf = &plane->surface;
4647
4648 assert(vk_format_get_plane_count(iview->image->vk_format) == 1);
4649
4650 memset(ds, 0, sizeof(*ds));
4651 switch (iview->image->vk_format) {
4652 case VK_FORMAT_D24_UNORM_S8_UINT:
4653 case VK_FORMAT_X8_D24_UNORM_PACK32:
4654 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-24);
4655 ds->offset_scale = 2.0f;
4656 break;
4657 case VK_FORMAT_D16_UNORM:
4658 case VK_FORMAT_D16_UNORM_S8_UINT:
4659 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-16);
4660 ds->offset_scale = 4.0f;
4661 break;
4662 case VK_FORMAT_D32_SFLOAT:
4663 case VK_FORMAT_D32_SFLOAT_S8_UINT:
4664 ds->pa_su_poly_offset_db_fmt_cntl = S_028B78_POLY_OFFSET_NEG_NUM_DB_BITS(-23) |
4665 S_028B78_POLY_OFFSET_DB_IS_FLOAT_FMT(1);
4666 ds->offset_scale = 1.0f;
4667 break;
4668 case VK_FORMAT_S8_UINT:
4669 stencil_only = true;
4670 break;
4671 default:
4672 break;
4673 }
4674
4675 format = radv_translate_dbformat(iview->image->vk_format);
4676 stencil_format = surf->has_stencil ?
4677 V_028044_STENCIL_8 : V_028044_STENCIL_INVALID;
4678
4679 uint32_t max_slice = radv_surface_max_layer_count(iview) - 1;
4680 ds->db_depth_view = S_028008_SLICE_START(iview->base_layer) |
4681 S_028008_SLICE_MAX(max_slice);
4682 if (device->physical_device->rad_info.chip_class >= GFX10) {
4683 ds->db_depth_view |= S_028008_SLICE_START_HI(iview->base_layer >> 11) |
4684 S_028008_SLICE_MAX_HI(max_slice >> 11);
4685 }
4686
4687 ds->db_htile_data_base = 0;
4688 ds->db_htile_surface = 0;
4689
4690 va = radv_buffer_get_va(iview->bo) + iview->image->offset;
4691 s_offs = z_offs = va;
4692
4693 if (device->physical_device->rad_info.chip_class >= GFX9) {
4694 assert(surf->u.gfx9.surf_offset == 0);
4695 s_offs += surf->u.gfx9.stencil_offset;
4696
4697 ds->db_z_info = S_028038_FORMAT(format) |
4698 S_028038_NUM_SAMPLES(util_logbase2(iview->image->info.samples)) |
4699 S_028038_SW_MODE(surf->u.gfx9.surf.swizzle_mode) |
4700 S_028038_MAXMIP(iview->image->info.levels - 1) |
4701 S_028038_ZRANGE_PRECISION(1);
4702 ds->db_stencil_info = S_02803C_FORMAT(stencil_format) |
4703 S_02803C_SW_MODE(surf->u.gfx9.stencil.swizzle_mode);
4704
4705 if (device->physical_device->rad_info.chip_class == GFX9) {
4706 ds->db_z_info2 = S_028068_EPITCH(surf->u.gfx9.surf.epitch);
4707 ds->db_stencil_info2 = S_02806C_EPITCH(surf->u.gfx9.stencil.epitch);
4708 }
4709
4710 ds->db_depth_view |= S_028008_MIPID(level);
4711 ds->db_depth_size = S_02801C_X_MAX(iview->image->info.width - 1) |
4712 S_02801C_Y_MAX(iview->image->info.height - 1);
4713
4714 if (radv_htile_enabled(iview->image, level)) {
4715 ds->db_z_info |= S_028038_TILE_SURFACE_ENABLE(1);
4716
4717 if (radv_image_is_tc_compat_htile(iview->image)) {
4718 unsigned max_zplanes =
4719 radv_calc_decompress_on_z_planes(device, iview);
4720
4721 ds->db_z_info |= S_028038_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
4722
4723 if (device->physical_device->rad_info.chip_class >= GFX10) {
4724 ds->db_z_info |= S_028040_ITERATE_FLUSH(1);
4725 ds->db_stencil_info |= S_028044_ITERATE_FLUSH(1);
4726 } else {
4727 ds->db_z_info |= S_028038_ITERATE_FLUSH(1);
4728 ds->db_stencil_info |= S_02803C_ITERATE_FLUSH(1);
4729 }
4730 }
4731
4732 if (!surf->has_stencil)
4733 /* Use all of the htile_buffer for depth if there's no stencil. */
4734 ds->db_stencil_info |= S_02803C_TILE_STENCIL_DISABLE(1);
4735 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
4736 iview->image->htile_offset;
4737 ds->db_htile_data_base = va >> 8;
4738 ds->db_htile_surface = S_028ABC_FULL_CACHE(1) |
4739 S_028ABC_PIPE_ALIGNED(surf->u.gfx9.htile.pipe_aligned);
4740
4741 if (device->physical_device->rad_info.chip_class == GFX9) {
4742 ds->db_htile_surface |= S_028ABC_RB_ALIGNED(surf->u.gfx9.htile.rb_aligned);
4743 }
4744 }
4745 } else {
4746 const struct legacy_surf_level *level_info = &surf->u.legacy.level[level];
4747
4748 if (stencil_only)
4749 level_info = &surf->u.legacy.stencil_level[level];
4750
4751 z_offs += surf->u.legacy.level[level].offset;
4752 s_offs += surf->u.legacy.stencil_level[level].offset;
4753
4754 ds->db_depth_info = S_02803C_ADDR5_SWIZZLE_MASK(!radv_image_is_tc_compat_htile(iview->image));
4755 ds->db_z_info = S_028040_FORMAT(format) | S_028040_ZRANGE_PRECISION(1);
4756 ds->db_stencil_info = S_028044_FORMAT(stencil_format);
4757
4758 if (iview->image->info.samples > 1)
4759 ds->db_z_info |= S_028040_NUM_SAMPLES(util_logbase2(iview->image->info.samples));
4760
4761 if (device->physical_device->rad_info.chip_class >= GFX7) {
4762 struct radeon_info *info = &device->physical_device->rad_info;
4763 unsigned tiling_index = surf->u.legacy.tiling_index[level];
4764 unsigned stencil_index = surf->u.legacy.stencil_tiling_index[level];
4765 unsigned macro_index = surf->u.legacy.macro_tile_index;
4766 unsigned tile_mode = info->si_tile_mode_array[tiling_index];
4767 unsigned stencil_tile_mode = info->si_tile_mode_array[stencil_index];
4768 unsigned macro_mode = info->cik_macrotile_mode_array[macro_index];
4769
4770 if (stencil_only)
4771 tile_mode = stencil_tile_mode;
4772
4773 ds->db_depth_info |=
4774 S_02803C_ARRAY_MODE(G_009910_ARRAY_MODE(tile_mode)) |
4775 S_02803C_PIPE_CONFIG(G_009910_PIPE_CONFIG(tile_mode)) |
4776 S_02803C_BANK_WIDTH(G_009990_BANK_WIDTH(macro_mode)) |
4777 S_02803C_BANK_HEIGHT(G_009990_BANK_HEIGHT(macro_mode)) |
4778 S_02803C_MACRO_TILE_ASPECT(G_009990_MACRO_TILE_ASPECT(macro_mode)) |
4779 S_02803C_NUM_BANKS(G_009990_NUM_BANKS(macro_mode));
4780 ds->db_z_info |= S_028040_TILE_SPLIT(G_009910_TILE_SPLIT(tile_mode));
4781 ds->db_stencil_info |= S_028044_TILE_SPLIT(G_009910_TILE_SPLIT(stencil_tile_mode));
4782 } else {
4783 unsigned tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, false);
4784 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
4785 tile_mode_index = si_tile_mode_index(&iview->image->planes[0], level, true);
4786 ds->db_stencil_info |= S_028044_TILE_MODE_INDEX(tile_mode_index);
4787 if (stencil_only)
4788 ds->db_z_info |= S_028040_TILE_MODE_INDEX(tile_mode_index);
4789 }
4790
4791 ds->db_depth_size = S_028058_PITCH_TILE_MAX((level_info->nblk_x / 8) - 1) |
4792 S_028058_HEIGHT_TILE_MAX((level_info->nblk_y / 8) - 1);
4793 ds->db_depth_slice = S_02805C_SLICE_TILE_MAX((level_info->nblk_x * level_info->nblk_y) / 64 - 1);
4794
4795 if (radv_htile_enabled(iview->image, level)) {
4796 ds->db_z_info |= S_028040_TILE_SURFACE_ENABLE(1);
4797
4798 if (!surf->has_stencil &&
4799 !radv_image_is_tc_compat_htile(iview->image))
4800 /* Use all of the htile_buffer for depth if there's no stencil. */
4801 ds->db_stencil_info |= S_028044_TILE_STENCIL_DISABLE(1);
4802
4803 va = radv_buffer_get_va(iview->bo) + iview->image->offset +
4804 iview->image->htile_offset;
4805 ds->db_htile_data_base = va >> 8;
4806 ds->db_htile_surface = S_028ABC_FULL_CACHE(1);
4807
4808 if (radv_image_is_tc_compat_htile(iview->image)) {
4809 unsigned max_zplanes =
4810 radv_calc_decompress_on_z_planes(device, iview);
4811
4812 ds->db_htile_surface |= S_028ABC_TC_COMPATIBLE(1);
4813 ds->db_z_info |= S_028040_DECOMPRESS_ON_N_ZPLANES(max_zplanes);
4814 }
4815 }
4816 }
4817
4818 ds->db_z_read_base = ds->db_z_write_base = z_offs >> 8;
4819 ds->db_stencil_read_base = ds->db_stencil_write_base = s_offs >> 8;
4820 }
4821
4822 VkResult radv_CreateFramebuffer(
4823 VkDevice _device,
4824 const VkFramebufferCreateInfo* pCreateInfo,
4825 const VkAllocationCallbacks* pAllocator,
4826 VkFramebuffer* pFramebuffer)
4827 {
4828 RADV_FROM_HANDLE(radv_device, device, _device);
4829 struct radv_framebuffer *framebuffer;
4830 const VkFramebufferAttachmentsCreateInfoKHR *imageless_create_info =
4831 vk_find_struct_const(pCreateInfo->pNext,
4832 FRAMEBUFFER_ATTACHMENTS_CREATE_INFO_KHR);
4833
4834 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
4835
4836 size_t size = sizeof(*framebuffer);
4837 if (!imageless_create_info)
4838 size += sizeof(struct radv_image_view*) * pCreateInfo->attachmentCount;
4839 framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
4840 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
4841 if (framebuffer == NULL)
4842 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
4843
4844 framebuffer->attachment_count = pCreateInfo->attachmentCount;
4845 framebuffer->width = pCreateInfo->width;
4846 framebuffer->height = pCreateInfo->height;
4847 framebuffer->layers = pCreateInfo->layers;
4848 if (imageless_create_info) {
4849 for (unsigned i = 0; i < imageless_create_info->attachmentImageInfoCount; ++i) {
4850 const VkFramebufferAttachmentImageInfoKHR *attachment =
4851 imageless_create_info->pAttachmentImageInfos + i;
4852 framebuffer->width = MIN2(framebuffer->width, attachment->width);
4853 framebuffer->height = MIN2(framebuffer->height, attachment->height);
4854 framebuffer->layers = MIN2(framebuffer->layers, attachment->layerCount);
4855 }
4856 } else {
4857 for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
4858 VkImageView _iview = pCreateInfo->pAttachments[i];
4859 struct radv_image_view *iview = radv_image_view_from_handle(_iview);
4860 framebuffer->attachments[i] = iview;
4861 framebuffer->width = MIN2(framebuffer->width, iview->extent.width);
4862 framebuffer->height = MIN2(framebuffer->height, iview->extent.height);
4863 framebuffer->layers = MIN2(framebuffer->layers, radv_surface_max_layer_count(iview));
4864 }
4865 }
4866
4867 *pFramebuffer = radv_framebuffer_to_handle(framebuffer);
4868 return VK_SUCCESS;
4869 }
4870
4871 void radv_DestroyFramebuffer(
4872 VkDevice _device,
4873 VkFramebuffer _fb,
4874 const VkAllocationCallbacks* pAllocator)
4875 {
4876 RADV_FROM_HANDLE(radv_device, device, _device);
4877 RADV_FROM_HANDLE(radv_framebuffer, fb, _fb);
4878
4879 if (!fb)
4880 return;
4881 vk_free2(&device->alloc, pAllocator, fb);
4882 }
4883
4884 static unsigned radv_tex_wrap(VkSamplerAddressMode address_mode)
4885 {
4886 switch (address_mode) {
4887 case VK_SAMPLER_ADDRESS_MODE_REPEAT:
4888 return V_008F30_SQ_TEX_WRAP;
4889 case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT:
4890 return V_008F30_SQ_TEX_MIRROR;
4891 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE:
4892 return V_008F30_SQ_TEX_CLAMP_LAST_TEXEL;
4893 case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER:
4894 return V_008F30_SQ_TEX_CLAMP_BORDER;
4895 case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE:
4896 return V_008F30_SQ_TEX_MIRROR_ONCE_LAST_TEXEL;
4897 default:
4898 unreachable("illegal tex wrap mode");
4899 break;
4900 }
4901 }
4902
4903 static unsigned
4904 radv_tex_compare(VkCompareOp op)
4905 {
4906 switch (op) {
4907 case VK_COMPARE_OP_NEVER:
4908 return V_008F30_SQ_TEX_DEPTH_COMPARE_NEVER;
4909 case VK_COMPARE_OP_LESS:
4910 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESS;
4911 case VK_COMPARE_OP_EQUAL:
4912 return V_008F30_SQ_TEX_DEPTH_COMPARE_EQUAL;
4913 case VK_COMPARE_OP_LESS_OR_EQUAL:
4914 return V_008F30_SQ_TEX_DEPTH_COMPARE_LESSEQUAL;
4915 case VK_COMPARE_OP_GREATER:
4916 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATER;
4917 case VK_COMPARE_OP_NOT_EQUAL:
4918 return V_008F30_SQ_TEX_DEPTH_COMPARE_NOTEQUAL;
4919 case VK_COMPARE_OP_GREATER_OR_EQUAL:
4920 return V_008F30_SQ_TEX_DEPTH_COMPARE_GREATEREQUAL;
4921 case VK_COMPARE_OP_ALWAYS:
4922 return V_008F30_SQ_TEX_DEPTH_COMPARE_ALWAYS;
4923 default:
4924 unreachable("illegal compare mode");
4925 break;
4926 }
4927 }
4928
4929 static unsigned
4930 radv_tex_filter(VkFilter filter, unsigned max_ansio)
4931 {
4932 switch (filter) {
4933 case VK_FILTER_NEAREST:
4934 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_POINT :
4935 V_008F38_SQ_TEX_XY_FILTER_POINT);
4936 case VK_FILTER_LINEAR:
4937 return (max_ansio > 1 ? V_008F38_SQ_TEX_XY_FILTER_ANISO_BILINEAR :
4938 V_008F38_SQ_TEX_XY_FILTER_BILINEAR);
4939 case VK_FILTER_CUBIC_IMG:
4940 default:
4941 fprintf(stderr, "illegal texture filter");
4942 return 0;
4943 }
4944 }
4945
4946 static unsigned
4947 radv_tex_mipfilter(VkSamplerMipmapMode mode)
4948 {
4949 switch (mode) {
4950 case VK_SAMPLER_MIPMAP_MODE_NEAREST:
4951 return V_008F38_SQ_TEX_Z_FILTER_POINT;
4952 case VK_SAMPLER_MIPMAP_MODE_LINEAR:
4953 return V_008F38_SQ_TEX_Z_FILTER_LINEAR;
4954 default:
4955 return V_008F38_SQ_TEX_Z_FILTER_NONE;
4956 }
4957 }
4958
4959 static unsigned
4960 radv_tex_bordercolor(VkBorderColor bcolor)
4961 {
4962 switch (bcolor) {
4963 case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK:
4964 case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK:
4965 return V_008F3C_SQ_TEX_BORDER_COLOR_TRANS_BLACK;
4966 case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK:
4967 case VK_BORDER_COLOR_INT_OPAQUE_BLACK:
4968 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_BLACK;
4969 case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE:
4970 case VK_BORDER_COLOR_INT_OPAQUE_WHITE:
4971 return V_008F3C_SQ_TEX_BORDER_COLOR_OPAQUE_WHITE;
4972 default:
4973 break;
4974 }
4975 return 0;
4976 }
4977
4978 static unsigned
4979 radv_tex_aniso_filter(unsigned filter)
4980 {
4981 if (filter < 2)
4982 return 0;
4983 if (filter < 4)
4984 return 1;
4985 if (filter < 8)
4986 return 2;
4987 if (filter < 16)
4988 return 3;
4989 return 4;
4990 }
4991
4992 static unsigned
4993 radv_tex_filter_mode(VkSamplerReductionModeEXT mode)
4994 {
4995 switch (mode) {
4996 case VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE_EXT:
4997 return V_008F30_SQ_IMG_FILTER_MODE_BLEND;
4998 case VK_SAMPLER_REDUCTION_MODE_MIN_EXT:
4999 return V_008F30_SQ_IMG_FILTER_MODE_MIN;
5000 case VK_SAMPLER_REDUCTION_MODE_MAX_EXT:
5001 return V_008F30_SQ_IMG_FILTER_MODE_MAX;
5002 default:
5003 break;
5004 }
5005 return 0;
5006 }
5007
5008 static uint32_t
5009 radv_get_max_anisotropy(struct radv_device *device,
5010 const VkSamplerCreateInfo *pCreateInfo)
5011 {
5012 if (device->force_aniso >= 0)
5013 return device->force_aniso;
5014
5015 if (pCreateInfo->anisotropyEnable &&
5016 pCreateInfo->maxAnisotropy > 1.0f)
5017 return (uint32_t)pCreateInfo->maxAnisotropy;
5018
5019 return 0;
5020 }
5021
5022 static void
5023 radv_init_sampler(struct radv_device *device,
5024 struct radv_sampler *sampler,
5025 const VkSamplerCreateInfo *pCreateInfo)
5026 {
5027 uint32_t max_aniso = radv_get_max_anisotropy(device, pCreateInfo);
5028 uint32_t max_aniso_ratio = radv_tex_aniso_filter(max_aniso);
5029 bool compat_mode = device->physical_device->rad_info.chip_class == GFX8 ||
5030 device->physical_device->rad_info.chip_class == GFX9;
5031 unsigned filter_mode = V_008F30_SQ_IMG_FILTER_MODE_BLEND;
5032
5033 const struct VkSamplerReductionModeCreateInfoEXT *sampler_reduction =
5034 vk_find_struct_const(pCreateInfo->pNext,
5035 SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT);
5036 if (sampler_reduction)
5037 filter_mode = radv_tex_filter_mode(sampler_reduction->reductionMode);
5038
5039 sampler->state[0] = (S_008F30_CLAMP_X(radv_tex_wrap(pCreateInfo->addressModeU)) |
5040 S_008F30_CLAMP_Y(radv_tex_wrap(pCreateInfo->addressModeV)) |
5041 S_008F30_CLAMP_Z(radv_tex_wrap(pCreateInfo->addressModeW)) |
5042 S_008F30_MAX_ANISO_RATIO(max_aniso_ratio) |
5043 S_008F30_DEPTH_COMPARE_FUNC(radv_tex_compare(pCreateInfo->compareOp)) |
5044 S_008F30_FORCE_UNNORMALIZED(pCreateInfo->unnormalizedCoordinates ? 1 : 0) |
5045 S_008F30_ANISO_THRESHOLD(max_aniso_ratio >> 1) |
5046 S_008F30_ANISO_BIAS(max_aniso_ratio) |
5047 S_008F30_DISABLE_CUBE_WRAP(0) |
5048 S_008F30_COMPAT_MODE(compat_mode) |
5049 S_008F30_FILTER_MODE(filter_mode));
5050 sampler->state[1] = (S_008F34_MIN_LOD(S_FIXED(CLAMP(pCreateInfo->minLod, 0, 15), 8)) |
5051 S_008F34_MAX_LOD(S_FIXED(CLAMP(pCreateInfo->maxLod, 0, 15), 8)) |
5052 S_008F34_PERF_MIP(max_aniso_ratio ? max_aniso_ratio + 6 : 0));
5053 sampler->state[2] = (S_008F38_LOD_BIAS(S_FIXED(CLAMP(pCreateInfo->mipLodBias, -16, 16), 8)) |
5054 S_008F38_XY_MAG_FILTER(radv_tex_filter(pCreateInfo->magFilter, max_aniso)) |
5055 S_008F38_XY_MIN_FILTER(radv_tex_filter(pCreateInfo->minFilter, max_aniso)) |
5056 S_008F38_MIP_FILTER(radv_tex_mipfilter(pCreateInfo->mipmapMode)) |
5057 S_008F38_MIP_POINT_PRECLAMP(0));
5058 sampler->state[3] = (S_008F3C_BORDER_COLOR_PTR(0) |
5059 S_008F3C_BORDER_COLOR_TYPE(radv_tex_bordercolor(pCreateInfo->borderColor)));
5060
5061 if (device->physical_device->rad_info.chip_class >= GFX10) {
5062 sampler->state[2] |= S_008F38_ANISO_OVERRIDE_GFX10(1);
5063 } else {
5064 sampler->state[2] |=
5065 S_008F38_DISABLE_LSB_CEIL(device->physical_device->rad_info.chip_class <= GFX8) |
5066 S_008F38_FILTER_PREC_FIX(1) |
5067 S_008F38_ANISO_OVERRIDE_GFX6(device->physical_device->rad_info.chip_class >= GFX8);
5068 }
5069 }
5070
5071 VkResult radv_CreateSampler(
5072 VkDevice _device,
5073 const VkSamplerCreateInfo* pCreateInfo,
5074 const VkAllocationCallbacks* pAllocator,
5075 VkSampler* pSampler)
5076 {
5077 RADV_FROM_HANDLE(radv_device, device, _device);
5078 struct radv_sampler *sampler;
5079
5080 const struct VkSamplerYcbcrConversionInfo *ycbcr_conversion =
5081 vk_find_struct_const(pCreateInfo->pNext,
5082 SAMPLER_YCBCR_CONVERSION_INFO);
5083
5084 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO);
5085
5086 sampler = vk_alloc2(&device->alloc, pAllocator, sizeof(*sampler), 8,
5087 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
5088 if (!sampler)
5089 return vk_error(device->instance, VK_ERROR_OUT_OF_HOST_MEMORY);
5090
5091 radv_init_sampler(device, sampler, pCreateInfo);
5092
5093 sampler->ycbcr_sampler = ycbcr_conversion ? radv_sampler_ycbcr_conversion_from_handle(ycbcr_conversion->conversion): NULL;
5094 *pSampler = radv_sampler_to_handle(sampler);
5095
5096 return VK_SUCCESS;
5097 }
5098
5099 void radv_DestroySampler(
5100 VkDevice _device,
5101 VkSampler _sampler,
5102 const VkAllocationCallbacks* pAllocator)
5103 {
5104 RADV_FROM_HANDLE(radv_device, device, _device);
5105 RADV_FROM_HANDLE(radv_sampler, sampler, _sampler);
5106
5107 if (!sampler)
5108 return;
5109 vk_free2(&device->alloc, pAllocator, sampler);
5110 }
5111
5112 /* vk_icd.h does not declare this function, so we declare it here to
5113 * suppress Wmissing-prototypes.
5114 */
5115 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
5116 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion);
5117
5118 PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
5119 vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t *pSupportedVersion)
5120 {
5121 /* For the full details on loader interface versioning, see
5122 * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
5123 * What follows is a condensed summary, to help you navigate the large and
5124 * confusing official doc.
5125 *
5126 * - Loader interface v0 is incompatible with later versions. We don't
5127 * support it.
5128 *
5129 * - In loader interface v1:
5130 * - The first ICD entrypoint called by the loader is
5131 * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
5132 * entrypoint.
5133 * - The ICD must statically expose no other Vulkan symbol unless it is
5134 * linked with -Bsymbolic.
5135 * - Each dispatchable Vulkan handle created by the ICD must be
5136 * a pointer to a struct whose first member is VK_LOADER_DATA. The
5137 * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
5138 * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
5139 * vkDestroySurfaceKHR(). The ICD must be capable of working with
5140 * such loader-managed surfaces.
5141 *
5142 * - Loader interface v2 differs from v1 in:
5143 * - The first ICD entrypoint called by the loader is
5144 * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
5145 * statically expose this entrypoint.
5146 *
5147 * - Loader interface v3 differs from v2 in:
5148 * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
5149 * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
5150 * because the loader no longer does so.
5151 */
5152 *pSupportedVersion = MIN2(*pSupportedVersion, 4u);
5153 return VK_SUCCESS;
5154 }
5155
5156 VkResult radv_GetMemoryFdKHR(VkDevice _device,
5157 const VkMemoryGetFdInfoKHR *pGetFdInfo,
5158 int *pFD)
5159 {
5160 RADV_FROM_HANDLE(radv_device, device, _device);
5161 RADV_FROM_HANDLE(radv_device_memory, memory, pGetFdInfo->memory);
5162
5163 assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
5164
5165 /* At the moment, we support only the below handle types. */
5166 assert(pGetFdInfo->handleType ==
5167 VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT ||
5168 pGetFdInfo->handleType ==
5169 VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT);
5170
5171 bool ret = radv_get_memory_fd(device, memory, pFD);
5172 if (ret == false)
5173 return vk_error(device->instance, VK_ERROR_OUT_OF_DEVICE_MEMORY);
5174 return VK_SUCCESS;
5175 }
5176
5177 VkResult radv_GetMemoryFdPropertiesKHR(VkDevice _device,
5178 VkExternalMemoryHandleTypeFlagBits handleType,
5179 int fd,
5180 VkMemoryFdPropertiesKHR *pMemoryFdProperties)
5181 {
5182 RADV_FROM_HANDLE(radv_device, device, _device);
5183
5184 switch (handleType) {
5185 case VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT:
5186 pMemoryFdProperties->memoryTypeBits = (1 << RADV_MEM_TYPE_COUNT) - 1;
5187 return VK_SUCCESS;
5188
5189 default:
5190 /* The valid usage section for this function says:
5191 *
5192 * "handleType must not be one of the handle types defined as
5193 * opaque."
5194 *
5195 * So opaque handle types fall into the default "unsupported" case.
5196 */
5197 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5198 }
5199 }
5200
5201 static VkResult radv_import_opaque_fd(struct radv_device *device,
5202 int fd,
5203 uint32_t *syncobj)
5204 {
5205 uint32_t syncobj_handle = 0;
5206 int ret = device->ws->import_syncobj(device->ws, fd, &syncobj_handle);
5207 if (ret != 0)
5208 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5209
5210 if (*syncobj)
5211 device->ws->destroy_syncobj(device->ws, *syncobj);
5212
5213 *syncobj = syncobj_handle;
5214 close(fd);
5215
5216 return VK_SUCCESS;
5217 }
5218
5219 static VkResult radv_import_sync_fd(struct radv_device *device,
5220 int fd,
5221 uint32_t *syncobj)
5222 {
5223 /* If we create a syncobj we do it locally so that if we have an error, we don't
5224 * leave a syncobj in an undetermined state in the fence. */
5225 uint32_t syncobj_handle = *syncobj;
5226 if (!syncobj_handle) {
5227 int ret = device->ws->create_syncobj(device->ws, &syncobj_handle);
5228 if (ret) {
5229 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5230 }
5231 }
5232
5233 if (fd == -1) {
5234 device->ws->signal_syncobj(device->ws, syncobj_handle);
5235 } else {
5236 int ret = device->ws->import_syncobj_from_sync_file(device->ws, syncobj_handle, fd);
5237 if (ret != 0)
5238 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5239 }
5240
5241 *syncobj = syncobj_handle;
5242 if (fd != -1)
5243 close(fd);
5244
5245 return VK_SUCCESS;
5246 }
5247
5248 VkResult radv_ImportSemaphoreFdKHR(VkDevice _device,
5249 const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo)
5250 {
5251 RADV_FROM_HANDLE(radv_device, device, _device);
5252 RADV_FROM_HANDLE(radv_semaphore, sem, pImportSemaphoreFdInfo->semaphore);
5253 uint32_t *syncobj_dst = NULL;
5254
5255 if (pImportSemaphoreFdInfo->flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT) {
5256 syncobj_dst = &sem->temp_syncobj;
5257 } else {
5258 syncobj_dst = &sem->syncobj;
5259 }
5260
5261 switch(pImportSemaphoreFdInfo->handleType) {
5262 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
5263 return radv_import_opaque_fd(device, pImportSemaphoreFdInfo->fd, syncobj_dst);
5264 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
5265 return radv_import_sync_fd(device, pImportSemaphoreFdInfo->fd, syncobj_dst);
5266 default:
5267 unreachable("Unhandled semaphore handle type");
5268 }
5269 }
5270
5271 VkResult radv_GetSemaphoreFdKHR(VkDevice _device,
5272 const VkSemaphoreGetFdInfoKHR *pGetFdInfo,
5273 int *pFd)
5274 {
5275 RADV_FROM_HANDLE(radv_device, device, _device);
5276 RADV_FROM_HANDLE(radv_semaphore, sem, pGetFdInfo->semaphore);
5277 int ret;
5278 uint32_t syncobj_handle;
5279
5280 if (sem->temp_syncobj)
5281 syncobj_handle = sem->temp_syncobj;
5282 else
5283 syncobj_handle = sem->syncobj;
5284
5285 switch(pGetFdInfo->handleType) {
5286 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT:
5287 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
5288 break;
5289 case VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT:
5290 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
5291 if (!ret) {
5292 if (sem->temp_syncobj) {
5293 close (sem->temp_syncobj);
5294 sem->temp_syncobj = 0;
5295 } else {
5296 device->ws->reset_syncobj(device->ws, syncobj_handle);
5297 }
5298 }
5299 break;
5300 default:
5301 unreachable("Unhandled semaphore handle type");
5302 }
5303
5304 if (ret)
5305 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5306 return VK_SUCCESS;
5307 }
5308
5309 void radv_GetPhysicalDeviceExternalSemaphoreProperties(
5310 VkPhysicalDevice physicalDevice,
5311 const VkPhysicalDeviceExternalSemaphoreInfo *pExternalSemaphoreInfo,
5312 VkExternalSemaphoreProperties *pExternalSemaphoreProperties)
5313 {
5314 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
5315
5316 /* Require has_syncobj_wait_for_submit for the syncobj signal ioctl introduced at virtually the same time */
5317 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
5318 (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT ||
5319 pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT)) {
5320 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
5321 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
5322 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
5323 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
5324 } else if (pExternalSemaphoreInfo->handleType == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT) {
5325 pExternalSemaphoreProperties->exportFromImportedHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
5326 pExternalSemaphoreProperties->compatibleHandleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_OPAQUE_FD_BIT;
5327 pExternalSemaphoreProperties->externalSemaphoreFeatures = VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT |
5328 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
5329 } else {
5330 pExternalSemaphoreProperties->exportFromImportedHandleTypes = 0;
5331 pExternalSemaphoreProperties->compatibleHandleTypes = 0;
5332 pExternalSemaphoreProperties->externalSemaphoreFeatures = 0;
5333 }
5334 }
5335
5336 VkResult radv_ImportFenceFdKHR(VkDevice _device,
5337 const VkImportFenceFdInfoKHR *pImportFenceFdInfo)
5338 {
5339 RADV_FROM_HANDLE(radv_device, device, _device);
5340 RADV_FROM_HANDLE(radv_fence, fence, pImportFenceFdInfo->fence);
5341 uint32_t *syncobj_dst = NULL;
5342
5343
5344 if (pImportFenceFdInfo->flags & VK_FENCE_IMPORT_TEMPORARY_BIT) {
5345 syncobj_dst = &fence->temp_syncobj;
5346 } else {
5347 syncobj_dst = &fence->syncobj;
5348 }
5349
5350 switch(pImportFenceFdInfo->handleType) {
5351 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
5352 return radv_import_opaque_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
5353 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
5354 return radv_import_sync_fd(device, pImportFenceFdInfo->fd, syncobj_dst);
5355 default:
5356 unreachable("Unhandled fence handle type");
5357 }
5358 }
5359
5360 VkResult radv_GetFenceFdKHR(VkDevice _device,
5361 const VkFenceGetFdInfoKHR *pGetFdInfo,
5362 int *pFd)
5363 {
5364 RADV_FROM_HANDLE(radv_device, device, _device);
5365 RADV_FROM_HANDLE(radv_fence, fence, pGetFdInfo->fence);
5366 int ret;
5367 uint32_t syncobj_handle;
5368
5369 if (fence->temp_syncobj)
5370 syncobj_handle = fence->temp_syncobj;
5371 else
5372 syncobj_handle = fence->syncobj;
5373
5374 switch(pGetFdInfo->handleType) {
5375 case VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT:
5376 ret = device->ws->export_syncobj(device->ws, syncobj_handle, pFd);
5377 break;
5378 case VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT:
5379 ret = device->ws->export_syncobj_to_sync_file(device->ws, syncobj_handle, pFd);
5380 if (!ret) {
5381 if (fence->temp_syncobj) {
5382 close (fence->temp_syncobj);
5383 fence->temp_syncobj = 0;
5384 } else {
5385 device->ws->reset_syncobj(device->ws, syncobj_handle);
5386 }
5387 }
5388 break;
5389 default:
5390 unreachable("Unhandled fence handle type");
5391 }
5392
5393 if (ret)
5394 return vk_error(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE);
5395 return VK_SUCCESS;
5396 }
5397
5398 void radv_GetPhysicalDeviceExternalFenceProperties(
5399 VkPhysicalDevice physicalDevice,
5400 const VkPhysicalDeviceExternalFenceInfo *pExternalFenceInfo,
5401 VkExternalFenceProperties *pExternalFenceProperties)
5402 {
5403 RADV_FROM_HANDLE(radv_physical_device, pdevice, physicalDevice);
5404
5405 if (pdevice->rad_info.has_syncobj_wait_for_submit &&
5406 (pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT ||
5407 pExternalFenceInfo->handleType == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT)) {
5408 pExternalFenceProperties->exportFromImportedHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
5409 pExternalFenceProperties->compatibleHandleTypes = VK_EXTERNAL_FENCE_HANDLE_TYPE_OPAQUE_FD_BIT | VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT;
5410 pExternalFenceProperties->externalFenceFeatures = VK_EXTERNAL_FENCE_FEATURE_EXPORTABLE_BIT |
5411 VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT;
5412 } else {
5413 pExternalFenceProperties->exportFromImportedHandleTypes = 0;
5414 pExternalFenceProperties->compatibleHandleTypes = 0;
5415 pExternalFenceProperties->externalFenceFeatures = 0;
5416 }
5417 }
5418
5419 VkResult
5420 radv_CreateDebugReportCallbackEXT(VkInstance _instance,
5421 const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
5422 const VkAllocationCallbacks* pAllocator,
5423 VkDebugReportCallbackEXT* pCallback)
5424 {
5425 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5426 return vk_create_debug_report_callback(&instance->debug_report_callbacks,
5427 pCreateInfo, pAllocator, &instance->alloc,
5428 pCallback);
5429 }
5430
5431 void
5432 radv_DestroyDebugReportCallbackEXT(VkInstance _instance,
5433 VkDebugReportCallbackEXT _callback,
5434 const VkAllocationCallbacks* pAllocator)
5435 {
5436 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5437 vk_destroy_debug_report_callback(&instance->debug_report_callbacks,
5438 _callback, pAllocator, &instance->alloc);
5439 }
5440
5441 void
5442 radv_DebugReportMessageEXT(VkInstance _instance,
5443 VkDebugReportFlagsEXT flags,
5444 VkDebugReportObjectTypeEXT objectType,
5445 uint64_t object,
5446 size_t location,
5447 int32_t messageCode,
5448 const char* pLayerPrefix,
5449 const char* pMessage)
5450 {
5451 RADV_FROM_HANDLE(radv_instance, instance, _instance);
5452 vk_debug_report(&instance->debug_report_callbacks, flags, objectType,
5453 object, location, messageCode, pLayerPrefix, pMessage);
5454 }
5455
5456 void
5457 radv_GetDeviceGroupPeerMemoryFeatures(
5458 VkDevice device,
5459 uint32_t heapIndex,
5460 uint32_t localDeviceIndex,
5461 uint32_t remoteDeviceIndex,
5462 VkPeerMemoryFeatureFlags* pPeerMemoryFeatures)
5463 {
5464 assert(localDeviceIndex == remoteDeviceIndex);
5465
5466 *pPeerMemoryFeatures = VK_PEER_MEMORY_FEATURE_COPY_SRC_BIT |
5467 VK_PEER_MEMORY_FEATURE_COPY_DST_BIT |
5468 VK_PEER_MEMORY_FEATURE_GENERIC_SRC_BIT |
5469 VK_PEER_MEMORY_FEATURE_GENERIC_DST_BIT;
5470 }
5471
5472 static const VkTimeDomainEXT radv_time_domains[] = {
5473 VK_TIME_DOMAIN_DEVICE_EXT,
5474 VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT,
5475 VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT,
5476 };
5477
5478 VkResult radv_GetPhysicalDeviceCalibrateableTimeDomainsEXT(
5479 VkPhysicalDevice physicalDevice,
5480 uint32_t *pTimeDomainCount,
5481 VkTimeDomainEXT *pTimeDomains)
5482 {
5483 int d;
5484 VK_OUTARRAY_MAKE(out, pTimeDomains, pTimeDomainCount);
5485
5486 for (d = 0; d < ARRAY_SIZE(radv_time_domains); d++) {
5487 vk_outarray_append(&out, i) {
5488 *i = radv_time_domains[d];
5489 }
5490 }
5491
5492 return vk_outarray_status(&out);
5493 }
5494
5495 static uint64_t
5496 radv_clock_gettime(clockid_t clock_id)
5497 {
5498 struct timespec current;
5499 int ret;
5500
5501 ret = clock_gettime(clock_id, &current);
5502 if (ret < 0 && clock_id == CLOCK_MONOTONIC_RAW)
5503 ret = clock_gettime(CLOCK_MONOTONIC, &current);
5504 if (ret < 0)
5505 return 0;
5506
5507 return (uint64_t) current.tv_sec * 1000000000ULL + current.tv_nsec;
5508 }
5509
5510 VkResult radv_GetCalibratedTimestampsEXT(
5511 VkDevice _device,
5512 uint32_t timestampCount,
5513 const VkCalibratedTimestampInfoEXT *pTimestampInfos,
5514 uint64_t *pTimestamps,
5515 uint64_t *pMaxDeviation)
5516 {
5517 RADV_FROM_HANDLE(radv_device, device, _device);
5518 uint32_t clock_crystal_freq = device->physical_device->rad_info.clock_crystal_freq;
5519 int d;
5520 uint64_t begin, end;
5521 uint64_t max_clock_period = 0;
5522
5523 begin = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
5524
5525 for (d = 0; d < timestampCount; d++) {
5526 switch (pTimestampInfos[d].timeDomain) {
5527 case VK_TIME_DOMAIN_DEVICE_EXT:
5528 pTimestamps[d] = device->ws->query_value(device->ws,
5529 RADEON_TIMESTAMP);
5530 uint64_t device_period = DIV_ROUND_UP(1000000, clock_crystal_freq);
5531 max_clock_period = MAX2(max_clock_period, device_period);
5532 break;
5533 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_EXT:
5534 pTimestamps[d] = radv_clock_gettime(CLOCK_MONOTONIC);
5535 max_clock_period = MAX2(max_clock_period, 1);
5536 break;
5537
5538 case VK_TIME_DOMAIN_CLOCK_MONOTONIC_RAW_EXT:
5539 pTimestamps[d] = begin;
5540 break;
5541 default:
5542 pTimestamps[d] = 0;
5543 break;
5544 }
5545 }
5546
5547 end = radv_clock_gettime(CLOCK_MONOTONIC_RAW);
5548
5549 /*
5550 * The maximum deviation is the sum of the interval over which we
5551 * perform the sampling and the maximum period of any sampled
5552 * clock. That's because the maximum skew between any two sampled
5553 * clock edges is when the sampled clock with the largest period is
5554 * sampled at the end of that period but right at the beginning of the
5555 * sampling interval and some other clock is sampled right at the
5556 * begining of its sampling period and right at the end of the
5557 * sampling interval. Let's assume the GPU has the longest clock
5558 * period and that the application is sampling GPU and monotonic:
5559 *
5560 * s e
5561 * w x y z 0 1 2 3 4 5 6 7 8 9 a b c d e f
5562 * Raw -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
5563 *
5564 * g
5565 * 0 1 2 3
5566 * GPU -----_____-----_____-----_____-----_____
5567 *
5568 * m
5569 * x y z 0 1 2 3 4 5 6 7 8 9 a b c
5570 * Monotonic -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-
5571 *
5572 * Interval <----------------->
5573 * Deviation <-------------------------->
5574 *
5575 * s = read(raw) 2
5576 * g = read(GPU) 1
5577 * m = read(monotonic) 2
5578 * e = read(raw) b
5579 *
5580 * We round the sample interval up by one tick to cover sampling error
5581 * in the interval clock
5582 */
5583
5584 uint64_t sample_interval = end - begin + 1;
5585
5586 *pMaxDeviation = sample_interval + max_clock_period;
5587
5588 return VK_SUCCESS;
5589 }
5590
5591 void radv_GetPhysicalDeviceMultisamplePropertiesEXT(
5592 VkPhysicalDevice physicalDevice,
5593 VkSampleCountFlagBits samples,
5594 VkMultisamplePropertiesEXT* pMultisampleProperties)
5595 {
5596 if (samples & (VK_SAMPLE_COUNT_2_BIT |
5597 VK_SAMPLE_COUNT_4_BIT |
5598 VK_SAMPLE_COUNT_8_BIT)) {
5599 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 2, 2 };
5600 } else {
5601 pMultisampleProperties->maxSampleLocationGridSize = (VkExtent2D){ 0, 0 };
5602 }
5603 }