blob: 4d7411dc6c09dfa2d8dccd3c8520c87cb48c7740 [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"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040034
Shahbaz Youssefi61656022018-10-24 15:00:50 -040035#include "third_party/trace_event/trace_event.h"
36
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070037// Consts
38namespace
39{
Jamie Madill7c985f52018-11-29 18:16:17 -050040const uint32_t kMockVendorID = 0xba5eba11;
41const uint32_t kMockDeviceID = 0xf005ba11;
42constexpr char kMockDeviceName[] = "Vulkan Mock Device";
43constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050044constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070045} // anonymous namespace
46
Jamie Madill9e54b5a2016-05-25 12:57:39 -040047namespace rx
48{
49
Jamie Madille09bd5d2016-11-29 16:20:35 -050050namespace
51{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040052// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
53// one for the vertex shader.
54constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040055// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050056constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040057// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050058constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050059
Omar El Sheikh26c61b22018-06-29 12:50:59 -060060bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
61{
62#if !defined(ANGLE_PLATFORM_ANDROID)
63 // Mock ICD does not currently run on Android
64 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
66 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
67#else
68 return false;
69#endif // !defined(ANGLE_PLATFORM_ANDROID)
70}
71
Jamie Madille09bd5d2016-11-29 16:20:35 -050072VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
73 const std::vector<const char *> &enabledExtensionNames)
74{
75 // Compile the extensions names into a set.
76 std::set<std::string> extensionNames;
77 for (const auto &extensionProp : extensionProps)
78 {
79 extensionNames.insert(extensionProp.extensionName);
80 }
81
Jamie Madillacf2f3a2017-11-21 19:22:44 -050082 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050083 {
84 if (extensionNames.count(extensionName) == 0)
85 {
86 return VK_ERROR_EXTENSION_NOT_PRESENT;
87 }
88 }
89
90 return VK_SUCCESS;
91}
92
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050093bool ExtensionFound(const char *extensionName,
94 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060095{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050096 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060097 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050098 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060099 {
100 return true;
101 }
102 }
103 return false;
104}
105
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500106// Array of Validation error/warning messages that will be ignored, should include bugID
107constexpr std::array<const char *, 1> kSkippedMessages = {
108 // http://anglebug.com/2796
109 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
110
111// Suppress validation errors that are known
112// return "true" if given code/prefix/message is known, else return "false"
113bool IsIgnoredDebugMessage(const char *message)
114{
Michael Spang25839802019-01-30 18:02:51 -0500115 if (!message)
116 {
117 return false;
118 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500119 for (const char *msg : kSkippedMessages)
120 {
121 if (strstr(message, msg) != nullptr)
122 {
123 return true;
124 }
125 }
126 return false;
127}
128
129const char *GetVkObjectTypeName(VkObjectType type)
130{
131 switch (type)
132 {
133 case VK_OBJECT_TYPE_UNKNOWN:
134 return "Unknown";
135 case VK_OBJECT_TYPE_INSTANCE:
136 return "Instance";
137 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
138 return "Physical Device";
139 case VK_OBJECT_TYPE_DEVICE:
140 return "Device";
141 case VK_OBJECT_TYPE_QUEUE:
142 return "Queue";
143 case VK_OBJECT_TYPE_SEMAPHORE:
144 return "Semaphore";
145 case VK_OBJECT_TYPE_COMMAND_BUFFER:
146 return "Command Buffer";
147 case VK_OBJECT_TYPE_FENCE:
148 return "Fence";
149 case VK_OBJECT_TYPE_DEVICE_MEMORY:
150 return "Device Memory";
151 case VK_OBJECT_TYPE_BUFFER:
152 return "Buffer";
153 case VK_OBJECT_TYPE_IMAGE:
154 return "Image";
155 case VK_OBJECT_TYPE_EVENT:
156 return "Event";
157 case VK_OBJECT_TYPE_QUERY_POOL:
158 return "Query Pool";
159 case VK_OBJECT_TYPE_BUFFER_VIEW:
160 return "Buffer View";
161 case VK_OBJECT_TYPE_IMAGE_VIEW:
162 return "Image View";
163 case VK_OBJECT_TYPE_SHADER_MODULE:
164 return "Shader Module";
165 case VK_OBJECT_TYPE_PIPELINE_CACHE:
166 return "Pipeline Cache";
167 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
168 return "Pipeline Layout";
169 case VK_OBJECT_TYPE_RENDER_PASS:
170 return "Render Pass";
171 case VK_OBJECT_TYPE_PIPELINE:
172 return "Pipeline";
173 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
174 return "Descriptor Set Layout";
175 case VK_OBJECT_TYPE_SAMPLER:
176 return "Sampler";
177 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
178 return "Descriptor Pool";
179 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
180 return "Descriptor Set";
181 case VK_OBJECT_TYPE_FRAMEBUFFER:
182 return "Framebuffer";
183 case VK_OBJECT_TYPE_COMMAND_POOL:
184 return "Command Pool";
185 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
186 return "Sampler YCbCr Conversion";
187 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
188 return "Descriptor Update Template";
189 case VK_OBJECT_TYPE_SURFACE_KHR:
190 return "Surface";
191 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
192 return "Swapchain";
193 case VK_OBJECT_TYPE_DISPLAY_KHR:
194 return "Display";
195 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
196 return "Display Mode";
197 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
198 return "Debug Report Callback";
199 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
200 return "Object Table";
201 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
202 return "Indirect Commands Layout";
203 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
204 return "Debug Utils Messenger";
205 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
206 return "Validation Cache";
207 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
208 return "Acceleration Structure";
209 default:
210 return "<Unrecognized>";
211 }
212}
213
214VKAPI_ATTR VkBool32 VKAPI_CALL
215DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
216 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
217 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
218 void *userData)
219{
220 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
221 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
222 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
223
224 // Check if we even care about this message.
225 if ((messageSeverity & kSeveritiesToLog) == 0)
226 {
227 return VK_FALSE;
228 }
229
230 // See if it's an issue we are aware of and don't want to be spammed about.
231 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
232 {
233 return VK_FALSE;
234 }
235
236 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500237 if (callbackData->pMessageIdName)
238 {
239 log << "[ " << callbackData->pMessageIdName << " ] ";
240 }
241 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500242
243 // Aesthetic value based on length of the function name, line number, etc.
244 constexpr size_t kStartIndent = 28;
245
246 // Output the debug marker hierarchy under which this error has occured.
247 size_t indent = kStartIndent;
248 if (callbackData->queueLabelCount > 0)
249 {
250 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
251 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
252 {
253 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
254 << std::endl;
255 }
256 }
257 if (callbackData->cmdBufLabelCount > 0)
258 {
259 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
260 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
261 {
262 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
263 << std::endl;
264 }
265 }
266 // Output the objects involved in this error message.
267 if (callbackData->objectCount > 0)
268 {
269 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
270 {
271 const char *objectName = callbackData->pObjects[i].pObjectName;
272 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
273 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
274 log << std::string(indent, ' ') << "Object: ";
275 if (objectHandle == 0)
276 {
277 log << "VK_NULL_HANDLE";
278 }
279 else
280 {
281 log << "0x" << std::hex << objectHandle << std::dec;
282 }
283 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
284 if (objectName)
285 {
286 log << " [" << objectName << "]";
287 }
288 log << std::endl;
289 }
290 }
291
292 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
293
294 if (isError)
295 {
296 ERR() << log.str();
297 }
298 else
299 {
300 WARN() << log.str();
301 }
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,
Jamie Madill21061022018-07-12 23:56:30 -0400596 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500597{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400598 mDisplay = display;
599 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600600 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
601 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500602 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400603 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500604
Jamie Madill0448ec82016-12-23 13:41:47 -0500605 // Gather global layer properties.
606 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400607 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500608
609 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
610 if (instanceLayerCount > 0)
611 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400612 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
613 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500614 }
615
Jamie Madille09bd5d2016-11-29 16:20:35 -0500616 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400617 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400618 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500619
620 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
621 if (instanceExtensionCount > 0)
622 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400623 ANGLE_VK_TRY(displayVk,
624 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
625 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500626 }
627
Yuly Novikov199f4292018-01-19 19:04:05 -0500628 const char *const *enabledLayerNames = nullptr;
629 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500630 if (mEnableValidationLayers)
631 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500632 bool layersRequested =
633 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
634 mEnableValidationLayers = GetAvailableValidationLayers(
635 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500636 }
637
Jamie Madille09bd5d2016-11-29 16:20:35 -0500638 std::vector<const char *> enabledInstanceExtensions;
639 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500640 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500641
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500642 bool enableDebugUtils =
643 mEnableValidationLayers &&
644 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
645 bool enableDebugReport =
646 mEnableValidationLayers && !enableDebugUtils &&
647 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
648
649 if (enableDebugUtils)
650 {
651 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
652 }
653 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500654 {
655 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
656 }
657
Jamie Madille09bd5d2016-11-29 16:20:35 -0500658 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400659 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400660 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500661
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400662 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500663 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500664 applicationInfo.pApplicationName = "ANGLE";
665 applicationInfo.applicationVersion = 1;
666 applicationInfo.pEngineName = "ANGLE";
667 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700668
669 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
670 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
671 if (!enumerateInstanceVersion)
672 {
673 applicationInfo.apiVersion = VK_API_VERSION_1_0;
674 }
675 else
676 {
677 uint32_t apiVersion = VK_API_VERSION_1_0;
678 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
679 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
680 {
681 // Note: will need to revisit this with Vulkan 1.2+.
682 applicationInfo.apiVersion = VK_API_VERSION_1_1;
683 }
684 else
685 {
686 applicationInfo.apiVersion = VK_API_VERSION_1_0;
687 }
688 }
Jamie Madill327ba852016-11-30 12:38:28 -0500689
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400690 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500691 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
692 instanceInfo.flags = 0;
693 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500694
Jamie Madille09bd5d2016-11-29 16:20:35 -0500695 // Enable requested layers and extensions.
696 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
697 instanceInfo.ppEnabledExtensionNames =
698 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500699 instanceInfo.enabledLayerCount = enabledLayerCount;
700 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500701
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400702 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500703
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500704 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500705 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500706 // Try to use the newer EXT_debug_utils if it exists.
707 InitDebugUtilsEXTFunctions(mInstance);
708
709 // Create the messenger callback.
710 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
711
712 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
713 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
714 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
715 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
716 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
717 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
718 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
719 messengerInfo.pUserData = this;
720
721 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
722 &mDebugUtilsMessenger));
723 }
724 else if (enableDebugReport)
725 {
726 // Fallback to EXT_debug_report.
727 InitDebugReportEXTFunctions(mInstance);
728
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400729 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500730
731 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500732 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500733 debugReportInfo.pfnCallback = &DebugReportCallback;
734 debugReportInfo.pUserData = this;
735
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500736 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
737 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500738 }
739
Jamie Madill4d0bf552016-12-28 15:45:24 -0500740 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400741 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
742 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500743
744 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700745 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400746 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
747 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400748 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700749 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500750
Jamie Madill30b5d842018-08-31 17:19:12 -0400751 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
752
Jamie Madill4d0bf552016-12-28 15:45:24 -0500753 // Ensure we can find a graphics queue family.
754 uint32_t queueCount = 0;
755 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
756
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400757 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500758
759 mQueueFamilyProperties.resize(queueCount);
760 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
761 mQueueFamilyProperties.data());
762
Jamie Madillb980c562018-11-27 11:34:27 -0500763 size_t graphicsQueueFamilyCount = false;
764 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500765 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500766 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
767 {
768 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500769 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500770 {
771 ASSERT(queueInfo.queueCount > 0);
772 graphicsQueueFamilyCount++;
773 if (firstGraphicsQueueFamily == 0)
774 {
775 firstGraphicsQueueFamily = familyIndex;
776 }
777 break;
778 }
779 }
780
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400781 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500782
783 // If only one queue family, go ahead and initialize the device. If there is more than one
784 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
785 if (graphicsQueueFamilyCount == 1)
786 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400787 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500788 }
789
Jamie Madill035fd6b2017-10-03 15:43:22 -0400790 // Store the physical device memory properties so we can find the right memory pools.
791 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500792
Jamie Madill06ca6342018-07-12 15:56:53 -0400793 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500794
Jamie Madill6a89d222017-11-02 11:59:51 -0400795 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500796 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400797
Jamie Madill7c985f52018-11-29 18:16:17 -0500798 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400799}
800
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400801angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500802{
803 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400804 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400805 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500806
807 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
808 if (deviceLayerCount > 0)
809 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400810 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
811 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500812 }
813
814 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400815 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
816 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500817
818 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
819 if (deviceExtensionCount > 0)
820 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400821 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
822 &deviceExtensionCount,
823 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500824 }
825
Yuly Novikov199f4292018-01-19 19:04:05 -0500826 const char *const *enabledLayerNames = nullptr;
827 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500828 if (mEnableValidationLayers)
829 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500830 mEnableValidationLayers = GetAvailableValidationLayers(
831 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500832 }
833
834 std::vector<const char *> enabledDeviceExtensions;
835 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
836
Ian Elliottbcb78902018-12-19 11:46:29 -0700837 initFeatures(deviceExtensionProps);
838 mFeaturesInitialized = true;
839
Luc Ferronbf6dc372018-06-28 15:24:19 -0400840 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700841 if ((getFeatures().flipViewportY) &&
842 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400843 {
844 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
845 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700846 if (getFeatures().supportsIncrementalPresent)
847 {
848 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
849 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400850
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400851 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500852
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400853 // Select additional features to be enabled
854 VkPhysicalDeviceFeatures enabledFeatures = {};
855 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500856 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400857
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400858 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500859
860 float zeroPriority = 0.0f;
861
862 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500863 queueCreateInfo.flags = 0;
864 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
865 queueCreateInfo.queueCount = 1;
866 queueCreateInfo.pQueuePriorities = &zeroPriority;
867
868 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400869 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500870
Jamie Madill50cf2be2018-06-15 09:46:57 -0400871 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400872 createInfo.flags = 0;
873 createInfo.queueCreateInfoCount = 1;
874 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500875 createInfo.enabledLayerCount = enabledLayerCount;
876 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500877 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
878 createInfo.ppEnabledExtensionNames =
879 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400880 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500881
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400882 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500883
884 mCurrentQueueFamilyIndex = queueFamilyIndex;
885
886 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
887
888 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400889 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500890 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
891 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
892 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500893
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000894 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400895
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400896 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500897 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500898
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400899 // Initialize the submission semaphore pool.
900 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
901
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400902#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
903 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
904 ASSERT(platform);
905
906 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
907 // platform discovery.
908 const unsigned char *gpuEventsEnabled =
909 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
910 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
911#endif
912
913 if (mGpuEventsEnabled)
914 {
915 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
916 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
917 vk::kDefaultTimestampQueryPoolSize));
918 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
919 }
920
Jamie Madill7c985f52018-11-29 18:16:17 -0500921 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500922}
923
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400924angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400925 VkSurfaceKHR surface,
926 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500927{
928 // We've already initialized a device, and can't re-create it unless it's never been used.
929 // TODO(jmadill): Handle the re-creation case if necessary.
930 if (mDevice != VK_NULL_HANDLE)
931 {
932 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
933
934 // Check if the current device supports present on this surface.
935 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400936 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400937 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500938 surface, &supportsPresent));
939
Jamie Madill6cad7732018-07-11 09:01:17 -0400940 if (supportsPresent == VK_TRUE)
941 {
942 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500943 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400944 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500945 }
946
947 // Find a graphics and present queue.
948 Optional<uint32_t> newPresentQueue;
949 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500950 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500951 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
952 {
953 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500954 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500955 {
956 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400957 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
958 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500959
960 if (supportsPresent == VK_TRUE)
961 {
962 newPresentQueue = queueIndex;
963 break;
964 }
965 }
966 }
967
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400968 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
969 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500970
Jamie Madill6cad7732018-07-11 09:01:17 -0400971 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500972 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500973}
974
975std::string RendererVk::getVendorString() const
976{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300977 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500978}
979
Jamie Madille09bd5d2016-11-29 16:20:35 -0500980std::string RendererVk::getRendererDescription() const
981{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500982 std::stringstream strstr;
983
984 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
985
986 strstr << "Vulkan ";
987 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
988 strstr << VK_VERSION_MINOR(apiVersion) << ".";
989 strstr << VK_VERSION_PATCH(apiVersion);
990
Olli Etuahoc6a06182018-04-13 14:11:46 +0300991 strstr << "(";
992
993 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
994 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
995 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
996 // driver detection.
997 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
998 {
999 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1000 }
1001
Geoff Langa7af56b2018-12-14 14:20:28 -05001002 strstr << mPhysicalDeviceProperties.deviceName;
1003 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1004
1005 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001006
1007 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001008}
1009
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001010gl::Version RendererVk::getMaxSupportedESVersion() const
1011{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001012 // Current highest supported version
1013 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1014 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001015
Geoff Lang0c2c9232019-01-14 16:01:38 -05001016 // Vulkan inherited queries are required to support any GL query type
1017 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001018 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001019 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001020 }
1021
Geoff Lang0c2c9232019-01-14 16:01:38 -05001022 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001023}
1024
Ian Elliottbcb78902018-12-19 11:46:29 -07001025void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001026{
Jamie Madillb36a4812018-09-25 10:15:11 -04001027// Use OpenGL line rasterization rules by default.
1028// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1029#if defined(ANGLE_PLATFORM_ANDROID)
1030 mFeatures.basicGLLineRasterization = false;
1031#else
Jamie Madill12222072018-07-11 14:59:48 -04001032 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001033#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001034
Ian Elliott52f5da42018-12-21 09:02:09 -07001035 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1036 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001037 {
1038 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1039 // investigation. http://anglebug.com/2728
1040 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1041 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001042
1043#ifdef ANGLE_PLATFORM_WINDOWS
1044 // http://anglebug.com/2838
1045 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001046
1047 // http://anglebug.com/3055
1048 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001049#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001050
1051 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1052 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001053
1054 // Work around incorrect NVIDIA point size range clamping.
1055 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1056 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1057 {
1058 mFeatures.clampPointSize = true;
1059 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001060
Jamie Madillfa7ca182019-01-15 11:20:58 -05001061 // We also need to clamp point size on several Android drivers.
1062 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1063 if (IsAndroid())
1064 {
1065 mFeatures.clampPointSize = true;
1066 }
1067
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001068#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001069 // Work around ineffective compute-graphics barriers on Nexus 5X.
1070 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1071 // http://anglebug.com/3019
1072 mFeatures.flushAfterVertexConversion =
1073 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001074#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001075
1076 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1077 {
1078 mFeatures.supportsIncrementalPresent = true;
1079 }
Jamie Madill12222072018-07-11 14:59:48 -04001080}
1081
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001082void RendererVk::initPipelineCacheVkKey()
1083{
1084 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1085 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1086 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1087 // there is no '\0' in the result.
1088 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1089 {
1090 hashStream << std::hex << c;
1091 }
1092 // Add the vendor and device id too for good measure.
1093 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1094 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1095
1096 const std::string &hashString = hashStream.str();
1097 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1098 hashString.length(), mPipelineCacheVkBlobKey.data());
1099}
1100
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001101angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001102{
1103 initPipelineCacheVkKey();
1104
1105 egl::BlobCache::Value initialData;
1106 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1107 mPipelineCacheVkBlobKey, &initialData);
1108
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001109 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001110
1111 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001112 pipelineCacheCreateInfo.flags = 0;
1113 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1114 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1115
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001116 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001117 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001118}
1119
Jamie Madillacccc6c2016-05-03 17:22:10 -04001120void RendererVk::ensureCapsInitialized() const
1121{
1122 if (!mCapsInitialized)
1123 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001124 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1125 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1126 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001127 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001128 mCapsInitialized = true;
1129 }
1130}
1131
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001132void RendererVk::getSubmitWaitSemaphores(
1133 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001134 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1135 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001136{
1137 if (mSubmitLastSignaledSemaphore.getSemaphore())
1138 {
1139 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001140 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001141
1142 // Return the semaphore to the pool (which will remain valid and unused until the
1143 // queue it's about to be waited on has finished execution).
1144 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1145 }
1146
1147 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1148 {
1149 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001150 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1151
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001152 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1153 }
1154 mSubmitWaitSemaphores.clear();
1155}
1156
Jamie Madillacccc6c2016-05-03 17:22:10 -04001157const gl::Caps &RendererVk::getNativeCaps() const
1158{
1159 ensureCapsInitialized();
1160 return mNativeCaps;
1161}
1162
1163const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1164{
1165 ensureCapsInitialized();
1166 return mNativeTextureCaps;
1167}
1168
1169const gl::Extensions &RendererVk::getNativeExtensions() const
1170{
1171 ensureCapsInitialized();
1172 return mNativeExtensions;
1173}
1174
1175const gl::Limitations &RendererVk::getNativeLimitations() const
1176{
1177 ensureCapsInitialized();
1178 return mNativeLimitations;
1179}
1180
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001181uint32_t RendererVk::getMaxActiveTextures()
1182{
1183 // TODO(lucferron): expose this limitation to GL in Context Caps
1184 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1185 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1186}
1187
Jamie Madill49ac74b2017-12-21 14:42:33 -05001188const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001189{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001190 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001191}
1192
Jamie Madill21061022018-07-12 23:56:30 -04001193angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001194{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001195 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001196 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001197 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1198
Luc Ferron1617e692018-07-11 11:08:19 -04001199 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1200 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001201
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001202 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001203 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1204 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001205
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001206 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001207 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001208 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1209 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001210 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001211 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001212 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001213 submitInfo.signalSemaphoreCount = 0;
1214 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001215
Jamie Madill21061022018-07-12 23:56:30 -04001216 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001217 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001218
Jamie Madill4c26fc22017-02-24 11:04:10 -05001219 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001220 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001221 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001222
1223 if (mGpuEventsEnabled)
1224 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001225 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001226 while (mInFlightGpuEventQueries.size() > 0)
1227 {
1228 ANGLE_TRY(checkCompletedGpuEvents(context));
1229 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001230 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1231 // synchronization if there is no event to be adjusted (happens when finish() gets called
1232 // multiple times towards the end of the application).
1233 if (mGpuEvents.size() > 0)
1234 {
1235 ANGLE_TRY(synchronizeCpuGpuTime(context));
1236 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001237 }
1238
Jamie Madill7c985f52018-11-29 18:16:17 -05001239 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001240}
1241
Jamie Madill0c0dc342017-03-24 14:18:51 -04001242void RendererVk::freeAllInFlightResources()
1243{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001244 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001245 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001246 // On device loss we need to wait for fence to be signaled before destroying it
1247 if (mDeviceLost)
1248 {
1249 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1250 // If wait times out, it is probably not possible to recover from lost device
1251 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1252 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001253 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001254 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001255 }
1256 mInFlightCommands.clear();
1257
1258 for (auto &garbage : mGarbage)
1259 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001260 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001261 }
1262 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001263
1264 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001265}
1266
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001267angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001268{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001269 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001270
Jamie Madill49ac74b2017-12-21 14:42:33 -05001271 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001272 {
Yuly Novikov27780292018-11-09 11:19:49 -05001273 VkResult result = batch.fence.getStatus(mDevice);
1274 if (result == VK_NOT_READY)
1275 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001276 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001277 }
1278 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001279
Jamie Madill49ac74b2017-12-21 14:42:33 -05001280 ASSERT(batch.serial > mLastCompletedQueueSerial);
1281 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001282
Jamie Madill49ac74b2017-12-21 14:42:33 -05001283 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001284 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001285 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001286 }
1287
Jamie Madill49ac74b2017-12-21 14:42:33 -05001288 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001289
1290 size_t freeIndex = 0;
1291 for (; freeIndex < mGarbage.size(); ++freeIndex)
1292 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001293 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001294 break;
1295 }
1296
1297 // Remove the entries from the garbage list - they should be ready to go.
1298 if (freeIndex > 0)
1299 {
1300 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001301 }
1302
Jamie Madill7c985f52018-11-29 18:16:17 -05001303 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001304}
1305
Jamie Madill21061022018-07-12 23:56:30 -04001306angle::Result RendererVk::submitFrame(vk::Context *context,
1307 const VkSubmitInfo &submitInfo,
1308 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001309{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001310 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001311 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001312 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1313 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001314
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001315 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001316 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001317 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318
Jamie Madill21061022018-07-12 23:56:30 -04001319 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001320
1321 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001322 batch.commandPool = std::move(mCommandPool);
1323 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001324
Jamie Madillbea35a62018-07-05 11:54:10 -04001325 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001326
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001327 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1328 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001329 // so the limit is larger than the expected number of images. The
1330 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001331 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001332
Jamie Madill85ca1892019-01-16 13:27:15 -05001333 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001334
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001335 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001336
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001337 if (mGpuEventsEnabled)
1338 {
1339 ANGLE_TRY(checkCompletedGpuEvents(context));
1340 }
1341
Jamie Madill49ac74b2017-12-21 14:42:33 -05001342 // Simply null out the command buffer here - it was allocated using the command pool.
1343 commandBuffer.releaseHandle();
1344
1345 // Reallocate the command pool for next frame.
1346 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001347 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001348 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001349 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001350 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001351
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001352 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001353 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001354}
1355
Jamie Madill85ca1892019-01-16 13:27:15 -05001356void RendererVk::nextSerial()
1357{
1358 // Increment the queue serial. If this fails, we should restart ANGLE.
1359 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1360 mCurrentQueueSerial = mQueueSerialFactory.generate();
1361
1362 // Notify the Contexts that they should be starting new command buffers.
1363 // We use one command pool per serial/submit associated with this VkQueue. We can also
1364 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1365 // check for a new serial when starting a new command buffer. We just check that the current
1366 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1367 // using this VkQueue that they their current command buffer is no longer valid.
1368 for (gl::Context *context : mDisplay->getContextSet())
1369 {
1370 ContextVk *contextVk = vk::GetImpl(context);
1371 contextVk->onCommandBufferFinished();
1372 }
1373}
1374
Jamie Madillaaca96e2018-06-12 10:19:48 -04001375bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001376{
1377 return serial > mLastCompletedQueueSerial;
1378}
1379
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001380angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1381{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001382 bool timedOut = false;
1383 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1384
1385 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1386 if (timedOut)
1387 {
1388 result = angle::Result::Stop;
1389 }
1390 return result;
1391}
1392
1393angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1394 Serial serial,
1395 uint64_t timeout,
1396 bool *outTimedOut)
1397{
1398 *outTimedOut = false;
1399
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001400 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1401 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001402 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001403 }
1404
1405 // Find the first batch with serial equal to or bigger than given serial (note that
1406 // the batch serials are unique, otherwise upper-bound would have been necessary).
1407 size_t batchIndex = mInFlightCommands.size() - 1;
1408 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1409 {
1410 if (mInFlightCommands[i].serial >= serial)
1411 {
1412 batchIndex = i;
1413 break;
1414 }
1415 }
1416 const CommandBatch &batch = mInFlightCommands[batchIndex];
1417
1418 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001419 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1420
1421 // If timed out, report it as such.
1422 if (status == VK_TIMEOUT)
1423 {
1424 *outTimedOut = true;
1425 return angle::Result::Continue;
1426 }
1427
1428 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001429
1430 // Clean up finished batches.
1431 return checkCompletedCommands(context);
1432}
1433
Jamie Madill21061022018-07-12 23:56:30 -04001434angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1435 const vk::RenderPassDesc &desc,
1436 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001437{
Jamie Madill21061022018-07-12 23:56:30 -04001438 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001439 renderPassOut);
1440}
1441
Jamie Madill21061022018-07-12 23:56:30 -04001442angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1443 const vk::RenderPassDesc &desc,
1444 const vk::AttachmentOpsArray &ops,
1445 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001446{
Jamie Madill21061022018-07-12 23:56:30 -04001447 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001448 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001449}
1450
Jamie Madilla5e06072018-05-18 14:36:05 -04001451vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001452{
Jamie Madilla5e06072018-05-18 14:36:05 -04001453 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001454}
1455
Jamie Madill21061022018-07-12 23:56:30 -04001456angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001457{
Jamie Madill21061022018-07-12 23:56:30 -04001458 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001459 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001460}
1461
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001462angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001463{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001464 if (mCommandGraph.empty())
1465 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001466 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001467 }
1468
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001469 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1470
Jamie Madillbea35a62018-07-05 11:54:10 -04001471 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1472 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001473
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001474 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001475 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1476 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001477
1478 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1479 // will be waited on.
1480 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001481
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001482 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001483 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001484 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1485 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001486 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001487 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001488 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001489 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001490 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001491
Jamie Madill21061022018-07-12 23:56:30 -04001492 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001493
Jamie Madill7c985f52018-11-29 18:16:17 -05001494 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001495}
1496
Jamie Madill78feddc2018-04-27 11:45:05 -04001497Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001498{
Jamie Madill78feddc2018-04-27 11:45:05 -04001499 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001500}
1501
Jamie Madill21061022018-07-12 23:56:30 -04001502angle::Result RendererVk::getDescriptorSetLayout(
1503 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001504 const vk::DescriptorSetLayoutDesc &desc,
1505 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1506{
Jamie Madill21061022018-07-12 23:56:30 -04001507 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001508}
1509
Jamie Madill21061022018-07-12 23:56:30 -04001510angle::Result RendererVk::getPipelineLayout(
1511 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001512 const vk::PipelineLayoutDesc &desc,
1513 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1514 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1515{
Jamie Madill21061022018-07-12 23:56:30 -04001516 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001517 pipelineLayoutOut);
1518}
1519
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001520angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1521{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001522 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001523
1524 if (--mPipelineCacheVkUpdateTimeout > 0)
1525 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001526 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001527 }
1528
1529 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1530
1531 // Get the size of the cache.
1532 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001533 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001534 if (result != VK_INCOMPLETE)
1535 {
1536 ANGLE_VK_TRY(displayVk, result);
1537 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001538
1539 angle::MemoryBuffer *pipelineCacheData = nullptr;
1540 ANGLE_VK_CHECK_ALLOC(displayVk,
1541 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1542
1543 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001544 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001545 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1546 // was determined just above), so receiving it hints at an implementation bug we would want
1547 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001548 ASSERT(result != VK_INCOMPLETE);
1549 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001550
1551 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1552 // the buffer to avoid leaking garbage memory.
1553 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1554 if (pipelineCacheSize < originalPipelineCacheSize)
1555 {
1556 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1557 originalPipelineCacheSize - pipelineCacheSize);
1558 }
1559
1560 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1561
Jamie Madill7c985f52018-11-29 18:16:17 -05001562 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001563}
1564
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001565angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1566 const vk::Semaphore **outSemaphore)
1567{
1568 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1569
1570 vk::SemaphoreHelper semaphore;
1571 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1572
1573 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1574 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1575
Jamie Madill7c985f52018-11-29 18:16:17 -05001576 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001577}
1578
1579const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1580{
1581 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1582
1583 // Return the semaphore to the pool (which will remain valid and unused until the
1584 // queue it's about to be waited on has finished execution). The caller is about
1585 // to wait on it.
1586 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1587
1588 return semaphore;
1589}
1590
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001591angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1592{
1593 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1594 // that seems impossible, so instead, we are going to make a small submission with just a
1595 // timestamp query. First, the disjoint timer query extension says:
1596 //
1597 // > This will return the GL time after all previous commands have reached the GL server but
1598 // have not yet necessarily executed.
1599 //
1600 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1601 // The wording allows us to make a submission to get the timestamp without performing a flush.
1602 //
1603 // Second:
1604 //
1605 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1606 // object target, applications can measure the latency between when commands reach the GL server
1607 // and when they are realized in the framebuffer.
1608 //
1609 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1610 // GPU bubble. This function directly generates a command buffer and submits it instead of
1611 // using the other member functions. This is to avoid changing any state, such as the queue
1612 // serial.
1613
1614 // Create a query used to receive the GPU timestamp
1615 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1616 vk::QueryHelper timestampQuery;
1617 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1618 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1619
1620 // Record the command buffer
1621 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1622 vk::CommandBuffer &commandBuffer = commandBatch.get();
1623
1624 VkCommandBufferAllocateInfo commandBufferInfo = {};
1625 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1626 commandBufferInfo.commandPool = mCommandPool.getHandle();
1627 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1628 commandBufferInfo.commandBufferCount = 1;
1629
Yuly Novikov27780292018-11-09 11:19:49 -05001630 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001631
1632 VkCommandBufferBeginInfo beginInfo = {};
1633 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1634 beginInfo.flags = 0;
1635 beginInfo.pInheritanceInfo = nullptr;
1636
Yuly Novikov27780292018-11-09 11:19:49 -05001637 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001638
1639 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1640 timestampQuery.getQuery(), 1);
1641 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1642 timestampQuery.getQueryPool()->getHandle(),
1643 timestampQuery.getQuery());
1644
Yuly Novikov27780292018-11-09 11:19:49 -05001645 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001646
1647 // Create fence for the submission
1648 VkFenceCreateInfo fenceInfo = {};
1649 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1650 fenceInfo.flags = 0;
1651
1652 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001653 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001654
1655 // Submit the command buffer
1656 VkSubmitInfo submitInfo = {};
1657 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1658 submitInfo.waitSemaphoreCount = 0;
1659 submitInfo.pWaitSemaphores = nullptr;
1660 submitInfo.pWaitDstStageMask = nullptr;
1661 submitInfo.commandBufferCount = 1;
1662 submitInfo.pCommandBuffers = commandBuffer.ptr();
1663 submitInfo.signalSemaphoreCount = 0;
1664 submitInfo.pSignalSemaphores = nullptr;
1665
1666 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1667
1668 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1669 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001670 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001671
1672 // Get the query results
1673 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1674
Yuly Novikov27780292018-11-09 11:19:49 -05001675 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1676 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1677 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001678
1679 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1680
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001681 // Convert results to nanoseconds.
1682 *timestampOut = static_cast<uint64_t>(
1683 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1684
Jamie Madill7c985f52018-11-29 18:16:17 -05001685 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001686}
1687
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001688// These functions look at the mandatory format for support, and fallback to querying the device (if
1689// necessary) to test the availability of the bits.
1690bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1691 const VkFormatFeatureFlags featureBits)
1692{
1693 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1694}
1695
1696bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1697 const VkFormatFeatureFlags featureBits)
1698{
1699 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1700}
1701
1702bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1703{
1704 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1705}
1706
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001707angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1708{
1709 ASSERT(mGpuEventsEnabled);
1710
1711 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1712 ASSERT(platform);
1713
1714 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1715 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1716 //
1717 // CPU GPU
1718 //
1719 // Record command buffer
1720 // with timestamp query
1721 //
1722 // Submit command buffer
1723 //
1724 // Post-submission work Begin execution
1725 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001726 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001727 //
1728 // ???? End execution
1729 //
1730 // ???? Return query results
1731 //
1732 // ????
1733 //
1734 // Get query results
1735 //
1736 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1737 // finished post-submission work while the GPU is executing in parallel. With no further work,
1738 // querying CPU timestamps before submission and after getting query results give the bounds to
1739 // Tgpu, which could be quite large.
1740 //
1741 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1742 // reduce this range. This function implements the following procedure:
1743 //
1744 // CPU GPU
1745 //
1746 // Record command buffer
1747 // with timestamp query
1748 //
1749 // Submit command buffer
1750 //
1751 // Post-submission work Begin execution
1752 //
1753 // ???? Set Event GPUReady
1754 //
1755 // Wait on Event GPUReady Wait on Event CPUReady
1756 //
1757 // Get CPU Time Ts Wait on Event CPUReady
1758 //
1759 // Set Event CPUReady Wait on Event CPUReady
1760 //
1761 // Get CPU Time Tcpu Get GPU Time Tgpu
1762 //
1763 // Wait on Event GPUDone Set Event GPUDone
1764 //
1765 // Get CPU Time Te End Execution
1766 //
1767 // Idle Return query results
1768 //
1769 // Get query results
1770 //
1771 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1772 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1773 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1774 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1775 // calibration.
1776 //
1777 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1778
1779 // Make sure nothing is running
1780 ASSERT(mCommandGraph.empty());
1781
1782 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1783
1784 // Create a query used to receive the GPU timestamp
1785 vk::QueryHelper timestampQuery;
1786 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1787
1788 // Create the three events
1789 VkEventCreateInfo eventCreateInfo = {};
1790 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1791 eventCreateInfo.flags = 0;
1792
1793 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001794 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1795 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1796 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001797
1798 constexpr uint32_t kRetries = 10;
1799
1800 // Time suffixes used are S for seconds and Cycles for cycles
1801 double tightestRangeS = 1e6f;
1802 double TcpuS = 0;
1803 uint64_t TgpuCycles = 0;
1804 for (uint32_t i = 0; i < kRetries; ++i)
1805 {
1806 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001807 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1808 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1809 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001810
1811 // Record the command buffer
1812 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1813 vk::CommandBuffer &commandBuffer = commandBatch.get();
1814
1815 VkCommandBufferAllocateInfo commandBufferInfo = {};
1816 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1817 commandBufferInfo.commandPool = mCommandPool.getHandle();
1818 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1819 commandBufferInfo.commandBufferCount = 1;
1820
Yuly Novikov27780292018-11-09 11:19:49 -05001821 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001822
1823 VkCommandBufferBeginInfo beginInfo = {};
1824 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1825 beginInfo.flags = 0;
1826 beginInfo.pInheritanceInfo = nullptr;
1827
Yuly Novikov27780292018-11-09 11:19:49 -05001828 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001829
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001830 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001831 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1832 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1833 nullptr);
1834
1835 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1836 timestampQuery.getQuery(), 1);
1837 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1838 timestampQuery.getQueryPool()->getHandle(),
1839 timestampQuery.getQuery());
1840
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001841 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001842
Yuly Novikov27780292018-11-09 11:19:49 -05001843 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001844
1845 // Submit the command buffer
1846 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1847 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1848 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1849
1850 VkSubmitInfo submitInfo = {};
1851 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1852 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1853 submitInfo.pWaitSemaphores = waitSemaphores.data();
1854 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1855 submitInfo.commandBufferCount = 1;
1856 submitInfo.pCommandBuffers = commandBuffer.ptr();
1857 submitInfo.signalSemaphoreCount = 0;
1858 submitInfo.pSignalSemaphores = nullptr;
1859
1860 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1861
1862 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001863 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001864 do
1865 {
Yuly Novikov27780292018-11-09 11:19:49 -05001866 result = gpuReady.get().getStatus(mDevice);
1867 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1868 {
1869 ANGLE_VK_TRY(context, result);
1870 }
1871 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001872
1873 double TsS = platform->monotonicallyIncreasingTime(platform);
1874
1875 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001876 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001877 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1878
1879 // Wait for GPU to be done. Another short busy wait.
1880 do
1881 {
Yuly Novikov27780292018-11-09 11:19:49 -05001882 result = gpuDone.get().getStatus(mDevice);
1883 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1884 {
1885 ANGLE_VK_TRY(context, result);
1886 }
1887 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001888
1889 double TeS = platform->monotonicallyIncreasingTime(platform);
1890
1891 // Get the query results
1892 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1893
1894 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1895
1896 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001897 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1898 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1899 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001900
1901 // Use the first timestamp queried as origin.
1902 if (mGpuEventTimestampOrigin == 0)
1903 {
1904 mGpuEventTimestampOrigin = gpuTimestampCycles;
1905 }
1906
1907 // Take these CPU and GPU timestamps if there is better confidence.
1908 double confidenceRangeS = TeS - TsS;
1909 if (confidenceRangeS < tightestRangeS)
1910 {
1911 tightestRangeS = confidenceRangeS;
1912 TcpuS = cpuTimestampS;
1913 TgpuCycles = gpuTimestampCycles;
1914 }
1915 }
1916
1917 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1918
1919 // timestampPeriod gives nanoseconds/cycle.
1920 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1921 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1922 1'000'000'000.0;
1923
1924 flushGpuEvents(TgpuS, TcpuS);
1925
1926 mGpuClockSync.gpuTimestampS = TgpuS;
1927 mGpuClockSync.cpuTimestampS = TcpuS;
1928
Jamie Madill7c985f52018-11-29 18:16:17 -05001929 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001930}
1931
1932angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1933 vk::CommandBuffer *commandBuffer,
1934 char phase,
1935 const char *name)
1936{
1937 ASSERT(mGpuEventsEnabled);
1938
1939 GpuEventQuery event;
1940
1941 event.name = name;
1942 event.phase = phase;
1943 event.serial = mCurrentQueueSerial;
1944
1945 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1946
1947 commandBuffer->resetQueryPool(
1948 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1949 commandBuffer->writeTimestamp(
1950 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1951 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1952
1953 mInFlightGpuEventQueries.push_back(std::move(event));
1954
Jamie Madill7c985f52018-11-29 18:16:17 -05001955 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001956}
1957
1958angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1959{
1960 ASSERT(mGpuEventsEnabled);
1961
1962 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1963 ASSERT(platform);
1964
1965 int finishedCount = 0;
1966
1967 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1968 {
1969 // Only check the timestamp query if the submission has finished.
1970 if (eventQuery.serial > mLastCompletedQueueSerial)
1971 {
1972 break;
1973 }
1974
1975 // See if the results are available.
1976 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001977 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1978 ->getResults(mDevice, eventQuery.queryIndex, 1,
1979 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1980 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1981 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001982 {
1983 break;
1984 }
Yuly Novikov27780292018-11-09 11:19:49 -05001985 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001986
1987 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1988
1989 GpuEvent event;
1990 event.gpuTimestampCycles = gpuTimestampCycles;
1991 event.name = eventQuery.name;
1992 event.phase = eventQuery.phase;
1993
1994 mGpuEvents.emplace_back(event);
1995
1996 ++finishedCount;
1997 }
1998
1999 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2000 mInFlightGpuEventQueries.begin() + finishedCount);
2001
Jamie Madill7c985f52018-11-29 18:16:17 -05002002 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002003}
2004
2005void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2006{
2007 if (mGpuEvents.size() == 0)
2008 {
2009 return;
2010 }
2011
2012 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2013 ASSERT(platform);
2014
2015 // Find the slope of the clock drift for adjustment
2016 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2017 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2018 double gpuSyncDriftSlope = 0;
2019
2020 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2021 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2022
2023 // No gpu trace events should have been generated before the clock sync, so if there is no
2024 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2025 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2026 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2027
2028 gpuSyncDriftSlope =
2029 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2030
2031 for (const GpuEvent &event : mGpuEvents)
2032 {
2033 double gpuTimestampS =
2034 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2035 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2036
2037 // Account for clock drift.
2038 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2039
2040 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2041 // for.
2042 static long long eventId = 1;
2043 static const unsigned char *categoryEnabled =
2044 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2045 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2046 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2047 }
2048
2049 mGpuEvents.clear();
2050}
2051
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002052template <VkFormatFeatureFlags VkFormatProperties::*features>
2053bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2054{
2055 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2056 VkFormatProperties &deviceProperties = mFormatProperties[format];
2057
2058 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2059 {
2060 // If we don't have the actual device features, see if the requested features are mandatory.
2061 // If so, there's no need to query the device.
2062 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2063 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2064 {
2065 return true;
2066 }
2067
2068 // Otherwise query the format features and cache it.
2069 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2070 }
2071
2072 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2073}
2074
Jamie Madillaaca96e2018-06-12 10:19:48 -04002075uint32_t GetUniformBufferDescriptorCount()
2076{
2077 return kUniformBufferDescriptorsPerDescriptorSet;
2078}
2079
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002080} // namespace rx