blob: 9ce020a937f6505e1b07e4266284532e092347c2 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Shahbaz Youssefi61656022018-10-24 15:00:50 -040034#include "third_party/trace_event/trace_event.h"
35
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070036// Consts
37namespace
38{
Jamie Madill7c985f52018-11-29 18:16:17 -050039const uint32_t kMockVendorID = 0xba5eba11;
40const uint32_t kMockDeviceID = 0xf005ba11;
41constexpr char kMockDeviceName[] = "Vulkan Mock Device";
42constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050043constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070044} // anonymous namespace
45
Jamie Madill9e54b5a2016-05-25 12:57:39 -040046namespace rx
47{
48
Jamie Madille09bd5d2016-11-29 16:20:35 -050049namespace
50{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040051// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
52// one for the vertex shader.
53constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040054// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050055constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040056// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050057constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050058
Omar El Sheikh26c61b22018-06-29 12:50:59 -060059bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
60{
61#if !defined(ANGLE_PLATFORM_ANDROID)
62 // Mock ICD does not currently run on Android
63 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
64 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
66#else
67 return false;
68#endif // !defined(ANGLE_PLATFORM_ANDROID)
69}
70
Jamie Madille09bd5d2016-11-29 16:20:35 -050071VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
72 const std::vector<const char *> &enabledExtensionNames)
73{
74 // Compile the extensions names into a set.
75 std::set<std::string> extensionNames;
76 for (const auto &extensionProp : extensionProps)
77 {
78 extensionNames.insert(extensionProp.extensionName);
79 }
80
Jamie Madillacf2f3a2017-11-21 19:22:44 -050081 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050082 {
83 if (extensionNames.count(extensionName) == 0)
84 {
85 return VK_ERROR_EXTENSION_NOT_PRESENT;
86 }
87 }
88
89 return VK_SUCCESS;
90}
91
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050092bool ExtensionFound(const char *extensionName,
93 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060094{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050095 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060096 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050097 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060098 {
99 return true;
100 }
101 }
102 return false;
103}
104
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500105// Array of Validation error/warning messages that will be ignored, should include bugID
106constexpr std::array<const char *, 1> kSkippedMessages = {
107 // http://anglebug.com/2796
108 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
109
110// Suppress validation errors that are known
111// return "true" if given code/prefix/message is known, else return "false"
112bool IsIgnoredDebugMessage(const char *message)
113{
Michael Spang25839802019-01-30 18:02:51 -0500114 if (!message)
115 {
116 return false;
117 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500118 for (const char *msg : kSkippedMessages)
119 {
120 if (strstr(message, msg) != nullptr)
121 {
122 return true;
123 }
124 }
125 return false;
126}
127
128const char *GetVkObjectTypeName(VkObjectType type)
129{
130 switch (type)
131 {
132 case VK_OBJECT_TYPE_UNKNOWN:
133 return "Unknown";
134 case VK_OBJECT_TYPE_INSTANCE:
135 return "Instance";
136 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
137 return "Physical Device";
138 case VK_OBJECT_TYPE_DEVICE:
139 return "Device";
140 case VK_OBJECT_TYPE_QUEUE:
141 return "Queue";
142 case VK_OBJECT_TYPE_SEMAPHORE:
143 return "Semaphore";
144 case VK_OBJECT_TYPE_COMMAND_BUFFER:
145 return "Command Buffer";
146 case VK_OBJECT_TYPE_FENCE:
147 return "Fence";
148 case VK_OBJECT_TYPE_DEVICE_MEMORY:
149 return "Device Memory";
150 case VK_OBJECT_TYPE_BUFFER:
151 return "Buffer";
152 case VK_OBJECT_TYPE_IMAGE:
153 return "Image";
154 case VK_OBJECT_TYPE_EVENT:
155 return "Event";
156 case VK_OBJECT_TYPE_QUERY_POOL:
157 return "Query Pool";
158 case VK_OBJECT_TYPE_BUFFER_VIEW:
159 return "Buffer View";
160 case VK_OBJECT_TYPE_IMAGE_VIEW:
161 return "Image View";
162 case VK_OBJECT_TYPE_SHADER_MODULE:
163 return "Shader Module";
164 case VK_OBJECT_TYPE_PIPELINE_CACHE:
165 return "Pipeline Cache";
166 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
167 return "Pipeline Layout";
168 case VK_OBJECT_TYPE_RENDER_PASS:
169 return "Render Pass";
170 case VK_OBJECT_TYPE_PIPELINE:
171 return "Pipeline";
172 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
173 return "Descriptor Set Layout";
174 case VK_OBJECT_TYPE_SAMPLER:
175 return "Sampler";
176 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
177 return "Descriptor Pool";
178 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
179 return "Descriptor Set";
180 case VK_OBJECT_TYPE_FRAMEBUFFER:
181 return "Framebuffer";
182 case VK_OBJECT_TYPE_COMMAND_POOL:
183 return "Command Pool";
184 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
185 return "Sampler YCbCr Conversion";
186 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
187 return "Descriptor Update Template";
188 case VK_OBJECT_TYPE_SURFACE_KHR:
189 return "Surface";
190 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
191 return "Swapchain";
192 case VK_OBJECT_TYPE_DISPLAY_KHR:
193 return "Display";
194 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
195 return "Display Mode";
196 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
197 return "Debug Report Callback";
198 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
199 return "Object Table";
200 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
201 return "Indirect Commands Layout";
202 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
203 return "Debug Utils Messenger";
204 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
205 return "Validation Cache";
206 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
207 return "Acceleration Structure";
208 default:
209 return "<Unrecognized>";
210 }
211}
212
213VKAPI_ATTR VkBool32 VKAPI_CALL
214DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
215 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
216 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
217 void *userData)
218{
219 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
220 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
221 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
222
223 // Check if we even care about this message.
224 if ((messageSeverity & kSeveritiesToLog) == 0)
225 {
226 return VK_FALSE;
227 }
228
229 // See if it's an issue we are aware of and don't want to be spammed about.
230 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
231 {
232 return VK_FALSE;
233 }
234
235 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500236 if (callbackData->pMessageIdName)
237 {
238 log << "[ " << callbackData->pMessageIdName << " ] ";
239 }
240 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500241
242 // Aesthetic value based on length of the function name, line number, etc.
243 constexpr size_t kStartIndent = 28;
244
245 // Output the debug marker hierarchy under which this error has occured.
246 size_t indent = kStartIndent;
247 if (callbackData->queueLabelCount > 0)
248 {
249 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
250 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
251 {
252 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
253 << std::endl;
254 }
255 }
256 if (callbackData->cmdBufLabelCount > 0)
257 {
258 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
259 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
260 {
261 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
262 << std::endl;
263 }
264 }
265 // Output the objects involved in this error message.
266 if (callbackData->objectCount > 0)
267 {
268 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
269 {
270 const char *objectName = callbackData->pObjects[i].pObjectName;
271 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
272 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
273 log << std::string(indent, ' ') << "Object: ";
274 if (objectHandle == 0)
275 {
276 log << "VK_NULL_HANDLE";
277 }
278 else
279 {
280 log << "0x" << std::hex << objectHandle << std::dec;
281 }
282 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
283 if (objectName)
284 {
285 log << " [" << objectName << "]";
286 }
287 log << std::endl;
288 }
289 }
290
Jamie Madill54ed8f02019-02-11 12:32:04 -0500291 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
292 std::string msg = log.str();
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500293
294 if (isError)
295 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500296 ERR() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500297 }
298 else
299 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500300 WARN() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500301 }
302
303 return VK_FALSE;
304}
305
Yuly Novikov199f4292018-01-19 19:04:05 -0500306VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
307 VkDebugReportObjectTypeEXT objectType,
308 uint64_t object,
309 size_t location,
310 int32_t messageCode,
311 const char *layerPrefix,
312 const char *message,
313 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500314{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600315 if (IsIgnoredDebugMessage(message))
316 {
317 return VK_FALSE;
318 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500319 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
320 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500321 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500322#if !defined(NDEBUG)
323 // Abort the call in Debug builds.
324 return VK_TRUE;
325#endif
326 }
327 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
328 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500329 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500330 }
331 else
332 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500333 // Uncomment this if you want Vulkan spam.
334 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500335 }
336
337 return VK_FALSE;
338}
339
Yuly Novikov199f4292018-01-19 19:04:05 -0500340// If we're loading the validation layers, we could be running from any random directory.
341// Change to the executable directory so we can find the layers, then change back to the
342// previous directory to be safe we don't disrupt the application.
343class ScopedVkLoaderEnvironment : angle::NonCopyable
344{
345 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600346 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
347 : mEnableValidationLayers(enableValidationLayers),
348 mEnableMockICD(enableMockICD),
349 mChangedCWD(false),
350 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500351 {
352// Changing CWD and setting environment variables makes no sense on Android,
353// since this code is a part of Java application there.
354// Android Vulkan loader doesn't need this either.
355#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600356 if (enableMockICD)
357 {
358 // Override environment variable to use built Mock ICD
359 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
360 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
361 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
362 if (!mChangedICDPath)
363 {
364 ERR() << "Error setting Path for Mock/Null Driver.";
365 mEnableMockICD = false;
366 }
367 }
Jamie Madill46848422018-08-09 10:46:06 -0400368 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500369 {
370 const auto &cwd = angle::GetCWD();
371 if (!cwd.valid())
372 {
373 ERR() << "Error getting CWD for Vulkan layers init.";
374 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400375 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500376 }
377 else
378 {
379 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500380 std::string exeDir = angle::GetExecutableDirectory();
381 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500382 if (!mChangedCWD)
383 {
384 ERR() << "Error setting CWD for Vulkan layers init.";
385 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400386 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500387 }
388 }
389 }
390
391 // Override environment variable to use the ANGLE layers.
392 if (mEnableValidationLayers)
393 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700394 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500395 {
396 ERR() << "Error setting environment for Vulkan layers init.";
397 mEnableValidationLayers = false;
398 }
399 }
400#endif // !defined(ANGLE_PLATFORM_ANDROID)
401 }
402
403 ~ScopedVkLoaderEnvironment()
404 {
405 if (mChangedCWD)
406 {
407#if !defined(ANGLE_PLATFORM_ANDROID)
408 ASSERT(mPreviousCWD.valid());
409 angle::SetCWD(mPreviousCWD.value().c_str());
410#endif // !defined(ANGLE_PLATFORM_ANDROID)
411 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600412 if (mChangedICDPath)
413 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600414 if (mPreviousICDPath.value().empty())
415 {
416 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
417 }
418 else
419 {
420 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
421 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600422 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500423 }
424
Jamie Madillaaca96e2018-06-12 10:19:48 -0400425 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500426
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600427 bool canEnableMockICD() const { return mEnableMockICD; }
428
Yuly Novikov199f4292018-01-19 19:04:05 -0500429 private:
430 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600431 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500432 bool mChangedCWD;
433 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600434 bool mChangedICDPath;
435 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500436};
437
Jamie Madill21061022018-07-12 23:56:30 -0400438void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
439 bool preferMockICD,
440 VkPhysicalDevice *physicalDeviceOut,
441 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
442{
443 ASSERT(!physicalDevices.empty());
444 if (preferMockICD)
445 {
446 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
447 {
448 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
449 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
450 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
451 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
452 {
453 *physicalDeviceOut = physicalDevice;
454 return;
455 }
456 }
457 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
458 "physicalDevice instead.";
459 }
460
461 // Fall back to first device.
462 *physicalDeviceOut = physicalDevices[0];
463 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
464}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400465
466// Initially dumping the command graphs is disabled.
467constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700468
Jamie Madille09bd5d2016-11-29 16:20:35 -0500469} // anonymous namespace
470
Jamie Madill49ac74b2017-12-21 14:42:33 -0500471// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400472RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500473
Jamie Madillaaca96e2018-06-12 10:19:48 -0400474RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500475
476RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000477 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500478{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500479
480RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
481{
482 std::swap(commandPool, other.commandPool);
483 std::swap(fence, other.fence);
484 std::swap(serial, other.serial);
485 return *this;
486}
487
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000488void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400489{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000490 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400491 fence.destroy(device);
492}
493
Jamie Madill9f2a8612017-11-30 12:43:09 -0500494// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500495RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400496 : mDisplay(nullptr),
497 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700498 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500499 mInstance(VK_NULL_HANDLE),
500 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400501 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500502 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500503 mDebugReportCallback(VK_NULL_HANDLE),
504 mPhysicalDevice(VK_NULL_HANDLE),
505 mQueue(VK_NULL_HANDLE),
506 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
507 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400508 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400509 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400510 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400511 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400512 mCommandGraph(kEnableCommandGraphDiagnostics),
513 mGpuEventsEnabled(false),
514 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
515 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500516{
517 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
518 mFormatProperties.fill(invalid);
519}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400520
Jamie Madillb980c562018-11-27 11:34:27 -0500521RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400522
523void RendererVk::onDestroy(vk::Context *context)
524{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500525 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500526 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500527 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400528 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500529 }
530
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100531 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500532
Jamie Madillc7918ce2018-06-13 13:25:31 -0400533 mPipelineLayoutCache.destroy(mDevice);
534 mDescriptorSetLayoutCache.destroy(mDevice);
535
Jamie Madill9f2a8612017-11-30 12:43:09 -0500536 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500537 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400538 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400539 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400540 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500541
Jamie Madill06ca6342018-07-12 15:56:53 -0400542 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500543
Jamie Madill5deea722017-02-16 10:44:46 -0500544 if (mCommandPool.valid())
545 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000546 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500547 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500548
549 if (mDevice)
550 {
551 vkDestroyDevice(mDevice, nullptr);
552 mDevice = VK_NULL_HANDLE;
553 }
554
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500555 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500556 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500557 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
558 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
559
560 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
561 }
562 else if (mDebugReportCallback)
563 {
564 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
565 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500566 }
567
Jamie Madill4d0bf552016-12-28 15:45:24 -0500568 if (mInstance)
569 {
570 vkDestroyInstance(mInstance, nullptr);
571 mInstance = VK_NULL_HANDLE;
572 }
573
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600574 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500575 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500576}
577
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400578void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400579{
580 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400581
582 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500583 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400584 freeAllInFlightResources();
585
586 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400587}
588
589bool RendererVk::isDeviceLost() const
590{
591 return mDeviceLost;
592}
593
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400594angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400595 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500596 const char *wsiExtension,
597 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500598{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400599 mDisplay = display;
600 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600601 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
602 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500603 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400604 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500605
Jamie Madill0448ec82016-12-23 13:41:47 -0500606 // Gather global layer properties.
607 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400608 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500609
610 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
611 if (instanceLayerCount > 0)
612 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400613 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
614 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500615 }
616
Michael Spang6c13c702019-02-06 15:59:44 -0500617 VulkanLayerVector enabledInstanceLayerNames;
618 if (mEnableValidationLayers)
619 {
620 bool layersRequested =
621 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
622 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
623 &enabledInstanceLayerNames);
624 }
625
626 if (wsiLayer)
627 {
628 enabledInstanceLayerNames.push_back(wsiLayer);
629 }
630
631 // Enumerate instance extensions that are provided by the vulkan
632 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500633 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400634 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400635 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500636
637 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
638 if (instanceExtensionCount > 0)
639 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400640 ANGLE_VK_TRY(displayVk,
641 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
642 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500643 }
644
Michael Spang6c13c702019-02-06 15:59:44 -0500645 // Enumerate instance extensions that are provided by explicit layers.
646 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500647 {
Michael Spang6c13c702019-02-06 15:59:44 -0500648 uint32_t previousExtensionCount = instanceExtensionProps.size();
649 uint32_t instanceLayerExtensionCount = 0;
650 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
651 layerName, &instanceLayerExtensionCount, nullptr));
652 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
653 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
654 layerName, &instanceLayerExtensionCount,
655 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500656 }
657
Jamie Madille09bd5d2016-11-29 16:20:35 -0500658 std::vector<const char *> enabledInstanceExtensions;
659 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500660 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500661
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500662 bool enableDebugUtils =
663 mEnableValidationLayers &&
664 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
665 bool enableDebugReport =
666 mEnableValidationLayers && !enableDebugUtils &&
667 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
668
669 if (enableDebugUtils)
670 {
671 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
672 }
673 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500674 {
675 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
676 }
677
Jamie Madille09bd5d2016-11-29 16:20:35 -0500678 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400679 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400680 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500681
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400682 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500683 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500684 applicationInfo.pApplicationName = "ANGLE";
685 applicationInfo.applicationVersion = 1;
686 applicationInfo.pEngineName = "ANGLE";
687 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700688
689 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
690 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
691 if (!enumerateInstanceVersion)
692 {
693 applicationInfo.apiVersion = VK_API_VERSION_1_0;
694 }
695 else
696 {
697 uint32_t apiVersion = VK_API_VERSION_1_0;
698 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
699 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
700 {
701 // Note: will need to revisit this with Vulkan 1.2+.
702 applicationInfo.apiVersion = VK_API_VERSION_1_1;
703 }
704 else
705 {
706 applicationInfo.apiVersion = VK_API_VERSION_1_0;
707 }
708 }
Jamie Madill327ba852016-11-30 12:38:28 -0500709
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400710 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500711 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
712 instanceInfo.flags = 0;
713 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500714
Jamie Madille09bd5d2016-11-29 16:20:35 -0500715 // Enable requested layers and extensions.
716 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
717 instanceInfo.ppEnabledExtensionNames =
718 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500719 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
720 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500721
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400722 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500723
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500724 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500725 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500726 // Try to use the newer EXT_debug_utils if it exists.
727 InitDebugUtilsEXTFunctions(mInstance);
728
729 // Create the messenger callback.
730 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
731
732 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
733 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
734 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
735 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
736 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
737 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
738 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
739 messengerInfo.pUserData = this;
740
741 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
742 &mDebugUtilsMessenger));
743 }
744 else if (enableDebugReport)
745 {
746 // Fallback to EXT_debug_report.
747 InitDebugReportEXTFunctions(mInstance);
748
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400749 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500750
751 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500752 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500753 debugReportInfo.pfnCallback = &DebugReportCallback;
754 debugReportInfo.pUserData = this;
755
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500756 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
757 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500758 }
759
Jamie Madill4d0bf552016-12-28 15:45:24 -0500760 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400761 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
762 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500763
764 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700765 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400766 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
767 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400768 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700769 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500770
Jamie Madill30b5d842018-08-31 17:19:12 -0400771 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
772
Jamie Madill4d0bf552016-12-28 15:45:24 -0500773 // Ensure we can find a graphics queue family.
774 uint32_t queueCount = 0;
775 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
776
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400777 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500778
779 mQueueFamilyProperties.resize(queueCount);
780 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
781 mQueueFamilyProperties.data());
782
Jamie Madillb980c562018-11-27 11:34:27 -0500783 size_t graphicsQueueFamilyCount = false;
784 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500785 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500786 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
787 {
788 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500789 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500790 {
791 ASSERT(queueInfo.queueCount > 0);
792 graphicsQueueFamilyCount++;
793 if (firstGraphicsQueueFamily == 0)
794 {
795 firstGraphicsQueueFamily = familyIndex;
796 }
797 break;
798 }
799 }
800
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400801 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500802
803 // If only one queue family, go ahead and initialize the device. If there is more than one
804 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
805 if (graphicsQueueFamilyCount == 1)
806 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400807 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500808 }
809
Jamie Madill035fd6b2017-10-03 15:43:22 -0400810 // Store the physical device memory properties so we can find the right memory pools.
811 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500812
Jamie Madill06ca6342018-07-12 15:56:53 -0400813 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500814
Jamie Madill6a89d222017-11-02 11:59:51 -0400815 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500816 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400817
Jamie Madill7c985f52018-11-29 18:16:17 -0500818 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400819}
820
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400821angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500822{
823 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400824 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400825 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500826
827 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
828 if (deviceLayerCount > 0)
829 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400830 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
831 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500832 }
833
Michael Spang6c13c702019-02-06 15:59:44 -0500834 VulkanLayerVector enabledDeviceLayerNames;
835 if (mEnableValidationLayers)
836 {
837 mEnableValidationLayers =
838 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
839 }
840
841 const char *wsiLayer = displayVk->getWSILayer();
842 if (wsiLayer)
843 {
844 enabledDeviceLayerNames.push_back(wsiLayer);
845 }
846
847 // Enumerate device extensions that are provided by the vulkan
848 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500849 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400850 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
851 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500852
853 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
854 if (deviceExtensionCount > 0)
855 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400856 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
857 &deviceExtensionCount,
858 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500859 }
860
Michael Spang6c13c702019-02-06 15:59:44 -0500861 // Enumerate device extensions that are provided by explicit layers.
862 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500863 {
Michael Spang6c13c702019-02-06 15:59:44 -0500864 uint32_t previousExtensionCount = deviceExtensionProps.size();
865 uint32_t deviceLayerExtensionCount = 0;
866 ANGLE_VK_TRY(displayVk,
867 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
868 &deviceLayerExtensionCount, nullptr));
869 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
870 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
871 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
872 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873 }
874
875 std::vector<const char *> enabledDeviceExtensions;
876 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
877
Ian Elliottbcb78902018-12-19 11:46:29 -0700878 initFeatures(deviceExtensionProps);
879 mFeaturesInitialized = true;
880
Luc Ferronbf6dc372018-06-28 15:24:19 -0400881 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700882 if ((getFeatures().flipViewportY) &&
883 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400884 {
885 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
886 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700887 if (getFeatures().supportsIncrementalPresent)
888 {
889 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
890 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400891
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400892 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500893
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400894 // Select additional features to be enabled
895 VkPhysicalDeviceFeatures enabledFeatures = {};
896 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500897 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400898
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400899 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500900
901 float zeroPriority = 0.0f;
902
903 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500904 queueCreateInfo.flags = 0;
905 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
906 queueCreateInfo.queueCount = 1;
907 queueCreateInfo.pQueuePriorities = &zeroPriority;
908
909 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400910 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500911
Jamie Madill50cf2be2018-06-15 09:46:57 -0400912 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400913 createInfo.flags = 0;
914 createInfo.queueCreateInfoCount = 1;
915 createInfo.pQueueCreateInfos = &queueCreateInfo;
Michael Spang6c13c702019-02-06 15:59:44 -0500916 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
917 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500918 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
919 createInfo.ppEnabledExtensionNames =
920 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400921 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500922
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400923 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500924
925 mCurrentQueueFamilyIndex = queueFamilyIndex;
926
927 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
928
929 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400930 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500931 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
932 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
933 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500934
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000935 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400936
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400937 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500938 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500939
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400940 // Initialize the submission semaphore pool.
941 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
942
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400943#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
944 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
945 ASSERT(platform);
946
947 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
948 // platform discovery.
949 const unsigned char *gpuEventsEnabled =
950 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
951 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
952#endif
953
954 if (mGpuEventsEnabled)
955 {
956 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
957 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
958 vk::kDefaultTimestampQueryPoolSize));
959 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
960 }
961
Jamie Madill7c985f52018-11-29 18:16:17 -0500962 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500963}
964
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400965angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400966 VkSurfaceKHR surface,
967 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500968{
969 // We've already initialized a device, and can't re-create it unless it's never been used.
970 // TODO(jmadill): Handle the re-creation case if necessary.
971 if (mDevice != VK_NULL_HANDLE)
972 {
973 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
974
975 // Check if the current device supports present on this surface.
976 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400977 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400978 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500979 surface, &supportsPresent));
980
Jamie Madill6cad7732018-07-11 09:01:17 -0400981 if (supportsPresent == VK_TRUE)
982 {
983 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500984 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400985 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500986 }
987
988 // Find a graphics and present queue.
989 Optional<uint32_t> newPresentQueue;
990 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500991 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500992 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
993 {
994 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500995 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500996 {
997 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400998 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
999 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001000
1001 if (supportsPresent == VK_TRUE)
1002 {
1003 newPresentQueue = queueIndex;
1004 break;
1005 }
1006 }
1007 }
1008
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001009 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1010 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001011
Jamie Madill6cad7732018-07-11 09:01:17 -04001012 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001013 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001014}
1015
1016std::string RendererVk::getVendorString() const
1017{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001018 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001019}
1020
Jamie Madille09bd5d2016-11-29 16:20:35 -05001021std::string RendererVk::getRendererDescription() const
1022{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001023 std::stringstream strstr;
1024
1025 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1026
1027 strstr << "Vulkan ";
1028 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1029 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1030 strstr << VK_VERSION_PATCH(apiVersion);
1031
Olli Etuahoc6a06182018-04-13 14:11:46 +03001032 strstr << "(";
1033
1034 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1035 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1036 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1037 // driver detection.
1038 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1039 {
1040 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1041 }
1042
Geoff Langa7af56b2018-12-14 14:20:28 -05001043 strstr << mPhysicalDeviceProperties.deviceName;
1044 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1045
1046 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001047
1048 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001049}
1050
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001051gl::Version RendererVk::getMaxSupportedESVersion() const
1052{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001053 // Current highest supported version
1054 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1055 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001056
Geoff Lang0c2c9232019-01-14 16:01:38 -05001057 // Vulkan inherited queries are required to support any GL query type
1058 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001059 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001060 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001061 }
1062
Geoff Lang0c2c9232019-01-14 16:01:38 -05001063 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001064}
1065
Ian Elliottbcb78902018-12-19 11:46:29 -07001066void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001067{
Jamie Madillb36a4812018-09-25 10:15:11 -04001068// Use OpenGL line rasterization rules by default.
1069// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1070#if defined(ANGLE_PLATFORM_ANDROID)
1071 mFeatures.basicGLLineRasterization = false;
1072#else
Jamie Madill12222072018-07-11 14:59:48 -04001073 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001074#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001075
Ian Elliott52f5da42018-12-21 09:02:09 -07001076 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1077 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001078 {
1079 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1080 // investigation. http://anglebug.com/2728
1081 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1082 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001083
1084#ifdef ANGLE_PLATFORM_WINDOWS
1085 // http://anglebug.com/2838
1086 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001087
1088 // http://anglebug.com/3055
1089 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001090#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001091
1092 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1093 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001094
1095 // Work around incorrect NVIDIA point size range clamping.
1096 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1097 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1098 {
1099 mFeatures.clampPointSize = true;
1100 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001101
Jamie Madillfa7ca182019-01-15 11:20:58 -05001102 // We also need to clamp point size on several Android drivers.
1103 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1104 if (IsAndroid())
1105 {
1106 mFeatures.clampPointSize = true;
1107 }
1108
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001109#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001110 // Work around ineffective compute-graphics barriers on Nexus 5X.
1111 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1112 // http://anglebug.com/3019
1113 mFeatures.flushAfterVertexConversion =
1114 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001115#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001116
1117 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1118 {
1119 mFeatures.supportsIncrementalPresent = true;
1120 }
Jamie Madill12222072018-07-11 14:59:48 -04001121}
1122
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001123void RendererVk::initPipelineCacheVkKey()
1124{
1125 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1126 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1127 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1128 // there is no '\0' in the result.
1129 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1130 {
1131 hashStream << std::hex << c;
1132 }
1133 // Add the vendor and device id too for good measure.
1134 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1135 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1136
1137 const std::string &hashString = hashStream.str();
1138 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1139 hashString.length(), mPipelineCacheVkBlobKey.data());
1140}
1141
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001142angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001143{
1144 initPipelineCacheVkKey();
1145
1146 egl::BlobCache::Value initialData;
1147 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1148 mPipelineCacheVkBlobKey, &initialData);
1149
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001150 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001151
1152 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001153 pipelineCacheCreateInfo.flags = 0;
1154 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1155 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1156
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001157 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001158 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001159}
1160
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001161void RendererVk::getSubmitWaitSemaphores(
1162 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001163 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1164 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001165{
1166 if (mSubmitLastSignaledSemaphore.getSemaphore())
1167 {
1168 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001169 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001170
1171 // Return the semaphore to the pool (which will remain valid and unused until the
1172 // queue it's about to be waited on has finished execution).
1173 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1174 }
1175
1176 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1177 {
1178 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001179 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1180
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001181 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1182 }
1183 mSubmitWaitSemaphores.clear();
1184}
1185
Jamie Madillacccc6c2016-05-03 17:22:10 -04001186const gl::Caps &RendererVk::getNativeCaps() const
1187{
1188 ensureCapsInitialized();
1189 return mNativeCaps;
1190}
1191
1192const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1193{
1194 ensureCapsInitialized();
1195 return mNativeTextureCaps;
1196}
1197
1198const gl::Extensions &RendererVk::getNativeExtensions() const
1199{
1200 ensureCapsInitialized();
1201 return mNativeExtensions;
1202}
1203
1204const gl::Limitations &RendererVk::getNativeLimitations() const
1205{
1206 ensureCapsInitialized();
1207 return mNativeLimitations;
1208}
1209
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001210uint32_t RendererVk::getMaxActiveTextures()
1211{
1212 // TODO(lucferron): expose this limitation to GL in Context Caps
1213 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1214 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1215}
1216
Jamie Madill49ac74b2017-12-21 14:42:33 -05001217const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001218{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001219 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001220}
1221
Jamie Madill21061022018-07-12 23:56:30 -04001222angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001223{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001224 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001225 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001226 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1227
Luc Ferron1617e692018-07-11 11:08:19 -04001228 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1229 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001230
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001231 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001232 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1233 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001234
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001235 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001236 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001237 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1238 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001239 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001240 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001241 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001242 submitInfo.signalSemaphoreCount = 0;
1243 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001244
Jamie Madill21061022018-07-12 23:56:30 -04001245 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001246 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001247
Jamie Madill4c26fc22017-02-24 11:04:10 -05001248 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001249 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001250 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001251
1252 if (mGpuEventsEnabled)
1253 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001254 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001255 while (mInFlightGpuEventQueries.size() > 0)
1256 {
1257 ANGLE_TRY(checkCompletedGpuEvents(context));
1258 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001259 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1260 // synchronization if there is no event to be adjusted (happens when finish() gets called
1261 // multiple times towards the end of the application).
1262 if (mGpuEvents.size() > 0)
1263 {
1264 ANGLE_TRY(synchronizeCpuGpuTime(context));
1265 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001266 }
1267
Jamie Madill7c985f52018-11-29 18:16:17 -05001268 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001269}
1270
Jamie Madill0c0dc342017-03-24 14:18:51 -04001271void RendererVk::freeAllInFlightResources()
1272{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001273 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001274 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001275 // On device loss we need to wait for fence to be signaled before destroying it
1276 if (mDeviceLost)
1277 {
1278 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1279 // If wait times out, it is probably not possible to recover from lost device
1280 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1281 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001282 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001283 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001284 }
1285 mInFlightCommands.clear();
1286
1287 for (auto &garbage : mGarbage)
1288 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001289 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001290 }
1291 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001292
1293 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001294}
1295
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001296angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001297{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001298 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001299
Jamie Madill49ac74b2017-12-21 14:42:33 -05001300 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001301 {
Yuly Novikov27780292018-11-09 11:19:49 -05001302 VkResult result = batch.fence.getStatus(mDevice);
1303 if (result == VK_NOT_READY)
1304 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001305 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001306 }
1307 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001308
Jamie Madill49ac74b2017-12-21 14:42:33 -05001309 ASSERT(batch.serial > mLastCompletedQueueSerial);
1310 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001311
Jamie Madill49ac74b2017-12-21 14:42:33 -05001312 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001313 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001314 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001315 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001316 }
1317
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001319
1320 size_t freeIndex = 0;
1321 for (; freeIndex < mGarbage.size(); ++freeIndex)
1322 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001323 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001324 break;
1325 }
1326
1327 // Remove the entries from the garbage list - they should be ready to go.
1328 if (freeIndex > 0)
1329 {
1330 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001331 }
1332
Jamie Madill7c985f52018-11-29 18:16:17 -05001333 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001334}
1335
Jamie Madill21061022018-07-12 23:56:30 -04001336angle::Result RendererVk::submitFrame(vk::Context *context,
1337 const VkSubmitInfo &submitInfo,
1338 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001339{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001340 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001341 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001342 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1343 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001344
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001345 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001346 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001347 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001348
Jamie Madill21061022018-07-12 23:56:30 -04001349 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001350
1351 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001352 batch.commandPool = std::move(mCommandPool);
1353 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001354
Jamie Madillbea35a62018-07-05 11:54:10 -04001355 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001356
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001357 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1358 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001359 // so the limit is larger than the expected number of images. The
1360 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001361 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001362
Jamie Madill85ca1892019-01-16 13:27:15 -05001363 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001364
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001365 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001366
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001367 if (mGpuEventsEnabled)
1368 {
1369 ANGLE_TRY(checkCompletedGpuEvents(context));
1370 }
1371
Jamie Madill49ac74b2017-12-21 14:42:33 -05001372 // Simply null out the command buffer here - it was allocated using the command pool.
1373 commandBuffer.releaseHandle();
1374
1375 // Reallocate the command pool for next frame.
1376 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001377 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001378 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001379 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001380 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001381
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001382 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001383 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001384}
1385
Jamie Madill85ca1892019-01-16 13:27:15 -05001386void RendererVk::nextSerial()
1387{
1388 // Increment the queue serial. If this fails, we should restart ANGLE.
1389 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1390 mCurrentQueueSerial = mQueueSerialFactory.generate();
1391
1392 // Notify the Contexts that they should be starting new command buffers.
1393 // We use one command pool per serial/submit associated with this VkQueue. We can also
1394 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1395 // check for a new serial when starting a new command buffer. We just check that the current
1396 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1397 // using this VkQueue that they their current command buffer is no longer valid.
1398 for (gl::Context *context : mDisplay->getContextSet())
1399 {
1400 ContextVk *contextVk = vk::GetImpl(context);
1401 contextVk->onCommandBufferFinished();
1402 }
1403}
1404
Jamie Madillaaca96e2018-06-12 10:19:48 -04001405bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001406{
1407 return serial > mLastCompletedQueueSerial;
1408}
1409
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001410angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1411{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001412 bool timedOut = false;
1413 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1414
1415 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1416 if (timedOut)
1417 {
1418 result = angle::Result::Stop;
1419 }
1420 return result;
1421}
1422
1423angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1424 Serial serial,
1425 uint64_t timeout,
1426 bool *outTimedOut)
1427{
1428 *outTimedOut = false;
1429
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001430 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1431 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001432 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001433 }
1434
1435 // Find the first batch with serial equal to or bigger than given serial (note that
1436 // the batch serials are unique, otherwise upper-bound would have been necessary).
1437 size_t batchIndex = mInFlightCommands.size() - 1;
1438 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1439 {
1440 if (mInFlightCommands[i].serial >= serial)
1441 {
1442 batchIndex = i;
1443 break;
1444 }
1445 }
1446 const CommandBatch &batch = mInFlightCommands[batchIndex];
1447
1448 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001449 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1450
1451 // If timed out, report it as such.
1452 if (status == VK_TIMEOUT)
1453 {
1454 *outTimedOut = true;
1455 return angle::Result::Continue;
1456 }
1457
1458 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001459
1460 // Clean up finished batches.
1461 return checkCompletedCommands(context);
1462}
1463
Jamie Madill21061022018-07-12 23:56:30 -04001464angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1465 const vk::RenderPassDesc &desc,
1466 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001467{
Jamie Madill21061022018-07-12 23:56:30 -04001468 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001469 renderPassOut);
1470}
1471
Jamie Madill21061022018-07-12 23:56:30 -04001472angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1473 const vk::RenderPassDesc &desc,
1474 const vk::AttachmentOpsArray &ops,
1475 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001476{
Jamie Madill21061022018-07-12 23:56:30 -04001477 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001478 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001479}
1480
Jamie Madilla5e06072018-05-18 14:36:05 -04001481vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001482{
Jamie Madilla5e06072018-05-18 14:36:05 -04001483 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001484}
1485
Jamie Madill21061022018-07-12 23:56:30 -04001486angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001487{
Jamie Madill21061022018-07-12 23:56:30 -04001488 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001489 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001490}
1491
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001492angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001493{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001494 if (mCommandGraph.empty())
1495 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001496 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001497 }
1498
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001499 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1500
Jamie Madillbea35a62018-07-05 11:54:10 -04001501 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1502 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001503
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001504 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001505 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1506 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001507
1508 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1509 // will be waited on.
1510 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001511
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001512 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001513 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001514 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1515 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001516 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001517 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001518 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001519 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001520 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001521
Jamie Madill21061022018-07-12 23:56:30 -04001522 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001523
Jamie Madill7c985f52018-11-29 18:16:17 -05001524 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001525}
1526
Jamie Madill78feddc2018-04-27 11:45:05 -04001527Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001528{
Jamie Madill78feddc2018-04-27 11:45:05 -04001529 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001530}
1531
Jamie Madill21061022018-07-12 23:56:30 -04001532angle::Result RendererVk::getDescriptorSetLayout(
1533 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001534 const vk::DescriptorSetLayoutDesc &desc,
1535 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1536{
Jamie Madill21061022018-07-12 23:56:30 -04001537 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001538}
1539
Jamie Madill21061022018-07-12 23:56:30 -04001540angle::Result RendererVk::getPipelineLayout(
1541 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001542 const vk::PipelineLayoutDesc &desc,
1543 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1544 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1545{
Jamie Madill21061022018-07-12 23:56:30 -04001546 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001547 pipelineLayoutOut);
1548}
1549
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001550angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1551{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001552 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001553
1554 if (--mPipelineCacheVkUpdateTimeout > 0)
1555 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001556 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001557 }
1558
1559 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1560
1561 // Get the size of the cache.
1562 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001563 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001564 if (result != VK_INCOMPLETE)
1565 {
1566 ANGLE_VK_TRY(displayVk, result);
1567 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001568
1569 angle::MemoryBuffer *pipelineCacheData = nullptr;
1570 ANGLE_VK_CHECK_ALLOC(displayVk,
1571 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1572
1573 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001574 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001575 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1576 // was determined just above), so receiving it hints at an implementation bug we would want
1577 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001578 ASSERT(result != VK_INCOMPLETE);
1579 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001580
1581 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1582 // the buffer to avoid leaking garbage memory.
1583 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1584 if (pipelineCacheSize < originalPipelineCacheSize)
1585 {
1586 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1587 originalPipelineCacheSize - pipelineCacheSize);
1588 }
1589
1590 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1591
Jamie Madill7c985f52018-11-29 18:16:17 -05001592 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001593}
1594
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001595angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1596 const vk::Semaphore **outSemaphore)
1597{
1598 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1599
1600 vk::SemaphoreHelper semaphore;
1601 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1602
1603 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1604 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1605
Jamie Madill7c985f52018-11-29 18:16:17 -05001606 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001607}
1608
1609const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1610{
1611 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1612
1613 // Return the semaphore to the pool (which will remain valid and unused until the
1614 // queue it's about to be waited on has finished execution). The caller is about
1615 // to wait on it.
1616 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1617
1618 return semaphore;
1619}
1620
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001621angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1622{
1623 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1624 // that seems impossible, so instead, we are going to make a small submission with just a
1625 // timestamp query. First, the disjoint timer query extension says:
1626 //
1627 // > This will return the GL time after all previous commands have reached the GL server but
1628 // have not yet necessarily executed.
1629 //
1630 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1631 // The wording allows us to make a submission to get the timestamp without performing a flush.
1632 //
1633 // Second:
1634 //
1635 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1636 // object target, applications can measure the latency between when commands reach the GL server
1637 // and when they are realized in the framebuffer.
1638 //
1639 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1640 // GPU bubble. This function directly generates a command buffer and submits it instead of
1641 // using the other member functions. This is to avoid changing any state, such as the queue
1642 // serial.
1643
1644 // Create a query used to receive the GPU timestamp
1645 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1646 vk::QueryHelper timestampQuery;
1647 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1648 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1649
1650 // Record the command buffer
1651 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1652 vk::CommandBuffer &commandBuffer = commandBatch.get();
1653
1654 VkCommandBufferAllocateInfo commandBufferInfo = {};
1655 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1656 commandBufferInfo.commandPool = mCommandPool.getHandle();
1657 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1658 commandBufferInfo.commandBufferCount = 1;
1659
Yuly Novikov27780292018-11-09 11:19:49 -05001660 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001661
1662 VkCommandBufferBeginInfo beginInfo = {};
1663 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1664 beginInfo.flags = 0;
1665 beginInfo.pInheritanceInfo = nullptr;
1666
Yuly Novikov27780292018-11-09 11:19:49 -05001667 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001668
1669 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1670 timestampQuery.getQuery(), 1);
1671 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1672 timestampQuery.getQueryPool()->getHandle(),
1673 timestampQuery.getQuery());
1674
Yuly Novikov27780292018-11-09 11:19:49 -05001675 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001676
1677 // Create fence for the submission
1678 VkFenceCreateInfo fenceInfo = {};
1679 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1680 fenceInfo.flags = 0;
1681
1682 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001683 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001684
1685 // Submit the command buffer
1686 VkSubmitInfo submitInfo = {};
1687 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1688 submitInfo.waitSemaphoreCount = 0;
1689 submitInfo.pWaitSemaphores = nullptr;
1690 submitInfo.pWaitDstStageMask = nullptr;
1691 submitInfo.commandBufferCount = 1;
1692 submitInfo.pCommandBuffers = commandBuffer.ptr();
1693 submitInfo.signalSemaphoreCount = 0;
1694 submitInfo.pSignalSemaphores = nullptr;
1695
1696 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1697
1698 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1699 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001700 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001701
1702 // Get the query results
1703 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1704
Yuly Novikov27780292018-11-09 11:19:49 -05001705 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1706 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1707 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001708
1709 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1710
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001711 // Convert results to nanoseconds.
1712 *timestampOut = static_cast<uint64_t>(
1713 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1714
Jamie Madill7c985f52018-11-29 18:16:17 -05001715 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001716}
1717
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001718// These functions look at the mandatory format for support, and fallback to querying the device (if
1719// necessary) to test the availability of the bits.
1720bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1721 const VkFormatFeatureFlags featureBits)
1722{
1723 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1724}
1725
1726bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1727 const VkFormatFeatureFlags featureBits)
1728{
1729 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1730}
1731
1732bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1733{
1734 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1735}
1736
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001737angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1738{
1739 ASSERT(mGpuEventsEnabled);
1740
1741 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1742 ASSERT(platform);
1743
1744 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1745 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1746 //
1747 // CPU GPU
1748 //
1749 // Record command buffer
1750 // with timestamp query
1751 //
1752 // Submit command buffer
1753 //
1754 // Post-submission work Begin execution
1755 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001756 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001757 //
1758 // ???? End execution
1759 //
1760 // ???? Return query results
1761 //
1762 // ????
1763 //
1764 // Get query results
1765 //
1766 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1767 // finished post-submission work while the GPU is executing in parallel. With no further work,
1768 // querying CPU timestamps before submission and after getting query results give the bounds to
1769 // Tgpu, which could be quite large.
1770 //
1771 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1772 // reduce this range. This function implements the following procedure:
1773 //
1774 // CPU GPU
1775 //
1776 // Record command buffer
1777 // with timestamp query
1778 //
1779 // Submit command buffer
1780 //
1781 // Post-submission work Begin execution
1782 //
1783 // ???? Set Event GPUReady
1784 //
1785 // Wait on Event GPUReady Wait on Event CPUReady
1786 //
1787 // Get CPU Time Ts Wait on Event CPUReady
1788 //
1789 // Set Event CPUReady Wait on Event CPUReady
1790 //
1791 // Get CPU Time Tcpu Get GPU Time Tgpu
1792 //
1793 // Wait on Event GPUDone Set Event GPUDone
1794 //
1795 // Get CPU Time Te End Execution
1796 //
1797 // Idle Return query results
1798 //
1799 // Get query results
1800 //
1801 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1802 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1803 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1804 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1805 // calibration.
1806 //
1807 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1808
1809 // Make sure nothing is running
1810 ASSERT(mCommandGraph.empty());
1811
1812 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1813
1814 // Create a query used to receive the GPU timestamp
1815 vk::QueryHelper timestampQuery;
1816 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1817
1818 // Create the three events
1819 VkEventCreateInfo eventCreateInfo = {};
1820 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1821 eventCreateInfo.flags = 0;
1822
1823 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001824 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1825 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1826 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001827
1828 constexpr uint32_t kRetries = 10;
1829
1830 // Time suffixes used are S for seconds and Cycles for cycles
1831 double tightestRangeS = 1e6f;
1832 double TcpuS = 0;
1833 uint64_t TgpuCycles = 0;
1834 for (uint32_t i = 0; i < kRetries; ++i)
1835 {
1836 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001837 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1838 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1839 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001840
1841 // Record the command buffer
1842 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1843 vk::CommandBuffer &commandBuffer = commandBatch.get();
1844
1845 VkCommandBufferAllocateInfo commandBufferInfo = {};
1846 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1847 commandBufferInfo.commandPool = mCommandPool.getHandle();
1848 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1849 commandBufferInfo.commandBufferCount = 1;
1850
Yuly Novikov27780292018-11-09 11:19:49 -05001851 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001852
1853 VkCommandBufferBeginInfo beginInfo = {};
1854 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1855 beginInfo.flags = 0;
1856 beginInfo.pInheritanceInfo = nullptr;
1857
Yuly Novikov27780292018-11-09 11:19:49 -05001858 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001859
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001860 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001861 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1862 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1863 nullptr);
1864
1865 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1866 timestampQuery.getQuery(), 1);
1867 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1868 timestampQuery.getQueryPool()->getHandle(),
1869 timestampQuery.getQuery());
1870
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001871 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001872
Yuly Novikov27780292018-11-09 11:19:49 -05001873 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001874
1875 // Submit the command buffer
1876 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1877 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1878 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1879
1880 VkSubmitInfo submitInfo = {};
1881 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1882 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1883 submitInfo.pWaitSemaphores = waitSemaphores.data();
1884 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1885 submitInfo.commandBufferCount = 1;
1886 submitInfo.pCommandBuffers = commandBuffer.ptr();
1887 submitInfo.signalSemaphoreCount = 0;
1888 submitInfo.pSignalSemaphores = nullptr;
1889
1890 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1891
1892 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001893 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001894 do
1895 {
Yuly Novikov27780292018-11-09 11:19:49 -05001896 result = gpuReady.get().getStatus(mDevice);
1897 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1898 {
1899 ANGLE_VK_TRY(context, result);
1900 }
1901 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001902
1903 double TsS = platform->monotonicallyIncreasingTime(platform);
1904
1905 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001906 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001907 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1908
1909 // Wait for GPU to be done. Another short busy wait.
1910 do
1911 {
Yuly Novikov27780292018-11-09 11:19:49 -05001912 result = gpuDone.get().getStatus(mDevice);
1913 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1914 {
1915 ANGLE_VK_TRY(context, result);
1916 }
1917 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001918
1919 double TeS = platform->monotonicallyIncreasingTime(platform);
1920
1921 // Get the query results
1922 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1923
1924 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1925
1926 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001927 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1928 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1929 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001930
1931 // Use the first timestamp queried as origin.
1932 if (mGpuEventTimestampOrigin == 0)
1933 {
1934 mGpuEventTimestampOrigin = gpuTimestampCycles;
1935 }
1936
1937 // Take these CPU and GPU timestamps if there is better confidence.
1938 double confidenceRangeS = TeS - TsS;
1939 if (confidenceRangeS < tightestRangeS)
1940 {
1941 tightestRangeS = confidenceRangeS;
1942 TcpuS = cpuTimestampS;
1943 TgpuCycles = gpuTimestampCycles;
1944 }
1945 }
1946
1947 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1948
1949 // timestampPeriod gives nanoseconds/cycle.
1950 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1951 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1952 1'000'000'000.0;
1953
1954 flushGpuEvents(TgpuS, TcpuS);
1955
1956 mGpuClockSync.gpuTimestampS = TgpuS;
1957 mGpuClockSync.cpuTimestampS = TcpuS;
1958
Jamie Madill7c985f52018-11-29 18:16:17 -05001959 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001960}
1961
1962angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1963 vk::CommandBuffer *commandBuffer,
1964 char phase,
1965 const char *name)
1966{
1967 ASSERT(mGpuEventsEnabled);
1968
1969 GpuEventQuery event;
1970
1971 event.name = name;
1972 event.phase = phase;
1973 event.serial = mCurrentQueueSerial;
1974
1975 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1976
1977 commandBuffer->resetQueryPool(
1978 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1979 commandBuffer->writeTimestamp(
1980 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1981 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1982
1983 mInFlightGpuEventQueries.push_back(std::move(event));
1984
Jamie Madill7c985f52018-11-29 18:16:17 -05001985 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001986}
1987
1988angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1989{
1990 ASSERT(mGpuEventsEnabled);
1991
1992 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1993 ASSERT(platform);
1994
1995 int finishedCount = 0;
1996
1997 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1998 {
1999 // Only check the timestamp query if the submission has finished.
2000 if (eventQuery.serial > mLastCompletedQueueSerial)
2001 {
2002 break;
2003 }
2004
2005 // See if the results are available.
2006 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002007 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2008 ->getResults(mDevice, eventQuery.queryIndex, 1,
2009 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2010 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2011 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002012 {
2013 break;
2014 }
Yuly Novikov27780292018-11-09 11:19:49 -05002015 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002016
2017 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2018
2019 GpuEvent event;
2020 event.gpuTimestampCycles = gpuTimestampCycles;
2021 event.name = eventQuery.name;
2022 event.phase = eventQuery.phase;
2023
2024 mGpuEvents.emplace_back(event);
2025
2026 ++finishedCount;
2027 }
2028
2029 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2030 mInFlightGpuEventQueries.begin() + finishedCount);
2031
Jamie Madill7c985f52018-11-29 18:16:17 -05002032 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002033}
2034
2035void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2036{
2037 if (mGpuEvents.size() == 0)
2038 {
2039 return;
2040 }
2041
2042 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2043 ASSERT(platform);
2044
2045 // Find the slope of the clock drift for adjustment
2046 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2047 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2048 double gpuSyncDriftSlope = 0;
2049
2050 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2051 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2052
2053 // No gpu trace events should have been generated before the clock sync, so if there is no
2054 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2055 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2056 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2057
2058 gpuSyncDriftSlope =
2059 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2060
2061 for (const GpuEvent &event : mGpuEvents)
2062 {
2063 double gpuTimestampS =
2064 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2065 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2066
2067 // Account for clock drift.
2068 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2069
2070 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2071 // for.
2072 static long long eventId = 1;
2073 static const unsigned char *categoryEnabled =
2074 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2075 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2076 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2077 }
2078
2079 mGpuEvents.clear();
2080}
2081
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002082template <VkFormatFeatureFlags VkFormatProperties::*features>
2083bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2084{
2085 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2086 VkFormatProperties &deviceProperties = mFormatProperties[format];
2087
2088 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2089 {
2090 // If we don't have the actual device features, see if the requested features are mandatory.
2091 // If so, there's no need to query the device.
2092 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2093 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2094 {
2095 return true;
2096 }
2097
2098 // Otherwise query the format features and cache it.
2099 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2100 }
2101
2102 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2103}
2104
Jamie Madillaaca96e2018-06-12 10:19:48 -04002105uint32_t GetUniformBufferDescriptorCount()
2106{
2107 return kUniformBufferDescriptorsPerDescriptorSet;
2108}
2109
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002110} // namespace rx