Debian Codegraph @

src/gpu/vk/VulkanUtilsPriv.cpp

raw
1 /*
2 * Copyright 2023 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/gpu/vk/VulkanUtilsPriv.h"
9
10 #include "include/gpu/vk/VulkanBackendContext.h"
11 #include "include/private/base/SkAssert.h"
12 #include "include/private/base/SkDebug.h"
13 #include "include/private/base/SkTFitsIn.h"
14 #include "include/private/base/SkTo.h"
15 #include "src/gpu/vk/VulkanInterface.h"
16
17 #include <algorithm>
18 #include <vector>
19
20 namespace skgpu {
21
22 /**
23 * Define a macro that both ganesh and graphite can use to make simple calls into Vulkan so we can
24 * share more code between them.
25 */
26 #define SHARED_GR_VULKAN_CALL(IFACE, X) (IFACE)->fFunctions.f##X
27
28 /**
29 * Parse the driver version number in VkPhysicalDeviceProperties::driverVersion according to the
30 * driver ID.
31 */
32 DriverVersion ParseVulkanDriverVersion(VkDriverId driverId, uint32_t driverVersion) {
33 // Most drivers follow the VK_MAKE_API_VERSION convention. The exceptions are documented in the
34 // switch cases below.
35 switch (driverId) {
36 case VK_DRIVER_ID_INTEL_PROPRIETARY_WINDOWS:
37 // Windows Intel driver versions are built in the following format:
38 //
39 // Major (18 bits) | Minor (14 bits)
40 //
41 return DriverVersion(driverVersion >> 14, driverVersion & 0x3FFF);
42 case VK_DRIVER_ID_NVIDIA_PROPRIETARY:
43 // Nvidia proprietary driver version is in the following format:
44 //
45 // Major (10 bits) | Minor (8 bits) | SubMinor (8 bits) | Patch (6 bits)
46 //
47 return DriverVersion(driverVersion >> 22, driverVersion >> 14 & 0xFF);
48 case VK_DRIVER_ID_QUALCOMM_PROPRIETARY:
49 // Qualcomm proprietary driver version has changed over time. In the new format, it's
50 // almost following the VK_MAKE_API_VERSION convention, except the top bit is set. With
51 // VK_API_VERSION_MAJOR, this bit is masked out (corresponding to a value of 512), which
52 // is typically expected to be visible in the version, i.e. the version is 512.NNNN. The
53 // old format is unknown, and is considered 0.NNNN.
54 if ((driverVersion & 0x80000000) != 0) {
55 return DriverVersion(VK_API_VERSION_MAJOR(driverVersion) | 512,
56 VK_API_VERSION_MINOR(driverVersion));
57 }
58
59 return DriverVersion(0, driverVersion);
60 case VK_DRIVER_ID_MOLTENVK:
61 // MoltenVK driver version is in the following format:
62 //
63 // Major * 10000 + Minor * 100 + patch
64 //
65 return DriverVersion(driverVersion / 10000, (driverVersion / 100) % 100);
66 default:
67 return DriverVersion(VK_API_VERSION_MAJOR(driverVersion),
68 VK_API_VERSION_MINOR(driverVersion));
69 }
70 }
71
72 #ifdef SK_BUILD_FOR_ANDROID
73
74 /**
75 * Shared Vulkan AHardwareBuffer utility functions between graphite and ganesh
76 */
77 void GetYcbcrConversionInfoFromFormatProps(
78 VulkanYcbcrConversionInfo* outConversionInfo,
79 const VkAndroidHardwareBufferFormatPropertiesANDROID& formatProps) {
80 VkFilter chromaFilter;
81 if (VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT &
82 formatProps.formatFeatures) {
83 chromaFilter = VK_FILTER_LINEAR;
84 } else {
85 chromaFilter = VK_FILTER_NEAREST;
86 }
87
88 *outConversionInfo = VulkanYcbcrConversionInfo(formatProps.externalFormat,
89 formatProps.suggestedYcbcrModel,
90 formatProps.suggestedYcbcrRange,
91 formatProps.suggestedXChromaOffset,
92 formatProps.suggestedYChromaOffset,
93 chromaFilter,
94 /*forceExplicitReconstruction=*/VK_FALSE,
95 formatProps.samplerYcbcrConversionComponents,
96 formatProps.formatFeatures);
97 }
98
99 bool GetAHardwareBufferProperties(
100 VkAndroidHardwareBufferFormatPropertiesANDROID* outHwbFormatProps,
101 VkAndroidHardwareBufferPropertiesANDROID* outHwbProps,
102 const skgpu::VulkanInterface* interface,
103 const AHardwareBuffer* hwBuffer,
104 VkDevice device) {
105 outHwbFormatProps->sType =
106 VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
107 outHwbFormatProps->pNext = nullptr;
108
109 outHwbProps->sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
110 outHwbProps->pNext = outHwbFormatProps;
111
112 VkResult result =
113 SHARED_GR_VULKAN_CALL(interface,
114 GetAndroidHardwareBufferProperties(device,
115 hwBuffer,
116 outHwbProps));
117 if (result != VK_SUCCESS) {
118 // The spec suggests VK_ERROR_OUT_OF_HOST_MEMORY and VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR
119 // are the only failure codes, but some platforms may report others, such as
120 // VK_ERROR_FORMAT_NOT_SUPPORTED (-11).
121 SkDebugf("Failed to get AndroidHardwareBufferProperties (result:%d)", result);
122 #if __ANDROID_API__ >= 26
123 AHardwareBuffer_Desc hwbDesc;
124 AHardwareBuffer_describe(hwBuffer, &hwbDesc);
125 SkDebugf("^ %" PRIu32 "x%" PRIu32 " AHB -- format:%" PRIu32 ", usage:%" PRIu64
126 ", layers:%" PRIu32,
127 hwbDesc.width,
128 hwbDesc.height,
129 hwbDesc.format,
130 hwbDesc.usage,
131 hwbDesc.layers);
132 #endif
133 return false;
134 }
135 return true;
136 }
137
138 bool AllocateAndBindImageMemory(skgpu::VulkanAlloc* outVulkanAlloc,
139 VkImage image,
140 const VkPhysicalDeviceMemoryProperties2& phyDevMemProps,
141 const VkAndroidHardwareBufferPropertiesANDROID& hwbProps,
142 AHardwareBuffer* hardwareBuffer,
143 const skgpu::VulkanInterface* interface,
144 VkDevice device) {
145 VkResult result;
146 uint32_t typeIndex = 0;
147 bool foundHeap = false;
148 uint32_t memTypeCnt = phyDevMemProps.memoryProperties.memoryTypeCount;
149 for (uint32_t i = 0; i < memTypeCnt && !foundHeap; ++i) {
150 if (hwbProps.memoryTypeBits & (1 << i)) {
151 const VkPhysicalDeviceMemoryProperties& pdmp = phyDevMemProps.memoryProperties;
152 uint32_t supportedFlags = pdmp.memoryTypes[i].propertyFlags &
153 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
154 if (supportedFlags == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
155 typeIndex = i;
156 foundHeap = true;
157 }
158 }
159 }
160
161 /**
162 * Fallback to use any available memory type for AHB.
163 *
164 * For external memory import, compatible memory types are decided by the Vulkan driver since
165 * the memory has been allocated externally. There are usually special requirements against
166 * external memory. e.g. AHB allocated with CPU R/W often usage bits is only importable for
167 * non-device-local heap on some AMD systems.
168 */
169 if (!foundHeap && hwbProps.memoryTypeBits) {
170 typeIndex = ffs(hwbProps.memoryTypeBits) - 1;
171 foundHeap = true;
172 }
173 if (!foundHeap) {
174 return false;
175 }
176
177 VkImportAndroidHardwareBufferInfoANDROID hwbImportInfo;
178 hwbImportInfo.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID;
179 hwbImportInfo.pNext = nullptr;
180 hwbImportInfo.buffer = hardwareBuffer;
181
182 VkMemoryDedicatedAllocateInfo dedicatedAllocInfo;
183 dedicatedAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
184 dedicatedAllocInfo.pNext = &hwbImportInfo;
185 dedicatedAllocInfo.image = image;
186 dedicatedAllocInfo.buffer = VK_NULL_HANDLE;
187
188 VkMemoryAllocateInfo allocInfo = {
189 VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, // sType
190 &dedicatedAllocInfo, // pNext
191 hwbProps.allocationSize, // allocationSize
192 typeIndex, // memoryTypeIndex
193 };
194
195 VkDeviceMemory memory;
196 result = SHARED_GR_VULKAN_CALL(interface,
197 AllocateMemory(device, &allocInfo, nullptr, &memory));
198 if (result != VK_SUCCESS) {
199 return false;
200 }
201
202 VkBindImageMemoryInfo bindImageInfo;
203 bindImageInfo.sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
204 bindImageInfo.pNext = nullptr;
205 bindImageInfo.image = image;
206 bindImageInfo.memory = memory;
207 bindImageInfo.memoryOffset = 0;
208
209 result = SHARED_GR_VULKAN_CALL(interface, BindImageMemory2(device, 1, &bindImageInfo));
210 if (result != VK_SUCCESS) {
211 SHARED_GR_VULKAN_CALL(interface, FreeMemory(device, memory, nullptr));
212 return false;
213 }
214
215 outVulkanAlloc->fMemory = memory;
216 outVulkanAlloc->fOffset = 0;
217 outVulkanAlloc->fSize = hwbProps.allocationSize;
218 outVulkanAlloc->fFlags = 0;
219 outVulkanAlloc->fBackendMemory = 0;
220 return true;
221 }
222
223 #endif // SK_BUILD_FOR_ANDROID
224
225 // Note: since this is called from Vulkan result-checking functions, any Vk calls this function
226 // makes must NOT be checked with those same functions to avoid infinite recursion.
227 void InvokeDeviceLostCallback(const skgpu::VulkanInterface* vulkanInterface,
228 VkDevice vkDevice,
229 skgpu::VulkanDeviceLostContext deviceLostContext,
230 skgpu::VulkanDeviceLostProc deviceLostProc,
231 bool supportsDeviceFaultInfoExtension) {
232 if (!deviceLostProc) {
233 return;
234 }
235
236 std::vector<VkDeviceFaultAddressInfoEXT> addressInfos = {};
237 std::vector<VkDeviceFaultVendorInfoEXT> vendorInfos = {};
238 std::vector<std::byte> vendorBinaryData = {};
239
240 if (!supportsDeviceFaultInfoExtension) {
241 deviceLostProc(deviceLostContext,
242 "No details: VK_EXT_device_fault not available/enabled.",
243 addressInfos,
244 vendorInfos,
245 vendorBinaryData);
246 return;
247 }
248
249 // Query counts
250 VkDeviceFaultCountsEXT faultCounts = {};
251 faultCounts.sType = VK_STRUCTURE_TYPE_DEVICE_FAULT_COUNTS_EXT;
252 VkResult result = SHARED_GR_VULKAN_CALL(vulkanInterface,
253 GetDeviceFaultInfo(vkDevice, &faultCounts, NULL));
254 if (result != VK_SUCCESS) {
255 deviceLostProc(
256 deviceLostContext,
257 "No details: VK_EXT_device_fault error counting failed: " + std::to_string(result),
258 addressInfos,
259 vendorInfos,
260 vendorBinaryData);
261 return;
262 }
263
264 // Prepare storage
265 addressInfos.resize(faultCounts.addressInfoCount);
266 vendorInfos.resize(faultCounts.vendorInfoCount);
267 vendorBinaryData.resize(faultCounts.vendorBinarySize);
268
269 // Query fault info
270 VkDeviceFaultInfoEXT faultInfo = {};
271 faultInfo.sType = VK_STRUCTURE_TYPE_DEVICE_FAULT_INFO_EXT;
272 faultInfo.pAddressInfos = addressInfos.data();
273 faultInfo.pVendorInfos = vendorInfos.data();
274 faultInfo.pVendorBinaryData =
275 faultCounts.vendorBinarySize > 0 ? vendorBinaryData.data() : nullptr;
276 result = SHARED_GR_VULKAN_CALL(vulkanInterface,
277 GetDeviceFaultInfo(vkDevice, &faultCounts, &faultInfo));
278 if (result != VK_SUCCESS) {
279 deviceLostProc(
280 deviceLostContext,
281 "No details: VK_EXT_device_fault info dumping failed: " + std::to_string(result),
282 addressInfos,
283 vendorInfos,
284 vendorBinaryData);
285 return;
286 }
287
288 deviceLostProc(deviceLostContext,
289 std::string(faultInfo.description),
290 addressInfos,
291 vendorInfos,
292 vendorBinaryData);
293 }
294
295 sk_sp<skgpu::VulkanInterface> MakeInterface(const skgpu::VulkanBackendContext& context,
296 const skgpu::VulkanExtensions* extOverride,
297 uint32_t* instanceVersionOut,
298 uint32_t* physDevVersionOut) {
299 if (!extOverride) {
300 extOverride = context.fVkExtensions;
301 }
302 SkASSERT(extOverride);
303 PFN_vkEnumerateInstanceVersion localEnumerateInstanceVersion =
304 reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
305 context.fGetProc("vkEnumerateInstanceVersion", VK_NULL_HANDLE, VK_NULL_HANDLE));
306 uint32_t instanceVersion = 0;
307 // Vulkan 1.1 is required, so vkEnumerateInstanceVersion should always be available.
308 SkASSERT(localEnumerateInstanceVersion != nullptr);
309 VkResult err = localEnumerateInstanceVersion(&instanceVersion);
310 if (err) {
311 return nullptr;
312 }
313
314 PFN_vkGetPhysicalDeviceProperties localGetPhysicalDeviceProperties =
315 reinterpret_cast<PFN_vkGetPhysicalDeviceProperties>(context.fGetProc(
316 "vkGetPhysicalDeviceProperties", context.fInstance, VK_NULL_HANDLE));
317 SkASSERT(localGetPhysicalDeviceProperties != nullptr);
318
319 VkPhysicalDeviceProperties physDeviceProperties;
320 localGetPhysicalDeviceProperties(context.fPhysicalDevice, &physDeviceProperties);
321 uint32_t physDevVersion = physDeviceProperties.apiVersion;
322
323 uint32_t apiVersion = context.fMaxAPIVersion ? context.fMaxAPIVersion : instanceVersion;
324
325 instanceVersion = std::min(instanceVersion, apiVersion);
326 physDevVersion = std::min(physDevVersion, apiVersion);
327
328 if (instanceVersion < VK_API_VERSION_1_1 || physDevVersion < VK_API_VERSION_1_1) {
329 SK_ABORT("Vulkan 1.1 is required but not available. "
330 "Instance version: %#08X, Device version: %#08X",
331 instanceVersion, physDevVersion);
332 }
333
334 sk_sp<skgpu::VulkanInterface> interface(new skgpu::VulkanInterface(context.fGetProc,
335 context.fInstance,
336 context.fDevice,
337 instanceVersion,
338 physDevVersion,
339 extOverride));
340 if (!interface->validate(instanceVersion, physDevVersion, extOverride)) {
341 return nullptr;
342 }
343 if (physDevVersionOut) {
344 *physDevVersionOut = physDevVersion;
345 }
346 if (instanceVersionOut) {
347 *instanceVersionOut = instanceVersion;
348 }
349 return interface;
350 }
351
352 VulkanYcbcrConversionInfo::VulkanYcbcrConversionInfo(VkFormat format,
353 uint64_t externalFormat,
354 VkSamplerYcbcrModelConversion ycbcrModel,
355 VkSamplerYcbcrRange ycbcrRange,
356 VkChromaLocation xChromaOffset,
357 VkChromaLocation yChromaOffset,
358 VkFilter chromaFilter,
359 VkBool32 forceExplicitReconstruction,
360 VkComponentMapping components,
361 VkFormatFeatureFlags formatFeatures)
362 : fFormat(format)
363 , fExternalFormat(externalFormat)
364 , fYcbcrModel(ycbcrModel)
365 , fYcbcrRange(ycbcrRange)
366 , fXChromaOffset(xChromaOffset)
367 , fYChromaOffset(yChromaOffset)
368 , fChromaFilter(chromaFilter)
369 , fForceExplicitReconstruction(forceExplicitReconstruction)
370 , fComponents(components) {
371 #ifdef SK_DEBUG
372 // Graphite can recreate these two flags so they don't reflect actual settings
373 constexpr VkFormatFeatureFlags kIgnoredFlags =
374 VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT |
375 VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
376
377 // Format feature flags are only representative of an external format's capabilities, so
378 // skip these checks in the case of using a known format or if the featureFlags were clearly
379 // not filled in.
380 if (fFormat == VK_FORMAT_UNDEFINED && (formatFeatures & ~kIgnoredFlags)) {
381 if (fXChromaOffset == VK_CHROMA_LOCATION_MIDPOINT ||
382 fYChromaOffset == VK_CHROMA_LOCATION_MIDPOINT) {
383 SkASSERT(formatFeatures & VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT);
384 }
385 if (fXChromaOffset == VK_CHROMA_LOCATION_COSITED_EVEN ||
386 fYChromaOffset == VK_CHROMA_LOCATION_COSITED_EVEN) {
387 SkASSERT(formatFeatures & VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT);
388 }
389 if (fChromaFilter == VK_FILTER_LINEAR) {
390 SkASSERT(formatFeatures &
391 VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT);
392 }
393 if (fForceExplicitReconstruction) {
394 SkASSERT(formatFeatures &
395 VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT);
396 }
397 }
398 #endif
399 fSamplerFilterMustMatchChromaFilter = !SkToBool(
400 formatFeatures &
401 VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT);
402 fSupportsLinearFilter = SkToBool(formatFeatures &
403 VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT);
404 if (fSamplerFilterMustMatchChromaFilter && !fSupportsLinearFilter) {
405 // Because we don't have separate reconstruction filter, the min, mag and filter must
406 // all match. However, we also don't support linear sampling so the min/mag filter have to
407 // be nearest. Therefore, we force the chroma filter to be nearest regardless of support for
408 // the feature VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT.
409 fChromaFilter = VK_FILTER_NEAREST;
410 }
411 }
412
413
414 void VulkanYcbcrConversionInfo::toVkSamplerYcbcrConversionCreateInfo(
415 VkSamplerYcbcrConversionCreateInfo* outInfo,
416 std::optional<VkFilter>* requiredSamplerFilter) const {
417 outInfo->sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO;
418 outInfo->pNext = nullptr;
419 outInfo->format = fFormat;
420 outInfo->ycbcrModel = fYcbcrModel;
421 outInfo->ycbcrRange = fYcbcrRange;
422 outInfo->components = fComponents;
423 outInfo->xChromaOffset = fXChromaOffset;
424 outInfo->yChromaOffset = fYChromaOffset;
425 outInfo->chromaFilter = fChromaFilter;
426 outInfo->forceExplicitReconstruction = fForceExplicitReconstruction;
427
428 if (fSamplerFilterMustMatchChromaFilter) {
429 *requiredSamplerFilter = fChromaFilter;
430 } else if (!fSupportsLinearFilter) {
431 *requiredSamplerFilter = VK_FILTER_NEAREST;
432 }
433 }
434
435 } // namespace skgpu