blob: b5f7caaf1b5b8dd04b9edbbdaff7b5631fc481d9 [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 <GrBackendSemaphore.h>
22#include <GrBackendSurface.h>
Adlai Hollerf8c434e2020-07-27 11:42:45 -040023#include <GrDirectContext.h>
Stan Ilievaaa9e832019-09-17 14:07:23 -040024#include <GrTypes.h>
25#include <android/sync.h>
Alec Mouri219997a2023-05-23 17:25:19 +000026#include <gui/TraceUtils.h>
27#include <include/gpu/ganesh/SkSurfaceGanesh.h>
Brian Osman734d8102023-08-29 18:07:56 +000028#include <include/gpu/ganesh/vk/GrVkBackendSurface.h>
Kevin Lubickf6b21952023-10-13 13:12:17 +000029#include <include/gpu/ganesh/vk/GrVkDirectContext.h>
Jagadeesh Pakaravoorb624af32020-05-01 00:01:40 +000030#include <ui/FatVector.h>
Stan Ilievaaa9e832019-09-17 14:07:23 -040031#include <vk/GrVkExtensions.h>
32#include <vk/GrVkTypes.h>
Stan Iliev305e13a2018-11-13 11:14:48 -050033
Nolan Scobieddc9c662024-01-30 17:38:42 -050034#include <sstream>
35
Greg Danielcd558522016-11-17 13:31:40 -050036#include "Properties.h"
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050037#include "RenderThread.h"
Greg Danielbe2803a2021-02-19 18:32:16 -050038#include "pipeline/skia/ShaderCache.h"
Greg Daniel45ec62b2017-01-04 14:27:00 -050039#include "renderstate/RenderState.h"
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050040
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050041namespace android {
42namespace uirenderer {
43namespace renderthread {
44
Nolan Scobieddc9c662024-01-30 17:38:42 -050045// Not all of these are strictly required, but are all enabled if present.
46static std::array<std::string_view, 21> sEnableExtensions{
John Reckf6067df2023-04-11 16:27:51 -040047 VK_KHR_BIND_MEMORY_2_EXTENSION_NAME,
48 VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME,
49 VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME,
50 VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
51 VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
52 VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
53 VK_KHR_MAINTENANCE1_EXTENSION_NAME,
54 VK_KHR_MAINTENANCE2_EXTENSION_NAME,
55 VK_KHR_MAINTENANCE3_EXTENSION_NAME,
56 VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME,
57 VK_KHR_SURFACE_EXTENSION_NAME,
58 VK_KHR_SWAPCHAIN_EXTENSION_NAME,
59 VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME,
John Reck90b244d2023-04-28 15:41:55 -040060 VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME,
John Reckf6067df2023-04-11 16:27:51 -040061 VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME,
62 VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME,
63 VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME,
64 VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME,
65 VK_KHR_ANDROID_SURFACE_EXTENSION_NAME,
Mattias Simonssone545f962023-07-17 08:03:14 +000066 VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME,
Nolan Scobieddc9c662024-01-30 17:38:42 -050067 VK_EXT_DEVICE_FAULT_EXTENSION_NAME,
John Reckf6067df2023-04-11 16:27:51 -040068};
69
70static bool shouldEnableExtension(const std::string_view& extension) {
71 for (const auto& it : sEnableExtensions) {
72 if (it == extension) {
73 return true;
74 }
75 }
76 return false;
77}
78
Bo Liu7b8c1eb2019-01-08 20:17:55 -080079static void free_features_extensions_structs(const VkPhysicalDeviceFeatures2& features) {
80 // All Vulkan structs that could be part of the features chain will start with the
81 // structure type followed by the pNext pointer. We cast to the CommonVulkanHeader
82 // so we can get access to the pNext for the next struct.
83 struct CommonVulkanHeader {
84 VkStructureType sType;
John Reck0fa0cbc2019-04-05 16:57:46 -070085 void* pNext;
Bo Liu7b8c1eb2019-01-08 20:17:55 -080086 };
87
88 void* pNext = features.pNext;
89 while (pNext) {
90 void* current = pNext;
91 pNext = static_cast<CommonVulkanHeader*>(current)->pNext;
92 free(current);
93 }
94}
95
Greg Daniel2ff202712018-06-14 11:50:10 -040096#define GET_PROC(F) m##F = (PFN_vk##F)vkGetInstanceProcAddr(VK_NULL_HANDLE, "vk" #F)
97#define GET_INST_PROC(F) m##F = (PFN_vk##F)vkGetInstanceProcAddr(mInstance, "vk" #F)
98#define GET_DEV_PROC(F) m##F = (PFN_vk##F)vkGetDeviceProcAddr(mDevice, "vk" #F)
Derek Sollenberger0e3cba32016-11-09 11:58:36 -050099
John Reck9fc3d272023-05-01 16:33:22 -0400100// cache a weakptr to the context to enable a second thread to share the same vulkan state
101static wp<VulkanManager> sWeakInstance = nullptr;
102static std::mutex sLock;
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400103
John Reck9fc3d272023-05-01 16:33:22 -0400104sp<VulkanManager> VulkanManager::getInstance() {
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400105 std::lock_guard _lock{sLock};
106 sp<VulkanManager> vulkanManager = sWeakInstance.promote();
107 if (!vulkanManager.get()) {
108 vulkanManager = new VulkanManager();
109 sWeakInstance = vulkanManager;
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500110 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500111
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400112 return vulkanManager;
113}
114
John Reck9fc3d272023-05-01 16:33:22 -0400115sp<VulkanManager> VulkanManager::peekInstance() {
116 std::lock_guard _lock{sLock};
117 return sWeakInstance.promote();
118}
119
Derek Sollenberger802fefa2020-08-13 16:53:30 -0400120VulkanManager::~VulkanManager() {
Greg Daniel2ff202712018-06-14 11:50:10 -0400121 if (mDevice != VK_NULL_HANDLE) {
122 mDeviceWaitIdle(mDevice);
123 mDestroyDevice(mDevice, nullptr);
John Reck1bcacfd2017-11-03 10:12:19 -0700124 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500125
Greg Daniel2ff202712018-06-14 11:50:10 -0400126 if (mInstance != VK_NULL_HANDLE) {
127 mDestroyInstance(mInstance, nullptr);
128 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500129
Greg Daniel2ff202712018-06-14 11:50:10 -0400130 mGraphicsQueue = VK_NULL_HANDLE;
Alec Mouri219997a2023-05-23 17:25:19 +0000131 mAHBUploadQueue = VK_NULL_HANDLE;
Greg Daniel2ff202712018-06-14 11:50:10 -0400132 mDevice = VK_NULL_HANDLE;
133 mPhysicalDevice = VK_NULL_HANDLE;
134 mInstance = VK_NULL_HANDLE;
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800135 mInstanceExtensionsOwner.clear();
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800136 mInstanceExtensions.clear();
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800137 mDeviceExtensionsOwner.clear();
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800138 mDeviceExtensions.clear();
139 free_features_extensions_structs(mPhysicalDeviceFeatures2);
140 mPhysicalDeviceFeatures2 = {};
Greg Daniel2ff202712018-06-14 11:50:10 -0400141}
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500142
Stan Iliev90276c82019-02-03 18:01:02 -0500143void VulkanManager::setupDevice(GrVkExtensions& grExtensions, VkPhysicalDeviceFeatures2& features) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400144 VkResult err;
145
146 constexpr VkApplicationInfo app_info = {
John Reck0fa0cbc2019-04-05 16:57:46 -0700147 VK_STRUCTURE_TYPE_APPLICATION_INFO, // sType
148 nullptr, // pNext
149 "android framework", // pApplicationName
150 0, // applicationVersion
151 "android framework", // pEngineName
152 0, // engineVerison
153 mAPIVersion, // apiVersion
Greg Daniel2ff202712018-06-14 11:50:10 -0400154 };
155
Greg Daniel2ff202712018-06-14 11:50:10 -0400156 {
157 GET_PROC(EnumerateInstanceExtensionProperties);
158
159 uint32_t extensionCount = 0;
160 err = mEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);
Stan Iliev90276c82019-02-03 18:01:02 -0500161 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800162 mInstanceExtensionsOwner.resize(extensionCount);
163 err = mEnumerateInstanceExtensionProperties(nullptr, &extensionCount,
164 mInstanceExtensionsOwner.data());
Stan Iliev90276c82019-02-03 18:01:02 -0500165 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Greg Daniel2ff202712018-06-14 11:50:10 -0400166 bool hasKHRSurfaceExtension = false;
167 bool hasKHRAndroidSurfaceExtension = false;
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800168 for (const VkExtensionProperties& extension : mInstanceExtensionsOwner) {
John Reckf6067df2023-04-11 16:27:51 -0400169 if (!shouldEnableExtension(extension.extensionName)) {
170 ALOGV("Not enabling instance extension %s", extension.extensionName);
171 continue;
172 }
173 ALOGV("Enabling instance extension %s", extension.extensionName);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800174 mInstanceExtensions.push_back(extension.extensionName);
175 if (!strcmp(extension.extensionName, VK_KHR_SURFACE_EXTENSION_NAME)) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400176 hasKHRSurfaceExtension = true;
177 }
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800178 if (!strcmp(extension.extensionName, VK_KHR_ANDROID_SURFACE_EXTENSION_NAME)) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400179 hasKHRAndroidSurfaceExtension = true;
180 }
181 }
Stan Iliev90276c82019-02-03 18:01:02 -0500182 LOG_ALWAYS_FATAL_IF(!hasKHRSurfaceExtension || !hasKHRAndroidSurfaceExtension);
Greg Daniel2ff202712018-06-14 11:50:10 -0400183 }
184
185 const VkInstanceCreateInfo instance_create = {
John Reck0fa0cbc2019-04-05 16:57:46 -0700186 VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, // sType
187 nullptr, // pNext
188 0, // flags
189 &app_info, // pApplicationInfo
190 0, // enabledLayerNameCount
191 nullptr, // ppEnabledLayerNames
192 (uint32_t)mInstanceExtensions.size(), // enabledExtensionNameCount
193 mInstanceExtensions.data(), // ppEnabledExtensionNames
Greg Daniel2ff202712018-06-14 11:50:10 -0400194 };
195
196 GET_PROC(CreateInstance);
197 err = mCreateInstance(&instance_create, nullptr, &mInstance);
Stan Iliev90276c82019-02-03 18:01:02 -0500198 LOG_ALWAYS_FATAL_IF(err < 0);
Greg Daniel2ff202712018-06-14 11:50:10 -0400199
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700200 GET_INST_PROC(CreateDevice);
Greg Daniel2ff202712018-06-14 11:50:10 -0400201 GET_INST_PROC(DestroyInstance);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700202 GET_INST_PROC(EnumerateDeviceExtensionProperties);
Greg Daniel2ff202712018-06-14 11:50:10 -0400203 GET_INST_PROC(EnumeratePhysicalDevices);
Greg Daniela227dbb2018-08-20 09:19:48 -0400204 GET_INST_PROC(GetPhysicalDeviceFeatures2);
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500205 GET_INST_PROC(GetPhysicalDeviceImageFormatProperties2);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700206 GET_INST_PROC(GetPhysicalDeviceProperties);
207 GET_INST_PROC(GetPhysicalDeviceQueueFamilyProperties);
Greg Daniel2ff202712018-06-14 11:50:10 -0400208
209 uint32_t gpuCount;
Stan Iliev90276c82019-02-03 18:01:02 -0500210 LOG_ALWAYS_FATAL_IF(mEnumeratePhysicalDevices(mInstance, &gpuCount, nullptr));
211 LOG_ALWAYS_FATAL_IF(!gpuCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400212 // Just returning the first physical device instead of getting the whole array. Since there
213 // should only be one device on android.
214 gpuCount = 1;
215 err = mEnumeratePhysicalDevices(mInstance, &gpuCount, &mPhysicalDevice);
216 // VK_INCOMPLETE is returned when the count we provide is less than the total device count.
Stan Iliev90276c82019-02-03 18:01:02 -0500217 LOG_ALWAYS_FATAL_IF(err && VK_INCOMPLETE != err);
Greg Daniel2ff202712018-06-14 11:50:10 -0400218
Greg Daniel96259622018-10-01 14:42:56 -0400219 VkPhysicalDeviceProperties physDeviceProperties;
220 mGetPhysicalDeviceProperties(mPhysicalDevice, &physDeviceProperties);
Stan Iliev90276c82019-02-03 18:01:02 -0500221 LOG_ALWAYS_FATAL_IF(physDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0));
Stan Ilievbf99c442019-03-29 11:09:11 -0400222 mDriverVersion = physDeviceProperties.driverVersion;
Greg Daniel96259622018-10-01 14:42:56 -0400223
Greg Daniel2ff202712018-06-14 11:50:10 -0400224 // query to get the initial queue props size
Alec Mouri219997a2023-05-23 17:25:19 +0000225 uint32_t queueCount = 0;
Greg Daniel2ff202712018-06-14 11:50:10 -0400226 mGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
Stan Iliev90276c82019-02-03 18:01:02 -0500227 LOG_ALWAYS_FATAL_IF(!queueCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400228
229 // now get the actual queue props
230 std::unique_ptr<VkQueueFamilyProperties[]> queueProps(new VkQueueFamilyProperties[queueCount]);
231 mGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, queueProps.get());
232
Alec Mouri219997a2023-05-23 17:25:19 +0000233 constexpr auto kRequestedQueueCount = 2;
234
Greg Daniel2ff202712018-06-14 11:50:10 -0400235 // iterate to find the graphics queue
236 mGraphicsQueueIndex = queueCount;
237 for (uint32_t i = 0; i < queueCount; i++) {
238 if (queueProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
239 mGraphicsQueueIndex = i;
Alec Mouri219997a2023-05-23 17:25:19 +0000240 LOG_ALWAYS_FATAL_IF(queueProps[i].queueCount < kRequestedQueueCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400241 break;
242 }
243 }
Stan Iliev90276c82019-02-03 18:01:02 -0500244 LOG_ALWAYS_FATAL_IF(mGraphicsQueueIndex == queueCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400245
Greg Daniel2ff202712018-06-14 11:50:10 -0400246 {
247 uint32_t extensionCount = 0;
248 err = mEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr, &extensionCount,
John Reck0fa0cbc2019-04-05 16:57:46 -0700249 nullptr);
Stan Iliev90276c82019-02-03 18:01:02 -0500250 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800251 mDeviceExtensionsOwner.resize(extensionCount);
Greg Daniel2ff202712018-06-14 11:50:10 -0400252 err = mEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr, &extensionCount,
John Reck0fa0cbc2019-04-05 16:57:46 -0700253 mDeviceExtensionsOwner.data());
Stan Iliev90276c82019-02-03 18:01:02 -0500254 LOG_ALWAYS_FATAL_IF(VK_SUCCESS != err);
Greg Daniel2ff202712018-06-14 11:50:10 -0400255 bool hasKHRSwapchainExtension = false;
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800256 for (const VkExtensionProperties& extension : mDeviceExtensionsOwner) {
John Reckf6067df2023-04-11 16:27:51 -0400257 if (!shouldEnableExtension(extension.extensionName)) {
258 ALOGV("Not enabling device extension %s", extension.extensionName);
259 continue;
260 }
261 ALOGV("Enabling device extension %s", extension.extensionName);
Roman Kiryanov74ace839e2019-03-07 18:22:19 -0800262 mDeviceExtensions.push_back(extension.extensionName);
263 if (!strcmp(extension.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME)) {
Greg Daniel2ff202712018-06-14 11:50:10 -0400264 hasKHRSwapchainExtension = true;
265 }
266 }
Stan Iliev90276c82019-02-03 18:01:02 -0500267 LOG_ALWAYS_FATAL_IF(!hasKHRSwapchainExtension);
Greg Daniel2ff202712018-06-14 11:50:10 -0400268 }
269
Alec Mouri219997a2023-05-23 17:25:19 +0000270 auto getProc = [](const char* proc_name, VkInstance instance, VkDevice device) {
271 if (device != VK_NULL_HANDLE) {
272 return vkGetDeviceProcAddr(device, proc_name);
273 }
274 return vkGetInstanceProcAddr(instance, proc_name);
275 };
276
277 grExtensions.init(getProc, mInstance, mPhysicalDevice, mInstanceExtensions.size(),
John Reck0fa0cbc2019-04-05 16:57:46 -0700278 mInstanceExtensions.data(), mDeviceExtensions.size(),
279 mDeviceExtensions.data());
Greg Daniela227dbb2018-08-20 09:19:48 -0400280
Stan Iliev90276c82019-02-03 18:01:02 -0500281 LOG_ALWAYS_FATAL_IF(!grExtensions.hasExtension(VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME, 1));
Greg Daniel26e0dca2018-09-18 10:33:19 -0400282
Greg Daniela227dbb2018-08-20 09:19:48 -0400283 memset(&features, 0, sizeof(VkPhysicalDeviceFeatures2));
284 features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
285 features.pNext = nullptr;
286
287 // Setup all extension feature structs we may want to use.
288 void** tailPNext = &features.pNext;
289
290 if (grExtensions.hasExtension(VK_EXT_BLEND_OPERATION_ADVANCED_EXTENSION_NAME, 2)) {
291 VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT* blend;
John Reck0fa0cbc2019-04-05 16:57:46 -0700292 blend = (VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT*)malloc(
Greg Daniela227dbb2018-08-20 09:19:48 -0400293 sizeof(VkPhysicalDeviceBlendOperationAdvancedFeaturesEXT));
294 LOG_ALWAYS_FATAL_IF(!blend);
295 blend->sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT;
296 blend->pNext = nullptr;
297 *tailPNext = blend;
298 tailPNext = &blend->pNext;
299 }
300
Greg Daniel05036172018-11-28 17:08:04 -0500301 VkPhysicalDeviceSamplerYcbcrConversionFeatures* ycbcrFeature;
John Reck0fa0cbc2019-04-05 16:57:46 -0700302 ycbcrFeature = (VkPhysicalDeviceSamplerYcbcrConversionFeatures*)malloc(
Greg Daniel05036172018-11-28 17:08:04 -0500303 sizeof(VkPhysicalDeviceSamplerYcbcrConversionFeatures));
304 LOG_ALWAYS_FATAL_IF(!ycbcrFeature);
305 ycbcrFeature->sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES;
306 ycbcrFeature->pNext = nullptr;
307 *tailPNext = ycbcrFeature;
308 tailPNext = &ycbcrFeature->pNext;
309
Nolan Scobieddc9c662024-01-30 17:38:42 -0500310 if (grExtensions.hasExtension(VK_EXT_DEVICE_FAULT_EXTENSION_NAME, 1)) {
311 VkPhysicalDeviceFaultFeaturesEXT* deviceFaultFeatures =
312 new VkPhysicalDeviceFaultFeaturesEXT;
313 deviceFaultFeatures->sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT;
314 deviceFaultFeatures->pNext = nullptr;
315 *tailPNext = deviceFaultFeatures;
316 tailPNext = &deviceFaultFeatures->pNext;
317 }
318
Greg Daniela227dbb2018-08-20 09:19:48 -0400319 // query to get the physical device features
320 mGetPhysicalDeviceFeatures2(mPhysicalDevice, &features);
Greg Daniel2ff202712018-06-14 11:50:10 -0400321 // this looks like it would slow things down,
322 // and we can't depend on it on all platforms
Greg Daniela227dbb2018-08-20 09:19:48 -0400323 features.features.robustBufferAccess = VK_FALSE;
Greg Daniel2ff202712018-06-14 11:50:10 -0400324
Alec Mouri219997a2023-05-23 17:25:19 +0000325 float queuePriorities[kRequestedQueueCount] = {0.0};
Greg Daniel2ff202712018-06-14 11:50:10 -0400326
Stan Iliev7e733362019-02-28 13:16:36 -0500327 void* queueNextPtr = nullptr;
328
329 VkDeviceQueueGlobalPriorityCreateInfoEXT queuePriorityCreateInfo;
330
John Reck0fa0cbc2019-04-05 16:57:46 -0700331 if (Properties::contextPriority != 0 &&
332 grExtensions.hasExtension(VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME, 2)) {
Stan Iliev7e733362019-02-28 13:16:36 -0500333 memset(&queuePriorityCreateInfo, 0, sizeof(VkDeviceQueueGlobalPriorityCreateInfoEXT));
334 queuePriorityCreateInfo.sType =
John Reck0fa0cbc2019-04-05 16:57:46 -0700335 VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT;
Stan Iliev7e733362019-02-28 13:16:36 -0500336 queuePriorityCreateInfo.pNext = nullptr;
337 switch (Properties::contextPriority) {
338 case EGL_CONTEXT_PRIORITY_LOW_IMG:
339 queuePriorityCreateInfo.globalPriority = VK_QUEUE_GLOBAL_PRIORITY_LOW_EXT;
340 break;
341 case EGL_CONTEXT_PRIORITY_MEDIUM_IMG:
342 queuePriorityCreateInfo.globalPriority = VK_QUEUE_GLOBAL_PRIORITY_MEDIUM_EXT;
343 break;
344 case EGL_CONTEXT_PRIORITY_HIGH_IMG:
345 queuePriorityCreateInfo.globalPriority = VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT;
346 break;
347 default:
348 LOG_ALWAYS_FATAL("Unsupported context priority");
John Reck0fa0cbc2019-04-05 16:57:46 -0700349 }
350 queueNextPtr = &queuePriorityCreateInfo;
Stan Iliev7e733362019-02-28 13:16:36 -0500351 }
352
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700353 const VkDeviceQueueCreateInfo queueInfo = {
354 VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, // sType
355 queueNextPtr, // pNext
356 0, // VkDeviceQueueCreateFlags
357 mGraphicsQueueIndex, // queueFamilyIndex
Alec Mouri219997a2023-05-23 17:25:19 +0000358 kRequestedQueueCount, // queueCount
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700359 queuePriorities, // pQueuePriorities
360 };
Greg Daniel2ff202712018-06-14 11:50:10 -0400361
362 const VkDeviceCreateInfo deviceInfo = {
John Reck0fa0cbc2019-04-05 16:57:46 -0700363 VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, // sType
364 &features, // pNext
365 0, // VkDeviceCreateFlags
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700366 1, // queueCreateInfoCount
367 &queueInfo, // pQueueCreateInfos
John Reck0fa0cbc2019-04-05 16:57:46 -0700368 0, // layerCount
369 nullptr, // ppEnabledLayerNames
370 (uint32_t)mDeviceExtensions.size(), // extensionCount
371 mDeviceExtensions.data(), // ppEnabledExtensionNames
372 nullptr, // ppEnabledFeatures
Greg Daniel2ff202712018-06-14 11:50:10 -0400373 };
374
Stan Iliev90276c82019-02-03 18:01:02 -0500375 LOG_ALWAYS_FATAL_IF(mCreateDevice(mPhysicalDevice, &deviceInfo, nullptr, &mDevice));
Greg Daniel2ff202712018-06-14 11:50:10 -0400376
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500377 GET_DEV_PROC(AllocateCommandBuffers);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500378 GET_DEV_PROC(BeginCommandBuffer);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500379 GET_DEV_PROC(CmdPipelineBarrier);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700380 GET_DEV_PROC(CreateCommandPool);
381 GET_DEV_PROC(CreateFence);
382 GET_DEV_PROC(CreateSemaphore);
383 GET_DEV_PROC(DestroyCommandPool);
384 GET_DEV_PROC(DestroyDevice);
385 GET_DEV_PROC(DestroyFence);
386 GET_DEV_PROC(DestroySemaphore);
387 GET_DEV_PROC(DeviceWaitIdle);
388 GET_DEV_PROC(EndCommandBuffer);
389 GET_DEV_PROC(FreeCommandBuffers);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500390 GET_DEV_PROC(GetDeviceQueue);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700391 GET_DEV_PROC(GetSemaphoreFdKHR);
392 GET_DEV_PROC(ImportSemaphoreFdKHR);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500393 GET_DEV_PROC(QueueSubmit);
394 GET_DEV_PROC(QueueWaitIdle);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700395 GET_DEV_PROC(ResetCommandBuffer);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500396 GET_DEV_PROC(ResetFences);
Yiwei Zhang0b9f0b82019-08-15 11:33:59 -0700397 GET_DEV_PROC(WaitForFences);
Hugues Evrardb9510a02021-03-01 14:35:22 +0000398 GET_DEV_PROC(FrameBoundaryANDROID);
Greg Daniel2ff202712018-06-14 11:50:10 -0400399}
400
401void VulkanManager::initialize() {
Alec Mouri671a9f62023-08-25 17:18:02 +0000402 std::call_once(mInitFlag, [&] {
403 GET_PROC(EnumerateInstanceVersion);
404 uint32_t instanceVersion;
405 LOG_ALWAYS_FATAL_IF(mEnumerateInstanceVersion(&instanceVersion));
406 LOG_ALWAYS_FATAL_IF(instanceVersion < VK_MAKE_VERSION(1, 1, 0));
Greg Daniel1d9de712021-05-14 09:28:34 -0400407
Alec Mouri671a9f62023-08-25 17:18:02 +0000408 this->setupDevice(mExtensions, mPhysicalDeviceFeatures2);
Greg Daniel2ff202712018-06-14 11:50:10 -0400409
Alec Mouri671a9f62023-08-25 17:18:02 +0000410 mGetDeviceQueue(mDevice, mGraphicsQueueIndex, 0, &mGraphicsQueue);
411 mGetDeviceQueue(mDevice, mGraphicsQueueIndex, 1, &mAHBUploadQueue);
Greg Daniela227dbb2018-08-20 09:19:48 -0400412
Alec Mouri671a9f62023-08-25 17:18:02 +0000413 if (Properties::enablePartialUpdates && Properties::useBufferAge) {
414 mSwapBehavior = SwapBehavior::BufferAge;
415 }
Greg Daniel2ff202712018-06-14 11:50:10 -0400416
Alec Mouri671a9f62023-08-25 17:18:02 +0000417 mInitialized = true;
418 });
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500419}
420
Nolan Scobieddc9c662024-01-30 17:38:42 -0500421namespace {
422void onVkDeviceFault(const std::string& contextLabel, const std::string& description,
423 const std::vector<VkDeviceFaultAddressInfoEXT>& addressInfos,
424 const std::vector<VkDeviceFaultVendorInfoEXT>& vendorInfos,
425 const std::vector<std::byte>& vendorBinaryData) {
426 // The final crash string should contain as much differentiating info as possible, up to 1024
427 // bytes. As this final message is constructed, the same information is also dumped to the logs
428 // but in a more verbose format. Building the crash string is unsightly, so the clearer logging
429 // statement is always placed first to give context.
430 ALOGE("VK_ERROR_DEVICE_LOST (%s context): %s", contextLabel.c_str(), description.c_str());
431 std::stringstream crashMsg;
432 crashMsg << "VK_ERROR_DEVICE_LOST (" << contextLabel;
433
434 if (!addressInfos.empty()) {
435 ALOGE("%zu VkDeviceFaultAddressInfoEXT:", addressInfos.size());
436 crashMsg << ", " << addressInfos.size() << " address info (";
437 for (VkDeviceFaultAddressInfoEXT addressInfo : addressInfos) {
438 ALOGE(" addressType: %d", (int)addressInfo.addressType);
439 ALOGE(" reportedAddress: %" PRIu64, addressInfo.reportedAddress);
440 ALOGE(" addressPrecision: %" PRIu64, addressInfo.addressPrecision);
441 crashMsg << addressInfo.addressType << ":"
442 << addressInfo.reportedAddress << ":"
443 << addressInfo.addressPrecision << ", ";
444 }
445 crashMsg.seekp(-2, crashMsg.cur); // Move back to overwrite trailing ", "
446 crashMsg << ")";
447 }
448
449 if (!vendorInfos.empty()) {
450 ALOGE("%zu VkDeviceFaultVendorInfoEXT:", vendorInfos.size());
451 crashMsg << ", " << vendorInfos.size() << " vendor info (";
452 for (VkDeviceFaultVendorInfoEXT vendorInfo : vendorInfos) {
453 ALOGE(" description: %s", vendorInfo.description);
454 ALOGE(" vendorFaultCode: %" PRIu64, vendorInfo.vendorFaultCode);
455 ALOGE(" vendorFaultData: %" PRIu64, vendorInfo.vendorFaultData);
456 // Omit descriptions for individual vendor info structs in the crash string, as the
457 // fault code and fault data fields should be enough for clustering, and the verbosity
458 // isn't worth it. Additionally, vendors may just set the general description field of
459 // the overall fault to the description of the first element in this list, and that
460 // overall description will be placed at the end of the crash string.
461 crashMsg << vendorInfo.vendorFaultCode << ":"
462 << vendorInfo.vendorFaultData << ", ";
463 }
464 crashMsg.seekp(-2, crashMsg.cur); // Move back to overwrite trailing ", "
465 crashMsg << ")";
466 }
467
468 if (!vendorBinaryData.empty()) {
469 // TODO: b/322830575 - Log in base64, or dump directly to a file that gets put in bugreports
470 ALOGE("%zu bytes of vendor-specific binary data (please notify Android's Core Graphics"
471 " Stack team if you observe this message).",
472 vendorBinaryData.size());
473 crashMsg << ", " << vendorBinaryData.size() << " bytes binary";
474 }
475
476 crashMsg << "): " << description;
477 LOG_ALWAYS_FATAL("%s", crashMsg.str().c_str());
478}
479
480void deviceLostProcRenderThread(void* callbackContext, const std::string& description,
481 const std::vector<VkDeviceFaultAddressInfoEXT>& addressInfos,
482 const std::vector<VkDeviceFaultVendorInfoEXT>& vendorInfos,
483 const std::vector<std::byte>& vendorBinaryData) {
484 onVkDeviceFault("RenderThread", description, addressInfos, vendorInfos, vendorBinaryData);
485}
486void deviceLostProcUploadThread(void* callbackContext, const std::string& description,
487 const std::vector<VkDeviceFaultAddressInfoEXT>& addressInfos,
488 const std::vector<VkDeviceFaultVendorInfoEXT>& vendorInfos,
489 const std::vector<std::byte>& vendorBinaryData) {
490 onVkDeviceFault("UploadThread", description, addressInfos, vendorInfos, vendorBinaryData);
491}
492} // anonymous namespace
493
John Reck9fc3d272023-05-01 16:33:22 -0400494static void onGrContextReleased(void* context) {
495 VulkanManager* manager = (VulkanManager*)context;
496 manager->decStrong((void*)onGrContextReleased);
497}
Stan Iliev981afe72019-02-13 14:24:33 -0500498
John Reck9fc3d272023-05-01 16:33:22 -0400499sk_sp<GrDirectContext> VulkanManager::createContext(GrContextOptions& options,
500 ContextType contextType) {
Alec Mouri219997a2023-05-23 17:25:19 +0000501 auto getProc = [](const char* proc_name, VkInstance instance, VkDevice device) {
502 if (device != VK_NULL_HANDLE) {
503 return vkGetDeviceProcAddr(device, proc_name);
504 }
505 return vkGetInstanceProcAddr(instance, proc_name);
506 };
507
Stan Iliev981afe72019-02-13 14:24:33 -0500508 GrVkBackendContext backendContext;
509 backendContext.fInstance = mInstance;
510 backendContext.fPhysicalDevice = mPhysicalDevice;
511 backendContext.fDevice = mDevice;
Alec Mouri219997a2023-05-23 17:25:19 +0000512 backendContext.fQueue =
513 (contextType == ContextType::kRenderThread) ? mGraphicsQueue : mAHBUploadQueue;
Stan Iliev981afe72019-02-13 14:24:33 -0500514 backendContext.fGraphicsQueueIndex = mGraphicsQueueIndex;
515 backendContext.fMaxAPIVersion = mAPIVersion;
516 backendContext.fVkExtensions = &mExtensions;
517 backendContext.fDeviceFeatures2 = &mPhysicalDeviceFeatures2;
Alec Mouri219997a2023-05-23 17:25:19 +0000518 backendContext.fGetProc = std::move(getProc);
Nolan Scobieddc9c662024-01-30 17:38:42 -0500519 backendContext.fDeviceLostContext = nullptr;
520 backendContext.fDeviceLostProc = (contextType == ContextType::kRenderThread)
521 ? deviceLostProcRenderThread
522 : deviceLostProcUploadThread;
Stan Iliev981afe72019-02-13 14:24:33 -0500523
John Reck9fc3d272023-05-01 16:33:22 -0400524 LOG_ALWAYS_FATAL_IF(options.fContextDeleteProc != nullptr, "Conflicting fContextDeleteProcs!");
525 this->incStrong((void*)onGrContextReleased);
526 options.fContextDeleteContext = this;
527 options.fContextDeleteProc = onGrContextReleased;
528
Kevin Lubickf6b21952023-10-13 13:12:17 +0000529 return GrDirectContexts::MakeVulkan(backendContext, options);
Stan Iliev981afe72019-02-13 14:24:33 -0500530}
531
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800532VkFunctorInitParams VulkanManager::getVkFunctorInitParams() const {
533 return VkFunctorInitParams{
534 .instance = mInstance,
535 .physical_device = mPhysicalDevice,
536 .device = mDevice,
537 .queue = mGraphicsQueue,
538 .graphics_queue_index = mGraphicsQueueIndex,
Greg Danieleaf310e2019-01-28 16:10:32 -0500539 .api_version = mAPIVersion,
Bo Liu7b8c1eb2019-01-08 20:17:55 -0800540 .enabled_instance_extension_names = mInstanceExtensions.data(),
541 .enabled_instance_extension_names_length =
542 static_cast<uint32_t>(mInstanceExtensions.size()),
543 .enabled_device_extension_names = mDeviceExtensions.data(),
544 .enabled_device_extension_names_length =
545 static_cast<uint32_t>(mDeviceExtensions.size()),
546 .device_features_2 = &mPhysicalDeviceFeatures2,
547 };
548}
549
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500550Frame VulkanManager::dequeueNextBuffer(VulkanSurface* surface) {
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500551 VulkanSurface::NativeBufferInfo* bufferInfo = surface->dequeueNativeBuffer();
552
553 if (bufferInfo == nullptr) {
554 ALOGE("VulkanSurface::dequeueNativeBuffer called with an invalid surface!");
555 return Frame(-1, -1, 0);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500556 }
557
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500558 LOG_ALWAYS_FATAL_IF(!bufferInfo->dequeued);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500559
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500560 if (bufferInfo->dequeue_fence != -1) {
Stan Iliev197843d2019-03-21 11:34:15 -0400561 struct sync_file_info* finfo = sync_file_info(bufferInfo->dequeue_fence);
562 bool isSignalPending = false;
563 if (finfo != NULL) {
564 isSignalPending = finfo->status != 1;
565 sync_file_info_free(finfo);
566 }
567 if (isSignalPending) {
568 int fence_clone = dup(bufferInfo->dequeue_fence);
569 if (fence_clone == -1) {
570 ALOGE("dup(fence) failed, stalling until signalled: %s (%d)", strerror(errno),
571 errno);
572 sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
573 } else {
574 VkSemaphoreCreateInfo semaphoreInfo;
575 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
576 semaphoreInfo.pNext = nullptr;
577 semaphoreInfo.flags = 0;
578 VkSemaphore semaphore;
579 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
Greg Danield6670772021-06-09 12:01:12 -0400580 if (err != VK_SUCCESS) {
581 ALOGE("Failed to create import semaphore, err: %d", err);
582 close(fence_clone);
583 sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
584 } else {
585 VkImportSemaphoreFdInfoKHR importInfo;
586 importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR;
587 importInfo.pNext = nullptr;
588 importInfo.semaphore = semaphore;
589 importInfo.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
590 importInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
591 importInfo.fd = fence_clone;
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500592
Greg Danield6670772021-06-09 12:01:12 -0400593 err = mImportSemaphoreFdKHR(mDevice, &importInfo);
594 if (err != VK_SUCCESS) {
595 ALOGE("Failed to import semaphore, err: %d", err);
596 mDestroySemaphore(mDevice, semaphore, nullptr);
597 close(fence_clone);
598 sync_wait(bufferInfo->dequeue_fence, -1 /* forever */);
599 } else {
600 GrBackendSemaphore backendSemaphore;
601 backendSemaphore.initVulkan(semaphore);
602 // Skia will take ownership of the VkSemaphore and delete it once the wait
603 // has finished. The VkSemaphore also owns the imported fd, so it will
604 // close the fd when it is deleted.
605 bufferInfo->skSurface->wait(1, &backendSemaphore);
606 // The following flush blocks the GPU immediately instead of waiting for
607 // other drawing ops. It seems dequeue_fence is not respected otherwise.
608 // TODO: remove the flush after finding why backendSemaphore is not working.
Kevin Lubickcae0b212023-09-12 18:33:10 +0000609 skgpu::ganesh::FlushAndSubmit(bufferInfo->skSurface.get());
Greg Danield6670772021-06-09 12:01:12 -0400610 }
611 }
Stan Iliev197843d2019-03-21 11:34:15 -0400612 }
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500613 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500614 }
615
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500616 int bufferAge = (mSwapBehavior == SwapBehavior::Discard) ? 0 : surface->getCurrentBuffersAge();
617 return Frame(surface->logicalWidth(), surface->logicalHeight(), bufferAge);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500618}
619
John Reck4db23fd2023-11-10 15:31:49 -0500620class SharedSemaphoreInfo : public LightRefBase<SharedSemaphoreInfo> {
Greg Danield92a9b12019-04-23 10:11:04 -0400621 PFN_vkDestroySemaphore mDestroyFunction;
622 VkDevice mDevice;
623 VkSemaphore mSemaphore;
John Reck4db23fd2023-11-10 15:31:49 -0500624 GrBackendSemaphore mGrBackendSemaphore;
Greg Danield92a9b12019-04-23 10:11:04 -0400625
John Reck4db23fd2023-11-10 15:31:49 -0500626 SharedSemaphoreInfo(PFN_vkDestroySemaphore destroyFunction, VkDevice device,
627 VkSemaphore semaphore)
628 : mDestroyFunction(destroyFunction), mDevice(device), mSemaphore(semaphore) {
629 mGrBackendSemaphore.initVulkan(semaphore);
630 }
John Reck5d3fac12023-11-08 23:08:10 -0500631
John Reck4db23fd2023-11-10 15:31:49 -0500632 ~SharedSemaphoreInfo() { mDestroyFunction(mDevice, mSemaphore, nullptr); }
633
634 friend class LightRefBase<SharedSemaphoreInfo>;
635 friend class sp<SharedSemaphoreInfo>;
636
637public:
638 VkSemaphore semaphore() const { return mSemaphore; }
639
640 GrBackendSemaphore* grBackendSemaphore() { return &mGrBackendSemaphore; }
Greg Danield92a9b12019-04-23 10:11:04 -0400641};
642
643static void destroy_semaphore(void* context) {
John Reck4db23fd2023-11-10 15:31:49 -0500644 SharedSemaphoreInfo* info = reinterpret_cast<SharedSemaphoreInfo*>(context);
645 info->decStrong(0);
Greg Danield92a9b12019-04-23 10:11:04 -0400646}
647
John Reck5d3fac12023-11-08 23:08:10 -0500648VulkanManager::VkDrawResult VulkanManager::finishFrame(SkSurface* surface) {
Greg Danielbe2803a2021-02-19 18:32:16 -0500649 ATRACE_NAME("Vulkan finish frame");
Stan Ilievbc5f06b2019-03-26 15:14:34 -0400650
John Reck4db23fd2023-11-10 15:31:49 -0500651 sp<SharedSemaphoreInfo> sharedSemaphore;
Greg Danielc7ad4082020-05-14 15:38:26 -0400652 GrFlushInfo flushInfo;
John Reck4db23fd2023-11-10 15:31:49 -0500653
654 {
655 VkExportSemaphoreCreateInfo exportInfo;
656 exportInfo.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO;
657 exportInfo.pNext = nullptr;
658 exportInfo.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
659
660 VkSemaphoreCreateInfo semaphoreInfo;
661 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
662 semaphoreInfo.pNext = &exportInfo;
663 semaphoreInfo.flags = 0;
664 VkSemaphore semaphore;
665 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
666 ALOGE_IF(VK_SUCCESS != err,
667 "VulkanManager::makeSwapSemaphore(): Failed to create semaphore");
668
669 if (err == VK_SUCCESS) {
670 sharedSemaphore = sp<SharedSemaphoreInfo>::make(mDestroySemaphore, mDevice, semaphore);
671 flushInfo.fNumSemaphores = 1;
672 flushInfo.fSignalSemaphores = sharedSemaphore->grBackendSemaphore();
673 flushInfo.fFinishedProc = destroy_semaphore;
674 sharedSemaphore->incStrong(0);
675 flushInfo.fFinishedContext = sharedSemaphore.get();
676 }
Greg Danielbe2803a2021-02-19 18:32:16 -0500677 }
John Reck4db23fd2023-11-10 15:31:49 -0500678
Greg Danielbe2803a2021-02-19 18:32:16 -0500679 GrDirectContext* context = GrAsDirectContext(surface->recordingContext());
Adlai Holler0375fee2020-09-15 12:31:22 -0400680 ALOGE_IF(!context, "Surface is not backed by gpu");
Kevin Lubickaa592d02023-05-30 15:07:06 +0000681 GrSemaphoresSubmitted submitted = context->flush(
682 surface, SkSurfaces::BackendSurfaceAccess::kPresent, flushInfo);
Adlai Holler0375fee2020-09-15 12:31:22 -0400683 context->submit();
John Reck5d3fac12023-11-08 23:08:10 -0500684 VkDrawResult drawResult{
685 .submissionTime = systemTime(),
686 };
John Reck4db23fd2023-11-10 15:31:49 -0500687 if (sharedSemaphore) {
688 if (submitted == GrSemaphoresSubmitted::kYes && mFrameBoundaryANDROID) {
689 // retrieve VkImage used as render target
690 VkImage image = VK_NULL_HANDLE;
691 GrBackendRenderTarget backendRenderTarget = SkSurfaces::GetBackendRenderTarget(
692 surface, SkSurfaces::BackendHandleAccess::kFlushRead);
693 if (backendRenderTarget.isValid()) {
694 GrVkImageInfo info;
695 if (GrBackendRenderTargets::GetVkImageInfo(backendRenderTarget, &info)) {
696 image = info.fImage;
Hugues Evrardb9510a02021-03-01 14:35:22 +0000697 } else {
John Reck4db23fd2023-11-10 15:31:49 -0500698 ALOGE("Frame boundary: backend is not vulkan");
Hugues Evrardb9510a02021-03-01 14:35:22 +0000699 }
John Reck4db23fd2023-11-10 15:31:49 -0500700 } else {
701 ALOGE("Frame boundary: invalid backend render target");
Hugues Evrardb9510a02021-03-01 14:35:22 +0000702 }
John Reck4db23fd2023-11-10 15:31:49 -0500703 // frameBoundaryANDROID needs to know about mSwapSemaphore, but
704 // it won't wait on it.
705 mFrameBoundaryANDROID(mDevice, sharedSemaphore->semaphore(), image);
Greg Danielbe2803a2021-02-19 18:32:16 -0500706 }
John Reck5d3fac12023-11-08 23:08:10 -0500707 VkSemaphoreGetFdInfoKHR getFdInfo;
708 getFdInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR;
709 getFdInfo.pNext = nullptr;
John Reck4db23fd2023-11-10 15:31:49 -0500710 getFdInfo.semaphore = sharedSemaphore->semaphore();
John Reck5d3fac12023-11-08 23:08:10 -0500711 getFdInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
712
713 int fenceFd = -1;
John Reck4db23fd2023-11-10 15:31:49 -0500714 VkResult err = mGetSemaphoreFdKHR(mDevice, &getFdInfo, &fenceFd);
John Reck5d3fac12023-11-08 23:08:10 -0500715 ALOGE_IF(VK_SUCCESS != err, "VulkanManager::swapBuffers(): Failed to get semaphore Fd");
716 drawResult.presentFence.reset(fenceFd);
717 } else {
718 ALOGE("VulkanManager::finishFrame(): Semaphore submission failed");
719 mQueueWaitIdle(mGraphicsQueue);
Greg Danielbe2803a2021-02-19 18:32:16 -0500720 }
John Reck5d3fac12023-11-08 23:08:10 -0500721
Greg Danielbe2803a2021-02-19 18:32:16 -0500722 skiapipeline::ShaderCache::get().onVkFrameFlushed(context);
Alec Mouri3afb3972022-05-27 22:03:11 +0000723
John Reck5d3fac12023-11-08 23:08:10 -0500724 return drawResult;
Greg Danielbe2803a2021-02-19 18:32:16 -0500725}
726
John Reck5d3fac12023-11-08 23:08:10 -0500727void VulkanManager::swapBuffers(VulkanSurface* surface, const SkRect& dirtyRect,
728 android::base::unique_fd&& presentFence) {
Greg Danielbe2803a2021-02-19 18:32:16 -0500729 if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
730 ATRACE_NAME("Finishing GPU work");
731 mDeviceWaitIdle(mDevice);
732 }
733
John Reck5d3fac12023-11-08 23:08:10 -0500734 surface->presentCurrentBuffer(dirtyRect, presentFence.release());
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500735}
736
737void VulkanManager::destroySurface(VulkanSurface* surface) {
738 // Make sure all submit commands have finished before starting to destroy objects.
Yiwei Zhang276d5fc2020-09-03 12:00:00 -0700739 if (VK_NULL_HANDLE != mGraphicsQueue) {
740 mQueueWaitIdle(mGraphicsQueue);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500741 }
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500742
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500743 delete surface;
744}
745
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400746VulkanSurface* VulkanManager::createSurface(ANativeWindow* window,
747 ColorMode colorMode,
Peiyong Lin3bff1352018-12-11 07:56:07 -0800748 sk_sp<SkColorSpace> surfaceColorSpace,
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400749 SkColorType surfaceColorType,
750 GrDirectContext* grContext,
John Reck0fa0cbc2019-04-05 16:57:46 -0700751 uint32_t extraBuffers) {
Stan Iliev981afe72019-02-13 14:24:33 -0500752 LOG_ALWAYS_FATAL_IF(!hasVkContext(), "Not initialized");
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500753 if (!window) {
754 return nullptr;
755 }
756
Derek Sollenbergera19b71a2019-02-15 16:36:30 -0500757 return VulkanSurface::Create(window, colorMode, surfaceColorType, surfaceColorSpace, grContext,
John Reck0fa0cbc2019-04-05 16:57:46 -0700758 *this, extraBuffers);
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500759}
760
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400761status_t VulkanManager::fenceWait(int fence, GrDirectContext* grContext) {
Greg Daniel26e0dca2018-09-18 10:33:19 -0400762 if (!hasVkContext()) {
763 ALOGE("VulkanManager::fenceWait: VkDevice not initialized");
764 return INVALID_OPERATION;
765 }
766
Stan Iliev7a081272018-10-26 17:54:18 -0400767 // Block GPU on the fence.
Stan Ilievaaa9e832019-09-17 14:07:23 -0400768 int fenceFd = ::dup(fence);
Stan Iliev7a081272018-10-26 17:54:18 -0400769 if (fenceFd == -1) {
770 ALOGE("VulkanManager::fenceWait: error dup'ing fence fd: %d", errno);
771 return -errno;
Stan Iliev564ca3e2018-09-04 22:00:00 +0000772 }
Stan Iliev7a081272018-10-26 17:54:18 -0400773
774 VkSemaphoreCreateInfo semaphoreInfo;
775 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
776 semaphoreInfo.pNext = nullptr;
777 semaphoreInfo.flags = 0;
778 VkSemaphore semaphore;
779 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
780 if (VK_SUCCESS != err) {
Greg Danield6670772021-06-09 12:01:12 -0400781 close(fenceFd);
Stan Iliev7a081272018-10-26 17:54:18 -0400782 ALOGE("Failed to create import semaphore, err: %d", err);
783 return UNKNOWN_ERROR;
784 }
785 VkImportSemaphoreFdInfoKHR importInfo;
786 importInfo.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR;
787 importInfo.pNext = nullptr;
788 importInfo.semaphore = semaphore;
789 importInfo.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT;
790 importInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
791 importInfo.fd = fenceFd;
792
793 err = mImportSemaphoreFdKHR(mDevice, &importInfo);
794 if (VK_SUCCESS != err) {
Greg Danield92a9b12019-04-23 10:11:04 -0400795 mDestroySemaphore(mDevice, semaphore, nullptr);
Greg Danield6670772021-06-09 12:01:12 -0400796 close(fenceFd);
Stan Iliev7a081272018-10-26 17:54:18 -0400797 ALOGE("Failed to import semaphore, err: %d", err);
798 return UNKNOWN_ERROR;
799 }
800
Greg Danield92a9b12019-04-23 10:11:04 -0400801 GrBackendSemaphore beSemaphore;
802 beSemaphore.initVulkan(semaphore);
Stan Iliev7a081272018-10-26 17:54:18 -0400803
Greg Danield6670772021-06-09 12:01:12 -0400804 // Skia will take ownership of the VkSemaphore and delete it once the wait has finished. The
805 // VkSemaphore also owns the imported fd, so it will close the fd when it is deleted.
Greg Danield92a9b12019-04-23 10:11:04 -0400806 grContext->wait(1, &beSemaphore);
Greg Danielc7ad4082020-05-14 15:38:26 -0400807 grContext->flushAndSubmit();
Stan Iliev7a081272018-10-26 17:54:18 -0400808
Stan Iliev564ca3e2018-09-04 22:00:00 +0000809 return OK;
810}
811
Adlai Hollerf8c434e2020-07-27 11:42:45 -0400812status_t VulkanManager::createReleaseFence(int* nativeFence, GrDirectContext* grContext) {
Stan Ilievaaa9e832019-09-17 14:07:23 -0400813 *nativeFence = -1;
Greg Daniel26e0dca2018-09-18 10:33:19 -0400814 if (!hasVkContext()) {
815 ALOGE("VulkanManager::createReleaseFence: VkDevice not initialized");
816 return INVALID_OPERATION;
817 }
818
Greg Daniel26e0dca2018-09-18 10:33:19 -0400819 VkExportSemaphoreCreateInfo exportInfo;
820 exportInfo.sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO;
821 exportInfo.pNext = nullptr;
822 exportInfo.handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
823
824 VkSemaphoreCreateInfo semaphoreInfo;
825 semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
826 semaphoreInfo.pNext = &exportInfo;
827 semaphoreInfo.flags = 0;
828 VkSemaphore semaphore;
829 VkResult err = mCreateSemaphore(mDevice, &semaphoreInfo, nullptr, &semaphore);
830 if (VK_SUCCESS != err) {
831 ALOGE("VulkanManager::createReleaseFence: Failed to create semaphore");
832 return INVALID_OPERATION;
833 }
834
John Reck4db23fd2023-11-10 15:31:49 -0500835 auto sharedSemaphore = sp<SharedSemaphoreInfo>::make(mDestroySemaphore, mDevice, semaphore);
Greg Daniel26e0dca2018-09-18 10:33:19 -0400836
Greg Danielfd429392019-05-09 15:44:56 -0400837 // Even if Skia fails to submit the semaphore, it will still call the destroy_semaphore callback
Greg Danielc7ad4082020-05-14 15:38:26 -0400838 GrFlushInfo flushInfo;
839 flushInfo.fNumSemaphores = 1;
John Reck4db23fd2023-11-10 15:31:49 -0500840 flushInfo.fSignalSemaphores = sharedSemaphore->grBackendSemaphore();
Greg Danielc7ad4082020-05-14 15:38:26 -0400841 flushInfo.fFinishedProc = destroy_semaphore;
John Reck4db23fd2023-11-10 15:31:49 -0500842 sharedSemaphore->incStrong(0);
843 flushInfo.fFinishedContext = sharedSemaphore.get();
Greg Danielc7ad4082020-05-14 15:38:26 -0400844 GrSemaphoresSubmitted submitted = grContext->flush(flushInfo);
845 grContext->submit();
Greg Daniel26e0dca2018-09-18 10:33:19 -0400846
Greg Danield92a9b12019-04-23 10:11:04 -0400847 if (submitted == GrSemaphoresSubmitted::kNo) {
848 ALOGE("VulkanManager::createReleaseFence: Failed to submit semaphore");
Greg Danield92a9b12019-04-23 10:11:04 -0400849 return INVALID_OPERATION;
850 }
Greg Daniel26e0dca2018-09-18 10:33:19 -0400851
852 VkSemaphoreGetFdInfoKHR getFdInfo;
853 getFdInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR;
854 getFdInfo.pNext = nullptr;
855 getFdInfo.semaphore = semaphore;
856 getFdInfo.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT;
857
858 int fenceFd = 0;
859
860 err = mGetSemaphoreFdKHR(mDevice, &getFdInfo, &fenceFd);
861 if (VK_SUCCESS != err) {
862 ALOGE("VulkanManager::createReleaseFence: Failed to get semaphore Fd");
863 return INVALID_OPERATION;
864 }
Stan Ilievaaa9e832019-09-17 14:07:23 -0400865 *nativeFence = fenceFd;
Greg Daniel26e0dca2018-09-18 10:33:19 -0400866
Stan Iliev564ca3e2018-09-04 22:00:00 +0000867 return OK;
868}
869
Derek Sollenberger0e3cba32016-11-09 11:58:36 -0500870} /* namespace renderthread */
871} /* namespace uirenderer */
872} /* namespace android */