blob: 6571d92aeafaa97e76dfb04dfb93236c24bfa9f0 [file] [log] [blame]
Derek Sollenberger0e3cba32016-11-09 11:58:36 -05001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "VulkanManager.h"
18
Alec Mouri6db59a62019-08-02 17:05:26 -070019#include <EGL/egl.h>
20#include <EGL/eglext.h>
Stan Ilievaaa9e832019-09-17 14:07:23 -040021#include <android/sync.h>
Alec Mouri219997a2023-05-23 17:25:19 +000022#include <gui/TraceUtils.h>
Nolan Scobie572d8012024-08-30 13:43:34 -040023#include <include/gpu/ganesh/GrBackendSemaphore.h>
24#include <include/gpu/ganesh/GrBackendSurface.h>
25#include <include/gpu/ganesh/GrDirectContext.h>
26#include <include/gpu/ganesh/GrTypes.h>
Alec Mouri219997a2023-05-23 17:25:19 +000027#include <include/gpu/ganesh/SkSurfaceGanesh.h>
Kevin Lubick913e9a42024-03-07 13:14:46 +000028#include <include/gpu/ganesh/vk/GrVkBackendSemaphore.h>
Brian Osman734d8102023-08-29 18:07:56 +000029#include <include/gpu/ganesh/vk/GrVkBackendSurface.h>
Kevin Lubickf6b21952023-10-13 13:12:17 +000030#include <include/gpu/ganesh/vk/GrVkDirectContext.h>
Nolan Scobie572d8012024-08-30 13:43:34 -040031#include <include/gpu/ganesh/vk/GrVkTypes.h>
Kaylee Lubickab1f35f2024-06-20 17:19:31 +000032#include <include/gpu/vk/VulkanBackendContext.h>
Jagadeesh Pakaravoorb624af32020-05-01 00:01:40 +000033#include <ui/FatVector.h>
Stan Iliev305e13a2018-11-13 11:14:48 -050034
Nolan Scobieddc9c662024-01-30 17:38:42 -050035#include <sstream>
36
Greg Danielcd558522016-11-17 13:31:40 -050037#include "Properties.h"
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050038#include "RenderThread.h"
Greg Danielbe2803a2021-02-19 18:32:16 -050039#include "pipeline/skia/ShaderCache.h"
Greg Daniel45ec62b2017-01-04 14:27:00 -050040#include "renderstate/RenderState.h"
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050041
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050042namespace android {
43namespace uirenderer {
44namespace renderthread {
45
Nolan Scobieddc9c662024-01-30 17:38:42 -050046// Not all of these are strictly required, but are all enabled if present.
Juston Li9a9e06c2024-08-13 20:45:14 +000047static std::array<std::string_view, 23> sEnableExtensions{
John Reckf6067df2023-04-11 16:27:51 -040048 VK_KHR_BIND_MEMORY_2_EXTENSION_NAME,
49 VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME,
50 VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME,
51 VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
52 VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
53 VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
54 VK_KHR_MAINTENANCE1_EXTENSION_NAME,
55 VK_KHR_MAINTENANCE2_EXTENSION_NAME,
56 VK_KHR_MAINTENANCE3_EXTENSION_NAME,
57 VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME,
58 VK_KHR_SURFACE_EXTENSION_NAME,
59 VK_KHR_SWAPCHAIN_EXTENSION_NAME,
60 VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME,
John Reck90b244d2023-04-28 15:41:55 -040061 VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME,
John Reckf6067df2023-04-11 16:27:51 -040062 VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,
63 VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME,
64 VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME,
65 VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,
66 VK_KHR_ANDROID_SURFACE_EXTENSION_NAME,
Mattias Simonssone545f962023-07-17 08:03:14 +000067 VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME,
Juston Li9a9e06c2024-08-13 20:45:14 +000068 VK_EXT_GLOBAL_PRIORITY_QUERY_EXTENSION_NAME,
69 VK_KHR_GLOBAL_PRIORITY_EXTENSION_NAME,
Nolan Scobieddc9c662024-01-30 17:38:42 -050070 VK_EXT_DEVICE_FAULT_EXTENSION_NAME,
John Reckf6067df2023-04-11 16:27:51 -040071};
72
73static bool shouldEnableExtension(const std::string_view& extension) {
74 for (const auto& it : sEnableExtensions) {
75 if (it == extension) {
76 return true;
77 }
78 }
79 return false;
80}
81
Bo Liu7b8c1eb2019-01-08 20:17:55 -080082static void free_features_extensions_structs(const VkPhysicalDeviceFeatures2& features) {
83 // All Vulkan structs that could be part of the features chain will start with the
84 // structure type followed by the pNext pointer. We cast to the CommonVulkanHeader
85 // so we can get access to the pNext for the next struct.
86 struct CommonVulkanHeader {
87 VkStructureType sType;
John Reck0fa0cbc2019-04-05 16:57:46 -070088 void* pNext;
Bo Liu7b8c1eb2019-01-08 20:17:55 -080089 };
90
91 void* pNext = features.pNext;
92 while (pNext) {
93 void* current = pNext;
94 pNext = static_cast<CommonVulkanHeader*>(current)->pNext;
95 free(current);
96 }
97}
98
Greg Daniel2ff202712018-06-14 11:50:10 -040099#define GET_PROC(F) m##F = (PFN_vk##F)vkGetInstanceProcAddr(VK_NULL_HANDLE, "vk" #F)
100#define GET_INST_PROC(F) m##F = (PFN_vk##F)vkGetInstanceProcAddr(mInstance, "vk" #F)
101#define GET_DEV_PROC(F) m##F = (PFN_vk##F)vkGetDeviceProcAddr(mDevice, "vk" #F)
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500102
John Reck9fc3d272023-05-01 16:33:22 -0400103// cache a weakptr to the context to enable a second thread to share the same vulkan state
104static wp<VulkanManager> sWeakInstance = nullptr;
105static std::mutex sLock;
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400106
John Reck9fc3d272023-05-01 16:33:22 -0400107sp<VulkanManager> VulkanManager::getInstance() {
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400108 std::lock_guard _lock{sLock};
109 sp<VulkanManager> vulkanManager = sWeakInstance.promote();
110 if (!vulkanManager.get()) {
111 vulkanManager = new VulkanManager();
112 sWeakInstance = vulkanManager;
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500113 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500114
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400115 return vulkanManager;
116}
117
John Reck9fc3d272023-05-01 16:33:22 -0400118sp<VulkanManager> VulkanManager::peekInstance() {
119 std::lock_guard _lock{sLock};
120 return sWeakInstance.promote();
121}
122
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400123VulkanManager::~VulkanManager() {
Greg Daniel2ff202712018-06-14 11:50:10 -0400124 if (mDevice != VK_NULL_HANDLE) {
125 mDeviceWaitIdle(mDevice);
126 mDestroyDevice(mDevice, nullptr);
John Reck1bcacfd2017-11-03 10:12:19 -0700127 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500128
Greg Daniel2ff202712018-06-14 11:50:10 -0400129 if (mInstance != VK_NULL_HANDLE) {
130 mDestroyInstance(mInstance, nullptr);
131 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500132
Greg Daniel2ff202712018-06-14 11:50:10 -0400133 mGraphicsQueue = VK_NULL_HANDLE;
Alec Mouri219997a2023-05-23 17:25:19 +0000134 mAHBUploadQueue = VK_NULL_HANDLE;
Greg Daniel2ff202712018-06-14 11:50:10 -0400135 mDevice = VK_NULL_HANDLE;
136 mPhysicalDevice = VK_NULL_HANDLE;
137 mInstance = VK_NULL_HANDLE;
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800138 mInstanceExtensionsOwner.clear();
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800139 mInstanceExtensions.clear();
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800140 mDeviceExtensionsOwner.clear();
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800141 mDeviceExtensions.clear();
142 free_features_extensions_structs(mPhysicalDeviceFeatures2);
143 mPhysicalDeviceFeatures2 = {};
Greg Daniel2ff202712018-06-14 11:50:10 -0400144}
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500145
Kaylee Lubickab1f35f2024-06-20 17:19:31 +0000146void VulkanManager::setupDevice(skgpu::VulkanExtensions& grExtensions,
147 VkPhysicalDeviceFeatures2& features) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400148 VkResult err;
149
150 constexpr VkApplicationInfo app_info = {
John Reck0fa0cbc2019-04-05 16:57:46 -0700151 VK_STRUCTURE_TYPE_APPLICATION_INFO, // sType
152 nullptr, // pNext
153 "android framework", // pApplicationName
154 0, // applicationVersion
155 "android framework", // pEngineName
156 0, // engineVerison
157 mAPIVersion, // apiVersion
Greg Daniel2ff202712018-06-14 11:50:10 -0400158 };
159
Greg Daniel2ff202712018-06-14 11:50:10 -0400160 {
161 GET_PROC(EnumerateInstanceExtensionProperties);
162
163 uint32_t extensionCount = 0;
164 err = mEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
Stan Iliev90276c82019-02-03 18:01:02 -0500165 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800166 mInstanceExtensionsOwner.resize(extensionCount);
167 err = mEnumerateInstanceExtensionProperties(nullptr, &extensionCount,
168 mInstanceExtensionsOwner.data());
Stan Iliev90276c82019-02-03 18:01:02 -0500169 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Greg Daniel2ff202712018-06-14 11:50:10 -0400170 bool hasKHRSurfaceExtension = false;
171 bool hasKHRAndroidSurfaceExtension = false;
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800172 for (const VkExtensionProperties& extension : mInstanceExtensionsOwner) {
John Reckf6067df2023-04-11 16:27:51 -0400173 if (!shouldEnableExtension(extension.extensionName)) {
174 ALOGV("Not enabling instance extension %s", extension.extensionName);
175 continue;
176 }
177 ALOGV("Enabling instance extension %s", extension.extensionName);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800178 mInstanceExtensions.push_back(extension.extensionName);
179 if (!strcmp(extension.extensionName, VK_KHR_SURFACE_EXTENSION_NAME)) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400180 hasKHRSurfaceExtension = true;
181 }
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800182 if (!strcmp(extension.extensionName, VK_KHR_ANDROID_SURFACE_EXTENSION_NAME)) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400183 hasKHRAndroidSurfaceExtension = true;
184 }
185 }
Stan Iliev90276c82019-02-03 18:01:02 -0500186 LOG_ALWAYS_FATAL_IF(!hasKHRSurfaceExtension || !hasKHRAndroidSurfaceExtension);
Greg Daniel2ff202712018-06-14 11:50:10 -0400187 }
188
189 const VkInstanceCreateInfo instance_create = {
John Reck0fa0cbc2019-04-05 16:57:46 -0700190 VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, // sType
191 nullptr, // pNext
192 0, // flags
193 &app_info, // pApplicationInfo
194 0, // enabledLayerNameCount
195 nullptr, // ppEnabledLayerNames
196 (uint32_t)mInstanceExtensions.size(), // enabledExtensionNameCount
197 mInstanceExtensions.data(), // ppEnabledExtensionNames
Greg Daniel2ff202712018-06-14 11:50:10 -0400198 };
199
200 GET_PROC(CreateInstance);
201 err = mCreateInstance(&instance_create, nullptr, &mInstance);
Stan Iliev90276c82019-02-03 18:01:02 -0500202 LOG_ALWAYS_FATAL_IF(err < 0);
Greg Daniel2ff202712018-06-14 11:50:10 -0400203
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700204 GET_INST_PROC(CreateDevice);
Greg Daniel2ff202712018-06-14 11:50:10 -0400205 GET_INST_PROC(DestroyInstance);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700206 GET_INST_PROC(EnumerateDeviceExtensionProperties);
Greg Daniel2ff202712018-06-14 11:50:10 -0400207 GET_INST_PROC(EnumeratePhysicalDevices);
Greg Daniela227dbb2018-08-20 09:19:48 -0400208 GET_INST_PROC(GetPhysicalDeviceFeatures2);
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500209 GET_INST_PROC(GetPhysicalDeviceImageFormatProperties2);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700210 GET_INST_PROC(GetPhysicalDeviceProperties);
Juston Li9a9e06c2024-08-13 20:45:14 +0000211 GET_INST_PROC(GetPhysicalDeviceQueueFamilyProperties2);
Greg Daniel2ff202712018-06-14 11:50:10 -0400212
213 uint32_t gpuCount;
Stan Iliev90276c82019-02-03 18:01:02 -0500214 LOG_ALWAYS_FATAL_IF(mEnumeratePhysicalDevices(mInstance, &gpuCount, nullptr));
215 LOG_ALWAYS_FATAL_IF(!gpuCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400216 // Just returning the first physical device instead of getting the whole array. Since there
217 // should only be one device on android.
218 gpuCount = 1;
219 err = mEnumeratePhysicalDevices(mInstance, &gpuCount, &mPhysicalDevice);
220 // VK_INCOMPLETE is returned when the count we provide is less than the total device count.
Stan Iliev90276c82019-02-03 18:01:02 -0500221 LOG_ALWAYS_FATAL_IF(err && VK_INCOMPLETE != err);
Greg Daniel2ff202712018-06-14 11:50:10 -0400222
Greg Daniel96259622018-10-01 14:42:56 -0400223 VkPhysicalDeviceProperties physDeviceProperties;
224 mGetPhysicalDeviceProperties(mPhysicalDevice, &physDeviceProperties);
Stan Iliev90276c82019-02-03 18:01:02 -0500225 LOG_ALWAYS_FATAL_IF(physDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0));
Stan Ilievbf99c442019-03-29 11:09:11 -0400226 mDriverVersion = physDeviceProperties.driverVersion;
Greg Daniel96259622018-10-01 14:42:56 -0400227
Greg Daniel2ff202712018-06-14 11:50:10 -0400228 // query to get the initial queue props size
Alec Mouri219997a2023-05-23 17:25:19 +0000229 uint32_t queueCount = 0;
Juston Li9a9e06c2024-08-13 20:45:14 +0000230 mGetPhysicalDeviceQueueFamilyProperties2(mPhysicalDevice, &queueCount, nullptr);
Stan Iliev90276c82019-02-03 18:01:02 -0500231 LOG_ALWAYS_FATAL_IF(!queueCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400232
233 // now get the actual queue props
Juston Li9a9e06c2024-08-13 20:45:14 +0000234 std::unique_ptr<VkQueueFamilyProperties2[]>
235 queueProps(new VkQueueFamilyProperties2[queueCount]);
236 // query the global priority, this ignored if VK_EXT_global_priority isn't supported
237 std::vector<VkQueueFamilyGlobalPriorityPropertiesEXT> queuePriorityProps(queueCount);
238 for (uint32_t i = 0; i < queueCount; i++) {
239 queuePriorityProps[i].sType = VK_STRUCTURE_TYPE_QUEUE_FAMILY_GLOBAL_PRIORITY_PROPERTIES_EXT;
240 queuePriorityProps[i].pNext = nullptr;
241 queueProps[i].pNext = &queuePriorityProps[i];
242 }
243 mGetPhysicalDeviceQueueFamilyProperties2(mPhysicalDevice, &queueCount, queueProps.get());
Greg Daniel2ff202712018-06-14 11:50:10 -0400244
Alec Mouri219997a2023-05-23 17:25:19 +0000245 constexpr auto kRequestedQueueCount = 2;
246
Greg Daniel2ff202712018-06-14 11:50:10 -0400247 // iterate to find the graphics queue
248 mGraphicsQueueIndex = queueCount;
249 for (uint32_t i = 0; i < queueCount; i++) {
Juston Li9a9e06c2024-08-13 20:45:14 +0000250 if (queueProps[i].queueFamilyProperties.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400251 mGraphicsQueueIndex = i;
Juston Li9a9e06c2024-08-13 20:45:14 +0000252 LOG_ALWAYS_FATAL_IF(
253 queueProps[i].queueFamilyProperties.queueCount < kRequestedQueueCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400254 break;
255 }
256 }
Stan Iliev90276c82019-02-03 18:01:02 -0500257 LOG_ALWAYS_FATAL_IF(mGraphicsQueueIndex == queueCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400258
Greg Daniel2ff202712018-06-14 11:50:10 -0400259 {
260 uint32_t extensionCount = 0;
261 err = mEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr, &extensionCount,
John Reck0fa0cbc2019-04-05 16:57:46 -0700262 nullptr);
Stan Iliev90276c82019-02-03 18:01:02 -0500263 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800264 mDeviceExtensionsOwner.resize(extensionCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400265 err = mEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr, &extensionCount,
John Reck0fa0cbc2019-04-05 16:57:46 -0700266 mDeviceExtensionsOwner.data());
Stan Iliev90276c82019-02-03 18:01:02 -0500267 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Greg Daniel2ff202712018-06-14 11:50:10 -0400268 bool hasKHRSwapchainExtension = false;
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800269 for (const VkExtensionProperties& extension : mDeviceExtensionsOwner) {
John Reckf6067df2023-04-11 16:27:51 -0400270 if (!shouldEnableExtension(extension.extensionName)) {
271 ALOGV("Not enabling device extension %s", extension.extensionName);
272 continue;
273 }
274 ALOGV("Enabling device extension %s", extension.extensionName);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800275 mDeviceExtensions.push_back(extension.extensionName);
276 if (!strcmp(extension.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400277 hasKHRSwapchainExtension = true;
278 }
279 }
Stan Iliev90276c82019-02-03 18:01:02 -0500280 LOG_ALWAYS_FATAL_IF(!hasKHRSwapchainExtension);
Greg Daniel2ff202712018-06-14 11:50:10 -0400281 }
282
Alec Mouri219997a2023-05-23 17:25:19 +0000283 auto getProc = [](const char* proc_name, VkInstance instance, VkDevice device) {
284 if (device != VK_NULL_HANDLE) {
285 return vkGetDeviceProcAddr(device, proc_name);
286 }
287 return vkGetInstanceProcAddr(instance, proc_name);
288 };
289
290 grExtensions.init(getProc, mInstance, mPhysicalDevice, mInstanceExtensions.size(),
John Reck0fa0cbc2019-04-05 16:57:46 -0700291 mInstanceExtensions.data(), mDeviceExtensions.size(),
292 mDeviceExtensions.data());
Greg Daniela227dbb2018-08-20 09:19:48 -0400293
Stan Iliev90276c82019-02-03 18:01:02 -0500294 LOG_ALWAYS_FATAL_IF(!grExtensions.hasExtension(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, 1));
Greg Daniel26e0dca2018-09-18 10:33:19 -0400295
Greg Daniela227dbb2018-08-20 09:19:48 -0400296 memset(&features, 0, sizeof(VkPhysicalDeviceFeatures2));
297 features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
298 features.pNext = nullptr;
299
300 // Setup all extension feature structs we may want to use.
301 void** tailPNext = &features.pNext;
302
303 if (grExtensions.hasExtension(VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME, 2)) {
304 VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT* blend;
John Reck0fa0cbc2019-04-05 16:57:46 -0700305 blend = (VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT*)malloc(
Greg Daniela227dbb2018-08-20 09:19:48 -0400306 sizeof(VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT));
307 LOG_ALWAYS_FATAL_IF(!blend);
308 blend->sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT;
309 blend->pNext = nullptr;
310 *tailPNext = blend;
311 tailPNext = &blend->pNext;
312 }
313
Greg Daniel05036172018-11-28 17:08:04 -0500314 VkPhysicalDeviceSamplerYcbcrConversionFeatures* ycbcrFeature;
John Reck0fa0cbc2019-04-05 16:57:46 -0700315 ycbcrFeature = (VkPhysicalDeviceSamplerYcbcrConversionFeatures*)malloc(
Greg Daniel05036172018-11-28 17:08:04 -0500316 sizeof(VkPhysicalDeviceSamplerYcbcrConversionFeatures));
317 LOG_ALWAYS_FATAL_IF(!ycbcrFeature);
318 ycbcrFeature->sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
319 ycbcrFeature->pNext = nullptr;
320 *tailPNext = ycbcrFeature;
321 tailPNext = &ycbcrFeature->pNext;
322
Nolan Scobieddc9c662024-01-30 17:38:42 -0500323 if (grExtensions.hasExtension(VK_EXT_DEVICE_FAULT_EXTENSION_NAME, 1)) {
324 VkPhysicalDeviceFaultFeaturesEXT* deviceFaultFeatures =
325 new VkPhysicalDeviceFaultFeaturesEXT;
326 deviceFaultFeatures->sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT;
327 deviceFaultFeatures->pNext = nullptr;
328 *tailPNext = deviceFaultFeatures;
329 tailPNext = &deviceFaultFeatures->pNext;
330 }
331
Greg Daniele77ab7a2024-09-04 15:29:52 +0000332 if (grExtensions.hasExtension(VK_EXT_RGBA10X6_FORMATS_EXTENSION_NAME, 1)) {
333 VkPhysicalDeviceRGBA10X6FormatsFeaturesEXT* formatFeatures =
334 new VkPhysicalDeviceRGBA10X6FormatsFeaturesEXT;
335 formatFeatures->sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RGBA10X6_FORMATS_FEATURES_EXT;
336 formatFeatures->pNext = nullptr;
337 *tailPNext = formatFeatures;
338 tailPNext = &formatFeatures->pNext;
339 }
340
Juston Li9a9e06c2024-08-13 20:45:14 +0000341 VkPhysicalDeviceGlobalPriorityQueryFeaturesEXT* globalPriorityQueryFeatures =
342 new VkPhysicalDeviceGlobalPriorityQueryFeaturesEXT;
343 globalPriorityQueryFeatures->sType =
344 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GLOBAL_PRIORITY_QUERY_FEATURES_EXT;
345 globalPriorityQueryFeatures->pNext = nullptr;
346 globalPriorityQueryFeatures->globalPriorityQuery = false;
347 *tailPNext = globalPriorityQueryFeatures;
348 tailPNext = &globalPriorityQueryFeatures->pNext;
349
Greg Daniela227dbb2018-08-20 09:19:48 -0400350 // query to get the physical device features
351 mGetPhysicalDeviceFeatures2(mPhysicalDevice, &features);
Greg Daniel2ff202712018-06-14 11:50:10 -0400352 // this looks like it would slow things down,
353 // and we can't depend on it on all platforms
Greg Daniela227dbb2018-08-20 09:19:48 -0400354 features.features.robustBufferAccess = VK_FALSE;
Greg Daniel2ff202712018-06-14 11:50:10 -0400355
Alec Mouri219997a2023-05-23 17:25:19 +0000356 float queuePriorities[kRequestedQueueCount] = {0.0};
Greg Daniel2ff202712018-06-14 11:50:10 -0400357
Stan Iliev7e733362019-02-28 13:16:36 -0500358 void* queueNextPtr = nullptr;
359
360 VkDeviceQueueGlobalPriorityCreateInfoEXT queuePriorityCreateInfo;
361
John Reck0fa0cbc2019-04-05 16:57:46 -0700362 if (Properties::contextPriority != 0 &&
363 grExtensions.hasExtension(VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME, 2)) {
Juston Li9a9e06c2024-08-13 20:45:14 +0000364 VkQueueGlobalPriorityEXT globalPriority;
Stan Iliev7e733362019-02-28 13:16:36 -0500365 switch (Properties::contextPriority) {
366 case EGL_CONTEXT_PRIORITY_LOW_IMG:
Juston Li9a9e06c2024-08-13 20:45:14 +0000367 globalPriority = VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT;
Stan Iliev7e733362019-02-28 13:16:36 -0500368 break;
369 case EGL_CONTEXT_PRIORITY_MEDIUM_IMG:
Juston Li9a9e06c2024-08-13 20:45:14 +0000370 globalPriority = VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
Stan Iliev7e733362019-02-28 13:16:36 -0500371 break;
372 case EGL_CONTEXT_PRIORITY_HIGH_IMG:
Juston Li9a9e06c2024-08-13 20:45:14 +0000373 globalPriority = VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT;
Stan Iliev7e733362019-02-28 13:16:36 -0500374 break;
375 default:
376 LOG_ALWAYS_FATAL("Unsupported context priority");
John Reck0fa0cbc2019-04-05 16:57:46 -0700377 }
Juston Li9a9e06c2024-08-13 20:45:14 +0000378
379 // check if the requested priority is reported by the query
380 bool attachGlobalPriority = false;
381 if (uirenderer::Properties::queryGlobalPriority &&
382 globalPriorityQueryFeatures->globalPriorityQuery) {
383 for (uint32_t i = 0; i < queuePriorityProps[mGraphicsQueueIndex].priorityCount; i++) {
384 if (queuePriorityProps[mGraphicsQueueIndex].priorities[i] == globalPriority) {
385 attachGlobalPriority = true;
386 break;
387 }
388 }
389 } else {
390 // Querying is not supported so attempt queue creation with requested priority anyways
391 // If the priority turns out not to be supported, the driver *may* fail with
392 // VK_ERROR_NOT_PERMITTED_KHR
393 attachGlobalPriority = true;
394 }
395
396 if (attachGlobalPriority) {
397 memset(&queuePriorityCreateInfo, 0, sizeof(VkDeviceQueueGlobalPriorityCreateInfoEXT));
398 queuePriorityCreateInfo.sType =
399 VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT;
400 queuePriorityCreateInfo.pNext = nullptr;
401 queuePriorityCreateInfo.globalPriority = globalPriority;
402 queueNextPtr = &queuePriorityCreateInfo;
403 } else {
404 // If globalPriorityQuery is enabled, attempting queue creation with an unsupported
405 // priority will return VK_ERROR_INITIALIZATION_FAILED.
406 //
407 // SysUI and Launcher will request HIGH when SF has RT but it is a known issue that
408 // upstream drm drivers currently lack a way to grant them the granular privileges
409 // they need for HIGH (but not RT) so they will fail queue creation.
410 // For now, drop the unsupported global priority request so that queue creation
411 // succeeds.
412 //
413 // Once that is fixed, this should probably be a fatal error indicating an improper
414 // request or an app needs to get the correct privileges.
415 ALOGW("Requested context priority is not supported by the queue");
416 }
Stan Iliev7e733362019-02-28 13:16:36 -0500417 }
418
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700419 const VkDeviceQueueCreateInfo queueInfo = {
420 VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // sType
421 queueNextPtr, // pNext
422 0, // VkDeviceQueueCreateFlags
423 mGraphicsQueueIndex, // queueFamilyIndex
Alec Mouri219997a2023-05-23 17:25:19 +0000424 kRequestedQueueCount, // queueCount
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700425 queuePriorities, // pQueuePriorities
426 };
Greg Daniel2ff202712018-06-14 11:50:10 -0400427
428 const VkDeviceCreateInfo deviceInfo = {
John Reck0fa0cbc2019-04-05 16:57:46 -0700429 VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // sType
430 &features, // pNext
431 0, // VkDeviceCreateFlags
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700432 1, // queueCreateInfoCount
433 &queueInfo, // pQueueCreateInfos
John Reck0fa0cbc2019-04-05 16:57:46 -0700434 0, // layerCount
435 nullptr, // ppEnabledLayerNames
436 (uint32_t)mDeviceExtensions.size(), // extensionCount
437 mDeviceExtensions.data(), // ppEnabledExtensionNames
438 nullptr, // ppEnabledFeatures
Greg Daniel2ff202712018-06-14 11:50:10 -0400439 };
440
Stan Iliev90276c82019-02-03 18:01:02 -0500441 LOG_ALWAYS_FATAL_IF(mCreateDevice(mPhysicalDevice, &deviceInfo, nullptr, &mDevice));
Greg Daniel2ff202712018-06-14 11:50:10 -0400442
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500443 GET_DEV_PROC(AllocateCommandBuffers);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500444 GET_DEV_PROC(BeginCommandBuffer);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500445 GET_DEV_PROC(CmdPipelineBarrier);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700446 GET_DEV_PROC(CreateCommandPool);
447 GET_DEV_PROC(CreateFence);
448 GET_DEV_PROC(CreateSemaphore);
449 GET_DEV_PROC(DestroyCommandPool);
450 GET_DEV_PROC(DestroyDevice);
451 GET_DEV_PROC(DestroyFence);
452 GET_DEV_PROC(DestroySemaphore);
453 GET_DEV_PROC(DeviceWaitIdle);
454 GET_DEV_PROC(EndCommandBuffer);
455 GET_DEV_PROC(FreeCommandBuffers);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500456 GET_DEV_PROC(GetDeviceQueue);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700457 GET_DEV_PROC(GetSemaphoreFdKHR);
458 GET_DEV_PROC(ImportSemaphoreFdKHR);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500459 GET_DEV_PROC(QueueSubmit);
460 GET_DEV_PROC(QueueWaitIdle);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700461 GET_DEV_PROC(ResetCommandBuffer);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500462 GET_DEV_PROC(ResetFences);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700463 GET_DEV_PROC(WaitForFences);
Hugues Evrardb9510a02021-03-01 14:35:22 +0000464 GET_DEV_PROC(FrameBoundaryANDROID);
Greg Daniel2ff202712018-06-14 11:50:10 -0400465}
466
467void VulkanManager::initialize() {
Alec Mouri671a9f62023-08-25 17:18:02 +0000468 std::call_once(mInitFlag, [&] {
469 GET_PROC(EnumerateInstanceVersion);
470 uint32_t instanceVersion;
471 LOG_ALWAYS_FATAL_IF(mEnumerateInstanceVersion(&instanceVersion));
472 LOG_ALWAYS_FATAL_IF(instanceVersion < VK_MAKE_VERSION(1, 1, 0));
Greg Daniel1d9de712021-05-14 09:28:34 -0400473
Alec Mouri671a9f62023-08-25 17:18:02 +0000474 this->setupDevice(mExtensions, mPhysicalDeviceFeatures2);
Greg Daniel2ff202712018-06-14 11:50:10 -0400475
Alec Mouri671a9f62023-08-25 17:18:02 +0000476 mGetDeviceQueue(mDevice, mGraphicsQueueIndex, 0, &mGraphicsQueue);
477 mGetDeviceQueue(mDevice, mGraphicsQueueIndex, 1, &mAHBUploadQueue);
Greg Daniela227dbb2018-08-20 09:19:48 -0400478
Alec Mouri671a9f62023-08-25 17:18:02 +0000479 if (Properties::enablePartialUpdates && Properties::useBufferAge) {
480 mSwapBehavior = SwapBehavior::BufferAge;
481 }
Greg Daniel2ff202712018-06-14 11:50:10 -0400482
Alec Mouri671a9f62023-08-25 17:18:02 +0000483 mInitialized = true;
484 });
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500485}
486
Nolan Scobieddc9c662024-01-30 17:38:42 -0500487namespace {
488void onVkDeviceFault(const std::string& contextLabel, const std::string& description,
489 const std::vector<VkDeviceFaultAddressInfoEXT>& addressInfos,
490 const std::vector<VkDeviceFaultVendorInfoEXT>& vendorInfos,
491 const std::vector<std::byte>& vendorBinaryData) {
492 // The final crash string should contain as much differentiating info as possible, up to 1024
493 // bytes. As this final message is constructed, the same information is also dumped to the logs
494 // but in a more verbose format. Building the crash string is unsightly, so the clearer logging
495 // statement is always placed first to give context.
496 ALOGE("VK_ERROR_DEVICE_LOST (%s context): %s", contextLabel.c_str(), description.c_str());
497 std::stringstream crashMsg;
498 crashMsg << "VK_ERROR_DEVICE_LOST (" << contextLabel;
499
500 if (!addressInfos.empty()) {
501 ALOGE("%zu VkDeviceFaultAddressInfoEXT:", addressInfos.size());
502 crashMsg << ", " << addressInfos.size() << " address info (";
503 for (VkDeviceFaultAddressInfoEXT addressInfo : addressInfos) {
504 ALOGE(" addressType: %d", (int)addressInfo.addressType);
505 ALOGE(" reportedAddress: %" PRIu64, addressInfo.reportedAddress);
506 ALOGE(" addressPrecision: %" PRIu64, addressInfo.addressPrecision);
507 crashMsg << addressInfo.addressType << ":"
508 << addressInfo.reportedAddress << ":"
509 << addressInfo.addressPrecision << ", ";
510 }
511 crashMsg.seekp(-2, crashMsg.cur); // Move back to overwrite trailing ", "
512 crashMsg << ")";
513 }
514
515 if (!vendorInfos.empty()) {
516 ALOGE("%zu VkDeviceFaultVendorInfoEXT:", vendorInfos.size());
517 crashMsg << ", " << vendorInfos.size() << " vendor info (";
518 for (VkDeviceFaultVendorInfoEXT vendorInfo : vendorInfos) {
519 ALOGE(" description: %s", vendorInfo.description);
520 ALOGE(" vendorFaultCode: %" PRIu64, vendorInfo.vendorFaultCode);
521 ALOGE(" vendorFaultData: %" PRIu64, vendorInfo.vendorFaultData);
522 // Omit descriptions for individual vendor info structs in the crash string, as the
523 // fault code and fault data fields should be enough for clustering, and the verbosity
524 // isn't worth it. Additionally, vendors may just set the general description field of
525 // the overall fault to the description of the first element in this list, and that
526 // overall description will be placed at the end of the crash string.
527 crashMsg << vendorInfo.vendorFaultCode << ":"
528 << vendorInfo.vendorFaultData << ", ";
529 }
530 crashMsg.seekp(-2, crashMsg.cur); // Move back to overwrite trailing ", "
531 crashMsg << ")";
532 }
533
534 if (!vendorBinaryData.empty()) {
535 // TODO: b/322830575 - Log in base64, or dump directly to a file that gets put in bugreports
536 ALOGE("%zu bytes of vendor-specific binary data (please notify Android's Core Graphics"
537 " Stack team if you observe this message).",
538 vendorBinaryData.size());
539 crashMsg << ", " << vendorBinaryData.size() << " bytes binary";
540 }
541
542 crashMsg << "): " << description;
543 LOG_ALWAYS_FATAL("%s", crashMsg.str().c_str());
544}
545
546void deviceLostProcRenderThread(void* callbackContext, const std::string& description,
547 const std::vector<VkDeviceFaultAddressInfoEXT>& addressInfos,
548 const std::vector<VkDeviceFaultVendorInfoEXT>& vendorInfos,
549 const std::vector<std::byte>& vendorBinaryData) {
550 onVkDeviceFault("RenderThread", description, addressInfos, vendorInfos, vendorBinaryData);
551}
552void deviceLostProcUploadThread(void* callbackContext, const std::string& description,
553 const std::vector<VkDeviceFaultAddressInfoEXT>& addressInfos,
554 const std::vector<VkDeviceFaultVendorInfoEXT>& vendorInfos,
555 const std::vector<std::byte>& vendorBinaryData) {
556 onVkDeviceFault("UploadThread", description, addressInfos, vendorInfos, vendorBinaryData);
557}
558} // anonymous namespace
559
John Reck9fc3d272023-05-01 16:33:22 -0400560static void onGrContextReleased(void* context) {
561 VulkanManager* manager = (VulkanManager*)context;
562 manager->decStrong((void*)onGrContextReleased);
563}
Stan Iliev981afe72019-02-13 14:24:33 -0500564
John Reck9fc3d272023-05-01 16:33:22 -0400565sk_sp<GrDirectContext> VulkanManager::createContext(GrContextOptions& options,
566 ContextType contextType) {
Alec Mouri219997a2023-05-23 17:25:19 +0000567 auto getProc = [](const char* proc_name, VkInstance instance, VkDevice device) {
568 if (device != VK_NULL_HANDLE) {
569 return vkGetDeviceProcAddr(device, proc_name);
570 }
571 return vkGetInstanceProcAddr(instance, proc_name);
572 };
573
Kaylee Lubickab1f35f2024-06-20 17:19:31 +0000574 skgpu::VulkanBackendContext backendContext;
Stan Iliev981afe72019-02-13 14:24:33 -0500575 backendContext.fInstance = mInstance;
576 backendContext.fPhysicalDevice = mPhysicalDevice;
577 backendContext.fDevice = mDevice;
Alec Mouri219997a2023-05-23 17:25:19 +0000578 backendContext.fQueue =
579 (contextType == ContextType::kRenderThread) ? mGraphicsQueue : mAHBUploadQueue;
Stan Iliev981afe72019-02-13 14:24:33 -0500580 backendContext.fGraphicsQueueIndex = mGraphicsQueueIndex;
581 backendContext.fMaxAPIVersion = mAPIVersion;
582 backendContext.fVkExtensions = &mExtensions;
583 backendContext.fDeviceFeatures2 = &mPhysicalDeviceFeatures2;
Alec Mouri219997a2023-05-23 17:25:19 +0000584 backendContext.fGetProc = std::move(getProc);
Nolan Scobieddc9c662024-01-30 17:38:42 -0500585 backendContext.fDeviceLostContext = nullptr;
586 backendContext.fDeviceLostProc = (contextType == ContextType::kRenderThread)
587 ? deviceLostProcRenderThread
588 : deviceLostProcUploadThread;
Stan Iliev981afe72019-02-13 14:24:33 -0500589
John Reck9fc3d272023-05-01 16:33:22 -0400590 LOG_ALWAYS_FATAL_IF(options.fContextDeleteProc != nullptr, "Conflicting fContextDeleteProcs!");
591 this->incStrong((void*)onGrContextReleased);
592 options.fContextDeleteContext = this;
593 options.fContextDeleteProc = onGrContextReleased;
594
Kevin Lubickf6b21952023-10-13 13:12:17 +0000595 return GrDirectContexts::MakeVulkan(backendContext, options);
Stan Iliev981afe72019-02-13 14:24:33 -0500596}
597
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800598VkFunctorInitParams VulkanManager::getVkFunctorInitParams() const {
599 return VkFunctorInitParams{
600 .instance = mInstance,
601 .physical_device = mPhysicalDevice,
602 .device = mDevice,
603 .queue = mGraphicsQueue,
604 .graphics_queue_index = mGraphicsQueueIndex,
Greg Danieleaf310e2019-01-28 16:10:32 -0500605 .api_version = mAPIVersion,
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800606 .enabled_instance_extension_names = mInstanceExtensions.data(),
607 .enabled_instance_extension_names_length =
608 static_cast<uint32_t>(mInstanceExtensions.size()),
609 .enabled_device_extension_names = mDeviceExtensions.data(),
610 .enabled_device_extension_names_length =
611 static_cast<uint32_t>(mDeviceExtensions.size()),
612 .device_features_2 = &mPhysicalDeviceFeatures2,
613 };
614}
615
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500616Frame VulkanManager::dequeueNextBuffer(VulkanSurface* surface) {
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500617 VulkanSurface::NativeBufferInfo* bufferInfo = surface->dequeueNativeBuffer();
618
619 if (bufferInfo == nullptr) {
620 ALOGE("VulkanSurface::dequeueNativeBuffer called with an invalid surface!");
621 return Frame(-1, -1, 0);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500622 }
623
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500624 LOG_ALWAYS_FATAL_IF(!bufferInfo->dequeued);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500625
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500626 if (bufferInfo->dequeue_fence != -1) {
Stan Iliev197843d2019-03-21 11:34:15 -0400627 struct sync_file_info* finfo = sync_file_info(bufferInfo->dequeue_fence);
628 bool isSignalPending = false;
629 if (finfo != NULL) {
630 isSignalPending = finfo->status != 1;
631 sync_file_info_free(finfo);
632 }
633 if (isSignalPending) {
634 int fence_clone = dup(bufferInfo->dequeue_fence);
635 if (fence_clone == -1) {
636 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)", strerror(errno),
637 errno);
638 sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
639 } else {
640 VkSemaphoreCreateInfo semaphoreInfo;
641 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
642 semaphoreInfo.pNext = nullptr;
643 semaphoreInfo.flags = 0;
644 VkSemaphore semaphore;
645 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
Greg Danield6670772021-06-09 12:01:12 -0400646 if (err != VK_SUCCESS) {
647 ALOGE("Failed to create import semaphore, err: %d", err);
648 close(fence_clone);
649 sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
650 } else {
651 VkImportSemaphoreFdInfoKHR importInfo;
652 importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR;
653 importInfo.pNext = nullptr;
654 importInfo.semaphore = semaphore;
655 importInfo.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
656 importInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
657 importInfo.fd = fence_clone;
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500658
Greg Danield6670772021-06-09 12:01:12 -0400659 err = mImportSemaphoreFdKHR(mDevice, &importInfo);
660 if (err != VK_SUCCESS) {
661 ALOGE("Failed to import semaphore, err: %d", err);
662 mDestroySemaphore(mDevice, semaphore, nullptr);
663 close(fence_clone);
664 sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
665 } else {
Kevin Lubick913e9a42024-03-07 13:14:46 +0000666 GrBackendSemaphore beSemaphore = GrBackendSemaphores::MakeVk(semaphore);
Greg Danield6670772021-06-09 12:01:12 -0400667 // Skia will take ownership of the VkSemaphore and delete it once the wait
668 // has finished. The VkSemaphore also owns the imported fd, so it will
669 // close the fd when it is deleted.
Kevin Lubick913e9a42024-03-07 13:14:46 +0000670 bufferInfo->skSurface->wait(1, &beSemaphore);
Greg Danield6670772021-06-09 12:01:12 -0400671 // The following flush blocks the GPU immediately instead of waiting for
672 // other drawing ops. It seems dequeue_fence is not respected otherwise.
Kevin Lubick913e9a42024-03-07 13:14:46 +0000673 // TODO: remove the flush after finding why beSemaphore is not working.
Kevin Lubickcae0b212023-09-12 18:33:10 +0000674 skgpu::ganesh::FlushAndSubmit(bufferInfo->skSurface.get());
Greg Danield6670772021-06-09 12:01:12 -0400675 }
676 }
Stan Iliev197843d2019-03-21 11:34:15 -0400677 }
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500678 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500679 }
680
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500681 int bufferAge = (mSwapBehavior == SwapBehavior::Discard) ? 0 : surface->getCurrentBuffersAge();
682 return Frame(surface->logicalWidth(), surface->logicalHeight(), bufferAge);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500683}
684
John Reck4db23fd2023-11-10 15:31:49 -0500685class SharedSemaphoreInfo : public LightRefBase<SharedSemaphoreInfo> {
Greg Danield92a9b12019-04-23 10:11:04 -0400686 PFN_vkDestroySemaphore mDestroyFunction;
687 VkDevice mDevice;
688 VkSemaphore mSemaphore;
John Reck4db23fd2023-11-10 15:31:49 -0500689 GrBackendSemaphore mGrBackendSemaphore;
Greg Danield92a9b12019-04-23 10:11:04 -0400690
John Reck4db23fd2023-11-10 15:31:49 -0500691 SharedSemaphoreInfo(PFN_vkDestroySemaphore destroyFunction, VkDevice device,
692 VkSemaphore semaphore)
Priyanka Advanidfca12a2024-03-06 22:25:04 +0000693 : mDestroyFunction(destroyFunction), mDevice(device), mSemaphore(semaphore) {
Kevin Lubick913e9a42024-03-07 13:14:46 +0000694 mGrBackendSemaphore = GrBackendSemaphores::MakeVk(mSemaphore);
John Reck4db23fd2023-11-10 15:31:49 -0500695 }
John Reck5d3fac12023-11-08 23:08:10 -0500696
John Reck4db23fd2023-11-10 15:31:49 -0500697 ~SharedSemaphoreInfo() { mDestroyFunction(mDevice, mSemaphore, nullptr); }
698
699 friend class LightRefBase<SharedSemaphoreInfo>;
700 friend class sp<SharedSemaphoreInfo>;
701
702public:
703 VkSemaphore semaphore() const { return mSemaphore; }
704
705 GrBackendSemaphore* grBackendSemaphore() { return &mGrBackendSemaphore; }
Greg Danield92a9b12019-04-23 10:11:04 -0400706};
707
708static void destroy_semaphore(void* context) {
John Reck4db23fd2023-11-10 15:31:49 -0500709 SharedSemaphoreInfo* info = reinterpret_cast<SharedSemaphoreInfo*>(context);
710 info->decStrong(0);
Greg Danield92a9b12019-04-23 10:11:04 -0400711}
712
John Reck5d3fac12023-11-08 23:08:10 -0500713VulkanManager::VkDrawResult VulkanManager::finishFrame(SkSurface* surface) {
Greg Danielbe2803a2021-02-19 18:32:16 -0500714 ATRACE_NAME("Vulkan finish frame");
Stan Ilievbc5f06b2019-03-26 15:14:34 -0400715
John Reck4db23fd2023-11-10 15:31:49 -0500716 sp<SharedSemaphoreInfo> sharedSemaphore;
Greg Danielc7ad4082020-05-14 15:38:26 -0400717 GrFlushInfo flushInfo;
John Reck4db23fd2023-11-10 15:31:49 -0500718
719 {
720 VkExportSemaphoreCreateInfo exportInfo;
721 exportInfo.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO;
722 exportInfo.pNext = nullptr;
723 exportInfo.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
724
725 VkSemaphoreCreateInfo semaphoreInfo;
726 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
727 semaphoreInfo.pNext = &exportInfo;
728 semaphoreInfo.flags = 0;
729 VkSemaphore semaphore;
730 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
731 ALOGE_IF(VK_SUCCESS != err,
732 "VulkanManager::makeSwapSemaphore(): Failed to create semaphore");
733
734 if (err == VK_SUCCESS) {
735 sharedSemaphore = sp<SharedSemaphoreInfo>::make(mDestroySemaphore, mDevice, semaphore);
736 flushInfo.fNumSemaphores = 1;
737 flushInfo.fSignalSemaphores = sharedSemaphore->grBackendSemaphore();
738 flushInfo.fFinishedProc = destroy_semaphore;
739 sharedSemaphore->incStrong(0);
740 flushInfo.fFinishedContext = sharedSemaphore.get();
741 }
Greg Danielbe2803a2021-02-19 18:32:16 -0500742 }
John Reck4db23fd2023-11-10 15:31:49 -0500743
Greg Danielbe2803a2021-02-19 18:32:16 -0500744 GrDirectContext* context = GrAsDirectContext(surface->recordingContext());
Adlai Holler0375fee2020-09-15 12:31:22 -0400745 ALOGE_IF(!context, "Surface is not backed by gpu");
Kevin Lubickaa592d02023-05-30 15:07:06 +0000746 GrSemaphoresSubmitted submitted = context->flush(
747 surface, SkSurfaces::BackendSurfaceAccess::kPresent, flushInfo);
Adlai Holler0375fee2020-09-15 12:31:22 -0400748 context->submit();
John Reck5d3fac12023-11-08 23:08:10 -0500749 VkDrawResult drawResult{
750 .submissionTime = systemTime(),
751 };
John Reck4db23fd2023-11-10 15:31:49 -0500752 if (sharedSemaphore) {
753 if (submitted == GrSemaphoresSubmitted::kYes && mFrameBoundaryANDROID) {
754 // retrieve VkImage used as render target
755 VkImage image = VK_NULL_HANDLE;
756 GrBackendRenderTarget backendRenderTarget = SkSurfaces::GetBackendRenderTarget(
757 surface, SkSurfaces::BackendHandleAccess::kFlushRead);
758 if (backendRenderTarget.isValid()) {
759 GrVkImageInfo info;
760 if (GrBackendRenderTargets::GetVkImageInfo(backendRenderTarget, &info)) {
761 image = info.fImage;
Hugues Evrardb9510a02021-03-01 14:35:22 +0000762 } else {
John Reck4db23fd2023-11-10 15:31:49 -0500763 ALOGE("Frame boundary: backend is not vulkan");
Hugues Evrardb9510a02021-03-01 14:35:22 +0000764 }
John Reck4db23fd2023-11-10 15:31:49 -0500765 } else {
766 ALOGE("Frame boundary: invalid backend render target");
Hugues Evrardb9510a02021-03-01 14:35:22 +0000767 }
John Reck4db23fd2023-11-10 15:31:49 -0500768 // frameBoundaryANDROID needs to know about mSwapSemaphore, but
769 // it won't wait on it.
770 mFrameBoundaryANDROID(mDevice, sharedSemaphore->semaphore(), image);
Greg Danielbe2803a2021-02-19 18:32:16 -0500771 }
John Reck5d3fac12023-11-08 23:08:10 -0500772 VkSemaphoreGetFdInfoKHR getFdInfo;
773 getFdInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR;
774 getFdInfo.pNext = nullptr;
John Reck4db23fd2023-11-10 15:31:49 -0500775 getFdInfo.semaphore = sharedSemaphore->semaphore();
John Reck5d3fac12023-11-08 23:08:10 -0500776 getFdInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
777
778 int fenceFd = -1;
John Reck4db23fd2023-11-10 15:31:49 -0500779 VkResult err = mGetSemaphoreFdKHR(mDevice, &getFdInfo, &fenceFd);
John Reck5d3fac12023-11-08 23:08:10 -0500780 ALOGE_IF(VK_SUCCESS != err, "VulkanManager::swapBuffers(): Failed to get semaphore Fd");
781 drawResult.presentFence.reset(fenceFd);
782 } else {
783 ALOGE("VulkanManager::finishFrame(): Semaphore submission failed");
784 mQueueWaitIdle(mGraphicsQueue);
Greg Danielbe2803a2021-02-19 18:32:16 -0500785 }
John Reck5d3fac12023-11-08 23:08:10 -0500786
Greg Danielbe2803a2021-02-19 18:32:16 -0500787 skiapipeline::ShaderCache::get().onVkFrameFlushed(context);
Alec Mouri3afb3972022-05-27 22:03:11 +0000788
John Reck5d3fac12023-11-08 23:08:10 -0500789 return drawResult;
Greg Danielbe2803a2021-02-19 18:32:16 -0500790}
791
John Reck5d3fac12023-11-08 23:08:10 -0500792void VulkanManager::swapBuffers(VulkanSurface* surface, const SkRect& dirtyRect,
793 android::base::unique_fd&& presentFence) {
Greg Danielbe2803a2021-02-19 18:32:16 -0500794 if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
795 ATRACE_NAME("Finishing GPU work");
796 mDeviceWaitIdle(mDevice);
797 }
798
John Reck5d3fac12023-11-08 23:08:10 -0500799 surface->presentCurrentBuffer(dirtyRect, presentFence.release());
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500800}
801
802void VulkanManager::destroySurface(VulkanSurface* surface) {
803 // Make sure all submit commands have finished before starting to destroy objects.
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700804 if (VK_NULL_HANDLE != mGraphicsQueue) {
805 mQueueWaitIdle(mGraphicsQueue);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500806 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500807
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500808 delete surface;
809}
810
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400811VulkanSurface* VulkanManager::createSurface(ANativeWindow* window,
812 ColorMode colorMode,
Peiyong Lin3bff1352018-12-11 07:56:07 -0800813 sk_sp<SkColorSpace> surfaceColorSpace,
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400814 SkColorType surfaceColorType,
815 GrDirectContext* grContext,
John Reck0fa0cbc2019-04-05 16:57:46 -0700816 uint32_t extraBuffers) {
Stan Iliev981afe72019-02-13 14:24:33 -0500817 LOG_ALWAYS_FATAL_IF(!hasVkContext(), "Not initialized");
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500818 if (!window) {
819 return nullptr;
820 }
821
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500822 return VulkanSurface::Create(window, colorMode, surfaceColorType, surfaceColorSpace, grContext,
John Reck0fa0cbc2019-04-05 16:57:46 -0700823 *this, extraBuffers);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500824}
825
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400826status_t VulkanManager::fenceWait(int fence, GrDirectContext* grContext) {
Greg Daniel26e0dca2018-09-18 10:33:19 -0400827 if (!hasVkContext()) {
828 ALOGE("VulkanManager::fenceWait: VkDevice not initialized");
829 return INVALID_OPERATION;
830 }
831
Stan Iliev7a081272018-10-26 17:54:18 -0400832 // Block GPU on the fence.
Stan Ilievaaa9e832019-09-17 14:07:23 -0400833 int fenceFd = ::dup(fence);
Stan Iliev7a081272018-10-26 17:54:18 -0400834 if (fenceFd == -1) {
835 ALOGE("VulkanManager::fenceWait: error dup'ing fence fd: %d", errno);
836 return -errno;
Stan Iliev564ca3e2018-09-04 22:00:00 +0000837 }
Stan Iliev7a081272018-10-26 17:54:18 -0400838
839 VkSemaphoreCreateInfo semaphoreInfo;
840 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
841 semaphoreInfo.pNext = nullptr;
842 semaphoreInfo.flags = 0;
843 VkSemaphore semaphore;
844 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
845 if (VK_SUCCESS != err) {
Greg Danield6670772021-06-09 12:01:12 -0400846 close(fenceFd);
Stan Iliev7a081272018-10-26 17:54:18 -0400847 ALOGE("Failed to create import semaphore, err: %d", err);
848 return UNKNOWN_ERROR;
849 }
850 VkImportSemaphoreFdInfoKHR importInfo;
851 importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR;
852 importInfo.pNext = nullptr;
853 importInfo.semaphore = semaphore;
854 importInfo.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
855 importInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
856 importInfo.fd = fenceFd;
857
858 err = mImportSemaphoreFdKHR(mDevice, &importInfo);
859 if (VK_SUCCESS != err) {
Greg Danield92a9b12019-04-23 10:11:04 -0400860 mDestroySemaphore(mDevice, semaphore, nullptr);
Greg Danield6670772021-06-09 12:01:12 -0400861 close(fenceFd);
Stan Iliev7a081272018-10-26 17:54:18 -0400862 ALOGE("Failed to import semaphore, err: %d", err);
863 return UNKNOWN_ERROR;
864 }
865
Kevin Lubick913e9a42024-03-07 13:14:46 +0000866 GrBackendSemaphore beSemaphore = GrBackendSemaphores::MakeVk(semaphore);
Stan Iliev7a081272018-10-26 17:54:18 -0400867
Greg Danield6670772021-06-09 12:01:12 -0400868 // Skia will take ownership of the VkSemaphore and delete it once the wait has finished. The
869 // VkSemaphore also owns the imported fd, so it will close the fd when it is deleted.
Greg Danield92a9b12019-04-23 10:11:04 -0400870 grContext->wait(1, &beSemaphore);
Greg Danielc7ad4082020-05-14 15:38:26 -0400871 grContext->flushAndSubmit();
Stan Iliev7a081272018-10-26 17:54:18 -0400872
Stan Iliev564ca3e2018-09-04 22:00:00 +0000873 return OK;
874}
875
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400876status_t VulkanManager::createReleaseFence(int* nativeFence, GrDirectContext* grContext) {
Stan Ilievaaa9e832019-09-17 14:07:23 -0400877 *nativeFence = -1;
Greg Daniel26e0dca2018-09-18 10:33:19 -0400878 if (!hasVkContext()) {
879 ALOGE("VulkanManager::createReleaseFence: VkDevice not initialized");
880 return INVALID_OPERATION;
881 }
882
Greg Daniel26e0dca2018-09-18 10:33:19 -0400883 VkExportSemaphoreCreateInfo exportInfo;
884 exportInfo.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO;
885 exportInfo.pNext = nullptr;
886 exportInfo.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
887
888 VkSemaphoreCreateInfo semaphoreInfo;
889 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
890 semaphoreInfo.pNext = &exportInfo;
891 semaphoreInfo.flags = 0;
892 VkSemaphore semaphore;
893 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
894 if (VK_SUCCESS != err) {
895 ALOGE("VulkanManager::createReleaseFence: Failed to create semaphore");
896 return INVALID_OPERATION;
897 }
898
John Reck4db23fd2023-11-10 15:31:49 -0500899 auto sharedSemaphore = sp<SharedSemaphoreInfo>::make(mDestroySemaphore, mDevice, semaphore);
Greg Daniel26e0dca2018-09-18 10:33:19 -0400900
Greg Danielfd429392019-05-09 15:44:56 -0400901 // Even if Skia fails to submit the semaphore, it will still call the destroy_semaphore callback
Greg Danielc7ad4082020-05-14 15:38:26 -0400902 GrFlushInfo flushInfo;
903 flushInfo.fNumSemaphores = 1;
John Reck4db23fd2023-11-10 15:31:49 -0500904 flushInfo.fSignalSemaphores = sharedSemaphore->grBackendSemaphore();
Greg Danielc7ad4082020-05-14 15:38:26 -0400905 flushInfo.fFinishedProc = destroy_semaphore;
John Reck4db23fd2023-11-10 15:31:49 -0500906 sharedSemaphore->incStrong(0);
907 flushInfo.fFinishedContext = sharedSemaphore.get();
Greg Danielc7ad4082020-05-14 15:38:26 -0400908 GrSemaphoresSubmitted submitted = grContext->flush(flushInfo);
909 grContext->submit();
Greg Daniel26e0dca2018-09-18 10:33:19 -0400910
Greg Danield92a9b12019-04-23 10:11:04 -0400911 if (submitted == GrSemaphoresSubmitted::kNo) {
912 ALOGE("VulkanManager::createReleaseFence: Failed to submit semaphore");
Greg Danield92a9b12019-04-23 10:11:04 -0400913 return INVALID_OPERATION;
914 }
Greg Daniel26e0dca2018-09-18 10:33:19 -0400915
916 VkSemaphoreGetFdInfoKHR getFdInfo;
917 getFdInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR;
918 getFdInfo.pNext = nullptr;
919 getFdInfo.semaphore = semaphore;
920 getFdInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
921
922 int fenceFd = 0;
923
924 err = mGetSemaphoreFdKHR(mDevice, &getFdInfo, &fenceFd);
925 if (VK_SUCCESS != err) {
926 ALOGE("VulkanManager::createReleaseFence: Failed to get semaphore Fd");
927 return INVALID_OPERATION;
928 }
Stan Ilievaaa9e832019-09-17 14:07:23 -0400929 *nativeFence = fenceFd;
Greg Daniel26e0dca2018-09-18 10:33:19 -0400930
Stan Iliev564ca3e2018-09-04 22:00:00 +0000931 return OK;
932}
933
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500934} /* namespace renderthread */
935} /* namespace uirenderer */
936} /* namespace android */