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