blob: 150e31d5e39bec51306d7933da7c4b72a19a0de9 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Shahbaz Youssefi61656022018-10-24 15:00:50 -040034#include "third_party/trace_event/trace_event.h"
35
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070036// Consts
37namespace
38{
Jamie Madill7c985f52018-11-29 18:16:17 -050039const uint32_t kMockVendorID = 0xba5eba11;
40const uint32_t kMockDeviceID = 0xf005ba11;
41constexpr char kMockDeviceName[] = "Vulkan Mock Device";
42constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050043constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070044} // anonymous namespace
45
Jamie Madill9e54b5a2016-05-25 12:57:39 -040046namespace rx
47{
48
Jamie Madille09bd5d2016-11-29 16:20:35 -050049namespace
50{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040051// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
52// one for the vertex shader.
53constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040054// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050055constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040056// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050057constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050058
Omar El Sheikh26c61b22018-06-29 12:50:59 -060059bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
60{
61#if !defined(ANGLE_PLATFORM_ANDROID)
62 // Mock ICD does not currently run on Android
63 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
64 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
66#else
67 return false;
68#endif // !defined(ANGLE_PLATFORM_ANDROID)
69}
70
Jamie Madille09bd5d2016-11-29 16:20:35 -050071VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
72 const std::vector<const char *> &enabledExtensionNames)
73{
74 // Compile the extensions names into a set.
75 std::set<std::string> extensionNames;
76 for (const auto &extensionProp : extensionProps)
77 {
78 extensionNames.insert(extensionProp.extensionName);
79 }
80
Jamie Madillacf2f3a2017-11-21 19:22:44 -050081 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050082 {
83 if (extensionNames.count(extensionName) == 0)
84 {
85 return VK_ERROR_EXTENSION_NOT_PRESENT;
86 }
87 }
88
89 return VK_SUCCESS;
90}
91
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050092bool ExtensionFound(const char *extensionName,
93 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060094{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050095 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060096 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050097 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060098 {
99 return true;
100 }
101 }
102 return false;
103}
104
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500105// Array of Validation error/warning messages that will be ignored, should include bugID
106constexpr std::array<const char *, 1> kSkippedMessages = {
107 // http://anglebug.com/2796
108 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
109
110// Suppress validation errors that are known
111// return "true" if given code/prefix/message is known, else return "false"
112bool IsIgnoredDebugMessage(const char *message)
113{
Michael Spang25839802019-01-30 18:02:51 -0500114 if (!message)
115 {
116 return false;
117 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500118 for (const char *msg : kSkippedMessages)
119 {
120 if (strstr(message, msg) != nullptr)
121 {
122 return true;
123 }
124 }
125 return false;
126}
127
128const char *GetVkObjectTypeName(VkObjectType type)
129{
130 switch (type)
131 {
132 case VK_OBJECT_TYPE_UNKNOWN:
133 return "Unknown";
134 case VK_OBJECT_TYPE_INSTANCE:
135 return "Instance";
136 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
137 return "Physical Device";
138 case VK_OBJECT_TYPE_DEVICE:
139 return "Device";
140 case VK_OBJECT_TYPE_QUEUE:
141 return "Queue";
142 case VK_OBJECT_TYPE_SEMAPHORE:
143 return "Semaphore";
144 case VK_OBJECT_TYPE_COMMAND_BUFFER:
145 return "Command Buffer";
146 case VK_OBJECT_TYPE_FENCE:
147 return "Fence";
148 case VK_OBJECT_TYPE_DEVICE_MEMORY:
149 return "Device Memory";
150 case VK_OBJECT_TYPE_BUFFER:
151 return "Buffer";
152 case VK_OBJECT_TYPE_IMAGE:
153 return "Image";
154 case VK_OBJECT_TYPE_EVENT:
155 return "Event";
156 case VK_OBJECT_TYPE_QUERY_POOL:
157 return "Query Pool";
158 case VK_OBJECT_TYPE_BUFFER_VIEW:
159 return "Buffer View";
160 case VK_OBJECT_TYPE_IMAGE_VIEW:
161 return "Image View";
162 case VK_OBJECT_TYPE_SHADER_MODULE:
163 return "Shader Module";
164 case VK_OBJECT_TYPE_PIPELINE_CACHE:
165 return "Pipeline Cache";
166 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
167 return "Pipeline Layout";
168 case VK_OBJECT_TYPE_RENDER_PASS:
169 return "Render Pass";
170 case VK_OBJECT_TYPE_PIPELINE:
171 return "Pipeline";
172 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
173 return "Descriptor Set Layout";
174 case VK_OBJECT_TYPE_SAMPLER:
175 return "Sampler";
176 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
177 return "Descriptor Pool";
178 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
179 return "Descriptor Set";
180 case VK_OBJECT_TYPE_FRAMEBUFFER:
181 return "Framebuffer";
182 case VK_OBJECT_TYPE_COMMAND_POOL:
183 return "Command Pool";
184 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
185 return "Sampler YCbCr Conversion";
186 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
187 return "Descriptor Update Template";
188 case VK_OBJECT_TYPE_SURFACE_KHR:
189 return "Surface";
190 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
191 return "Swapchain";
192 case VK_OBJECT_TYPE_DISPLAY_KHR:
193 return "Display";
194 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
195 return "Display Mode";
196 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
197 return "Debug Report Callback";
198 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
199 return "Object Table";
200 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
201 return "Indirect Commands Layout";
202 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
203 return "Debug Utils Messenger";
204 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
205 return "Validation Cache";
206 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
207 return "Acceleration Structure";
208 default:
209 return "<Unrecognized>";
210 }
211}
212
213VKAPI_ATTR VkBool32 VKAPI_CALL
214DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
215 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
216 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
217 void *userData)
218{
219 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
220 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
221 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
222
223 // Check if we even care about this message.
224 if ((messageSeverity & kSeveritiesToLog) == 0)
225 {
226 return VK_FALSE;
227 }
228
229 // See if it's an issue we are aware of and don't want to be spammed about.
230 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
231 {
232 return VK_FALSE;
233 }
234
235 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500236 if (callbackData->pMessageIdName)
237 {
238 log << "[ " << callbackData->pMessageIdName << " ] ";
239 }
240 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500241
242 // Aesthetic value based on length of the function name, line number, etc.
243 constexpr size_t kStartIndent = 28;
244
245 // Output the debug marker hierarchy under which this error has occured.
246 size_t indent = kStartIndent;
247 if (callbackData->queueLabelCount > 0)
248 {
249 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
250 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
251 {
252 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
253 << std::endl;
254 }
255 }
256 if (callbackData->cmdBufLabelCount > 0)
257 {
258 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
259 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
260 {
261 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
262 << std::endl;
263 }
264 }
265 // Output the objects involved in this error message.
266 if (callbackData->objectCount > 0)
267 {
268 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
269 {
270 const char *objectName = callbackData->pObjects[i].pObjectName;
271 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
272 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
273 log << std::string(indent, ' ') << "Object: ";
274 if (objectHandle == 0)
275 {
276 log << "VK_NULL_HANDLE";
277 }
278 else
279 {
280 log << "0x" << std::hex << objectHandle << std::dec;
281 }
282 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
283 if (objectName)
284 {
285 log << " [" << objectName << "]";
286 }
287 log << std::endl;
288 }
289 }
290
291 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
292
293 if (isError)
294 {
295 ERR() << log.str();
296 }
297 else
298 {
299 WARN() << log.str();
300 }
301
302 return VK_FALSE;
303}
304
Yuly Novikov199f4292018-01-19 19:04:05 -0500305VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
306 VkDebugReportObjectTypeEXT objectType,
307 uint64_t object,
308 size_t location,
309 int32_t messageCode,
310 const char *layerPrefix,
311 const char *message,
312 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500313{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600314 if (IsIgnoredDebugMessage(message))
315 {
316 return VK_FALSE;
317 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500318 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
319 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500320 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500321#if !defined(NDEBUG)
322 // Abort the call in Debug builds.
323 return VK_TRUE;
324#endif
325 }
326 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
327 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500328 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500329 }
330 else
331 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500332 // Uncomment this if you want Vulkan spam.
333 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500334 }
335
336 return VK_FALSE;
337}
338
Yuly Novikov199f4292018-01-19 19:04:05 -0500339// If we're loading the validation layers, we could be running from any random directory.
340// Change to the executable directory so we can find the layers, then change back to the
341// previous directory to be safe we don't disrupt the application.
342class ScopedVkLoaderEnvironment : angle::NonCopyable
343{
344 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600345 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
346 : mEnableValidationLayers(enableValidationLayers),
347 mEnableMockICD(enableMockICD),
348 mChangedCWD(false),
349 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500350 {
351// Changing CWD and setting environment variables makes no sense on Android,
352// since this code is a part of Java application there.
353// Android Vulkan loader doesn't need this either.
354#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600355 if (enableMockICD)
356 {
357 // Override environment variable to use built Mock ICD
358 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
359 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
360 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
361 if (!mChangedICDPath)
362 {
363 ERR() << "Error setting Path for Mock/Null Driver.";
364 mEnableMockICD = false;
365 }
366 }
Jamie Madill46848422018-08-09 10:46:06 -0400367 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500368 {
369 const auto &cwd = angle::GetCWD();
370 if (!cwd.valid())
371 {
372 ERR() << "Error getting CWD for Vulkan layers init.";
373 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400374 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500375 }
376 else
377 {
378 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500379 std::string exeDir = angle::GetExecutableDirectory();
380 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500381 if (!mChangedCWD)
382 {
383 ERR() << "Error setting CWD for Vulkan layers init.";
384 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400385 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500386 }
387 }
388 }
389
390 // Override environment variable to use the ANGLE layers.
391 if (mEnableValidationLayers)
392 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700393 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500394 {
395 ERR() << "Error setting environment for Vulkan layers init.";
396 mEnableValidationLayers = false;
397 }
398 }
399#endif // !defined(ANGLE_PLATFORM_ANDROID)
400 }
401
402 ~ScopedVkLoaderEnvironment()
403 {
404 if (mChangedCWD)
405 {
406#if !defined(ANGLE_PLATFORM_ANDROID)
407 ASSERT(mPreviousCWD.valid());
408 angle::SetCWD(mPreviousCWD.value().c_str());
409#endif // !defined(ANGLE_PLATFORM_ANDROID)
410 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600411 if (mChangedICDPath)
412 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600413 if (mPreviousICDPath.value().empty())
414 {
415 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
416 }
417 else
418 {
419 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
420 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600421 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500422 }
423
Jamie Madillaaca96e2018-06-12 10:19:48 -0400424 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500425
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool canEnableMockICD() const { return mEnableMockICD; }
427
Yuly Novikov199f4292018-01-19 19:04:05 -0500428 private:
429 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600430 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500431 bool mChangedCWD;
432 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600433 bool mChangedICDPath;
434 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500435};
436
Jamie Madill21061022018-07-12 23:56:30 -0400437void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
438 bool preferMockICD,
439 VkPhysicalDevice *physicalDeviceOut,
440 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
441{
442 ASSERT(!physicalDevices.empty());
443 if (preferMockICD)
444 {
445 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
446 {
447 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
448 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
449 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
450 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
451 {
452 *physicalDeviceOut = physicalDevice;
453 return;
454 }
455 }
456 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
457 "physicalDevice instead.";
458 }
459
460 // Fall back to first device.
461 *physicalDeviceOut = physicalDevices[0];
462 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
463}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400464
465// Initially dumping the command graphs is disabled.
466constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700467
Jamie Madille09bd5d2016-11-29 16:20:35 -0500468} // anonymous namespace
469
Jamie Madill49ac74b2017-12-21 14:42:33 -0500470// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400471RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500472
Jamie Madillaaca96e2018-06-12 10:19:48 -0400473RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500474
475RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000476 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500477{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500478
479RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
480{
481 std::swap(commandPool, other.commandPool);
482 std::swap(fence, other.fence);
483 std::swap(serial, other.serial);
484 return *this;
485}
486
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000487void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400488{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000489 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400490 fence.destroy(device);
491}
492
Jamie Madill9f2a8612017-11-30 12:43:09 -0500493// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500494RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400495 : mDisplay(nullptr),
496 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700497 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500498 mInstance(VK_NULL_HANDLE),
499 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400500 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500501 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500502 mDebugReportCallback(VK_NULL_HANDLE),
503 mPhysicalDevice(VK_NULL_HANDLE),
504 mQueue(VK_NULL_HANDLE),
505 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
506 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400507 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400508 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400509 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400510 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400511 mCommandGraph(kEnableCommandGraphDiagnostics),
512 mGpuEventsEnabled(false),
513 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
514 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500515{
516 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
517 mFormatProperties.fill(invalid);
518}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400519
Jamie Madillb980c562018-11-27 11:34:27 -0500520RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400521
522void RendererVk::onDestroy(vk::Context *context)
523{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500524 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500525 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500526 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400527 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500528 }
529
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100530 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500531
Jamie Madillc7918ce2018-06-13 13:25:31 -0400532 mPipelineLayoutCache.destroy(mDevice);
533 mDescriptorSetLayoutCache.destroy(mDevice);
534
Jamie Madill9f2a8612017-11-30 12:43:09 -0500535 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500536 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400537 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400538 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400539 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500540
Jamie Madill06ca6342018-07-12 15:56:53 -0400541 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500542
Jamie Madill5deea722017-02-16 10:44:46 -0500543 if (mCommandPool.valid())
544 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000545 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500546 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500547
548 if (mDevice)
549 {
550 vkDestroyDevice(mDevice, nullptr);
551 mDevice = VK_NULL_HANDLE;
552 }
553
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500554 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500555 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500556 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
557 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
558
559 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
560 }
561 else if (mDebugReportCallback)
562 {
563 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
564 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500565 }
566
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 if (mInstance)
568 {
569 vkDestroyInstance(mInstance, nullptr);
570 mInstance = VK_NULL_HANDLE;
571 }
572
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600573 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500574 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500575}
576
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400577void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400578{
579 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400580
581 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500582 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400583 freeAllInFlightResources();
584
585 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400586}
587
588bool RendererVk::isDeviceLost() const
589{
590 return mDeviceLost;
591}
592
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400593angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400594 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400595 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500596{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400597 mDisplay = display;
598 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600599 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
600 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500601 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400602 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500603
Jamie Madill0448ec82016-12-23 13:41:47 -0500604 // Gather global layer properties.
605 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400606 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500607
608 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
609 if (instanceLayerCount > 0)
610 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400611 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
612 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500613 }
614
Jamie Madille09bd5d2016-11-29 16:20:35 -0500615 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400616 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400617 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500618
619 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
620 if (instanceExtensionCount > 0)
621 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400622 ANGLE_VK_TRY(displayVk,
623 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
624 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500625 }
626
Yuly Novikov199f4292018-01-19 19:04:05 -0500627 const char *const *enabledLayerNames = nullptr;
628 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500629 if (mEnableValidationLayers)
630 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500631 bool layersRequested =
632 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
633 mEnableValidationLayers = GetAvailableValidationLayers(
634 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500635 }
636
Jamie Madille09bd5d2016-11-29 16:20:35 -0500637 std::vector<const char *> enabledInstanceExtensions;
638 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500639 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500640
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500641 bool enableDebugUtils =
642 mEnableValidationLayers &&
643 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
644 bool enableDebugReport =
645 mEnableValidationLayers && !enableDebugUtils &&
646 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
647
648 if (enableDebugUtils)
649 {
650 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
651 }
652 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500653 {
654 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
655 }
656
Jamie Madille09bd5d2016-11-29 16:20:35 -0500657 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400658 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400659 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500660
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400661 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500662 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500663 applicationInfo.pApplicationName = "ANGLE";
664 applicationInfo.applicationVersion = 1;
665 applicationInfo.pEngineName = "ANGLE";
666 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700667
668 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
669 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
670 if (!enumerateInstanceVersion)
671 {
672 applicationInfo.apiVersion = VK_API_VERSION_1_0;
673 }
674 else
675 {
676 uint32_t apiVersion = VK_API_VERSION_1_0;
677 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
678 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
679 {
680 // Note: will need to revisit this with Vulkan 1.2+.
681 applicationInfo.apiVersion = VK_API_VERSION_1_1;
682 }
683 else
684 {
685 applicationInfo.apiVersion = VK_API_VERSION_1_0;
686 }
687 }
Jamie Madill327ba852016-11-30 12:38:28 -0500688
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400689 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500690 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
691 instanceInfo.flags = 0;
692 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500693
Jamie Madille09bd5d2016-11-29 16:20:35 -0500694 // Enable requested layers and extensions.
695 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
696 instanceInfo.ppEnabledExtensionNames =
697 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500698 instanceInfo.enabledLayerCount = enabledLayerCount;
699 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500700
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400701 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500702
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500703 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500704 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500705 // Try to use the newer EXT_debug_utils if it exists.
706 InitDebugUtilsEXTFunctions(mInstance);
707
708 // Create the messenger callback.
709 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
710
711 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
712 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
713 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
714 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
715 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
716 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
717 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
718 messengerInfo.pUserData = this;
719
720 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
721 &mDebugUtilsMessenger));
722 }
723 else if (enableDebugReport)
724 {
725 // Fallback to EXT_debug_report.
726 InitDebugReportEXTFunctions(mInstance);
727
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400728 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500729
730 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500731 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500732 debugReportInfo.pfnCallback = &DebugReportCallback;
733 debugReportInfo.pUserData = this;
734
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500735 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
736 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500737 }
738
Jamie Madill4d0bf552016-12-28 15:45:24 -0500739 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400740 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
741 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500742
743 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700744 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400745 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
746 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400747 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700748 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500749
Jamie Madill30b5d842018-08-31 17:19:12 -0400750 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
751
Jamie Madill4d0bf552016-12-28 15:45:24 -0500752 // Ensure we can find a graphics queue family.
753 uint32_t queueCount = 0;
754 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
755
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400756 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500757
758 mQueueFamilyProperties.resize(queueCount);
759 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
760 mQueueFamilyProperties.data());
761
Jamie Madillb980c562018-11-27 11:34:27 -0500762 size_t graphicsQueueFamilyCount = false;
763 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500764 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500765 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
766 {
767 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500768 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500769 {
770 ASSERT(queueInfo.queueCount > 0);
771 graphicsQueueFamilyCount++;
772 if (firstGraphicsQueueFamily == 0)
773 {
774 firstGraphicsQueueFamily = familyIndex;
775 }
776 break;
777 }
778 }
779
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400780 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500781
782 // If only one queue family, go ahead and initialize the device. If there is more than one
783 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
784 if (graphicsQueueFamilyCount == 1)
785 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400786 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500787 }
788
Jamie Madill035fd6b2017-10-03 15:43:22 -0400789 // Store the physical device memory properties so we can find the right memory pools.
790 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500791
Jamie Madill06ca6342018-07-12 15:56:53 -0400792 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500793
Jamie Madill6a89d222017-11-02 11:59:51 -0400794 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500795 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400796
Jamie Madill7c985f52018-11-29 18:16:17 -0500797 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400798}
799
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400800angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500801{
802 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400803 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400804 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500805
806 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
807 if (deviceLayerCount > 0)
808 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400809 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
810 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500811 }
812
813 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400814 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
815 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500816
817 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
818 if (deviceExtensionCount > 0)
819 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400820 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
821 &deviceExtensionCount,
822 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500823 }
824
Yuly Novikov199f4292018-01-19 19:04:05 -0500825 const char *const *enabledLayerNames = nullptr;
826 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500827 if (mEnableValidationLayers)
828 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500829 mEnableValidationLayers = GetAvailableValidationLayers(
830 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500831 }
832
833 std::vector<const char *> enabledDeviceExtensions;
834 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
835
Ian Elliottbcb78902018-12-19 11:46:29 -0700836 initFeatures(deviceExtensionProps);
837 mFeaturesInitialized = true;
838
Luc Ferronbf6dc372018-06-28 15:24:19 -0400839 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700840 if ((getFeatures().flipViewportY) &&
841 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400842 {
843 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
844 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700845 if (getFeatures().supportsIncrementalPresent)
846 {
847 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
848 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400849
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400850 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500851
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400852 // Select additional features to be enabled
853 VkPhysicalDeviceFeatures enabledFeatures = {};
854 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500855 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400856
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400857 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500858
859 float zeroPriority = 0.0f;
860
861 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862 queueCreateInfo.flags = 0;
863 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
864 queueCreateInfo.queueCount = 1;
865 queueCreateInfo.pQueuePriorities = &zeroPriority;
866
867 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400868 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500869
Jamie Madill50cf2be2018-06-15 09:46:57 -0400870 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400871 createInfo.flags = 0;
872 createInfo.queueCreateInfoCount = 1;
873 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500874 createInfo.enabledLayerCount = enabledLayerCount;
875 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500876 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
877 createInfo.ppEnabledExtensionNames =
878 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400879 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500880
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400881 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500882
883 mCurrentQueueFamilyIndex = queueFamilyIndex;
884
885 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
886
887 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400888 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500889 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
890 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
891 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500892
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000893 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400894
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400895 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500896 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500897
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400898 // Initialize the submission semaphore pool.
899 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
900
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400901#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
902 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
903 ASSERT(platform);
904
905 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
906 // platform discovery.
907 const unsigned char *gpuEventsEnabled =
908 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
909 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
910#endif
911
912 if (mGpuEventsEnabled)
913 {
914 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
915 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
916 vk::kDefaultTimestampQueryPoolSize));
917 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
918 }
919
Jamie Madill7c985f52018-11-29 18:16:17 -0500920 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500921}
922
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400923angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400924 VkSurfaceKHR surface,
925 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500926{
927 // We've already initialized a device, and can't re-create it unless it's never been used.
928 // TODO(jmadill): Handle the re-creation case if necessary.
929 if (mDevice != VK_NULL_HANDLE)
930 {
931 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
932
933 // Check if the current device supports present on this surface.
934 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400935 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400936 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500937 surface, &supportsPresent));
938
Jamie Madill6cad7732018-07-11 09:01:17 -0400939 if (supportsPresent == VK_TRUE)
940 {
941 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500942 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400943 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500944 }
945
946 // Find a graphics and present queue.
947 Optional<uint32_t> newPresentQueue;
948 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500949 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500950 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
951 {
952 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500953 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500954 {
955 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400956 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
957 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500958
959 if (supportsPresent == VK_TRUE)
960 {
961 newPresentQueue = queueIndex;
962 break;
963 }
964 }
965 }
966
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400967 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
968 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500969
Jamie Madill6cad7732018-07-11 09:01:17 -0400970 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500971 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500972}
973
974std::string RendererVk::getVendorString() const
975{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300976 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500977}
978
Jamie Madille09bd5d2016-11-29 16:20:35 -0500979std::string RendererVk::getRendererDescription() const
980{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500981 std::stringstream strstr;
982
983 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
984
985 strstr << "Vulkan ";
986 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
987 strstr << VK_VERSION_MINOR(apiVersion) << ".";
988 strstr << VK_VERSION_PATCH(apiVersion);
989
Olli Etuahoc6a06182018-04-13 14:11:46 +0300990 strstr << "(";
991
992 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
993 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
994 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
995 // driver detection.
996 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
997 {
998 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
999 }
1000
Geoff Langa7af56b2018-12-14 14:20:28 -05001001 strstr << mPhysicalDeviceProperties.deviceName;
1002 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1003
1004 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001005
1006 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001007}
1008
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001009gl::Version RendererVk::getMaxSupportedESVersion() const
1010{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001011 // Current highest supported version
1012 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1013 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001014
Geoff Lang0c2c9232019-01-14 16:01:38 -05001015 // Vulkan inherited queries are required to support any GL query type
1016 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001017 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001018 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001019 }
1020
Geoff Lang0c2c9232019-01-14 16:01:38 -05001021 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001022}
1023
Ian Elliottbcb78902018-12-19 11:46:29 -07001024void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001025{
Jamie Madillb36a4812018-09-25 10:15:11 -04001026// Use OpenGL line rasterization rules by default.
1027// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1028#if defined(ANGLE_PLATFORM_ANDROID)
1029 mFeatures.basicGLLineRasterization = false;
1030#else
Jamie Madill12222072018-07-11 14:59:48 -04001031 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001032#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001033
Ian Elliott52f5da42018-12-21 09:02:09 -07001034 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1035 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001036 {
1037 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1038 // investigation. http://anglebug.com/2728
1039 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1040 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001041
1042#ifdef ANGLE_PLATFORM_WINDOWS
1043 // http://anglebug.com/2838
1044 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001045
1046 // http://anglebug.com/3055
1047 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001048#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001049
1050 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1051 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001052
1053 // Work around incorrect NVIDIA point size range clamping.
1054 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1055 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1056 {
1057 mFeatures.clampPointSize = true;
1058 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001059
Jamie Madillfa7ca182019-01-15 11:20:58 -05001060 // We also need to clamp point size on several Android drivers.
1061 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1062 if (IsAndroid())
1063 {
1064 mFeatures.clampPointSize = true;
1065 }
1066
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001067#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001068 // Work around ineffective compute-graphics barriers on Nexus 5X.
1069 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1070 // http://anglebug.com/3019
1071 mFeatures.flushAfterVertexConversion =
1072 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001073#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001074
1075 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1076 {
1077 mFeatures.supportsIncrementalPresent = true;
1078 }
Jamie Madill12222072018-07-11 14:59:48 -04001079}
1080
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001081void RendererVk::initPipelineCacheVkKey()
1082{
1083 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1084 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1085 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1086 // there is no '\0' in the result.
1087 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1088 {
1089 hashStream << std::hex << c;
1090 }
1091 // Add the vendor and device id too for good measure.
1092 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1093 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1094
1095 const std::string &hashString = hashStream.str();
1096 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1097 hashString.length(), mPipelineCacheVkBlobKey.data());
1098}
1099
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001100angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001101{
1102 initPipelineCacheVkKey();
1103
1104 egl::BlobCache::Value initialData;
1105 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1106 mPipelineCacheVkBlobKey, &initialData);
1107
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001108 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001109
1110 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001111 pipelineCacheCreateInfo.flags = 0;
1112 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1113 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1114
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001115 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001116 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001117}
1118
Jamie Madillacccc6c2016-05-03 17:22:10 -04001119void RendererVk::ensureCapsInitialized() const
1120{
1121 if (!mCapsInitialized)
1122 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001123 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1124 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1125 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001126 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001127 mCapsInitialized = true;
1128 }
1129}
1130
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001131void RendererVk::getSubmitWaitSemaphores(
1132 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001133 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1134 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001135{
1136 if (mSubmitLastSignaledSemaphore.getSemaphore())
1137 {
1138 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001139 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001140
1141 // Return the semaphore to the pool (which will remain valid and unused until the
1142 // queue it's about to be waited on has finished execution).
1143 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1144 }
1145
1146 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1147 {
1148 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001149 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1150
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001151 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1152 }
1153 mSubmitWaitSemaphores.clear();
1154}
1155
Jamie Madillacccc6c2016-05-03 17:22:10 -04001156const gl::Caps &RendererVk::getNativeCaps() const
1157{
1158 ensureCapsInitialized();
1159 return mNativeCaps;
1160}
1161
1162const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1163{
1164 ensureCapsInitialized();
1165 return mNativeTextureCaps;
1166}
1167
1168const gl::Extensions &RendererVk::getNativeExtensions() const
1169{
1170 ensureCapsInitialized();
1171 return mNativeExtensions;
1172}
1173
1174const gl::Limitations &RendererVk::getNativeLimitations() const
1175{
1176 ensureCapsInitialized();
1177 return mNativeLimitations;
1178}
1179
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001180uint32_t RendererVk::getMaxActiveTextures()
1181{
1182 // TODO(lucferron): expose this limitation to GL in Context Caps
1183 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1184 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1185}
1186
Jamie Madill49ac74b2017-12-21 14:42:33 -05001187const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001188{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001189 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001190}
1191
Jamie Madill21061022018-07-12 23:56:30 -04001192angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001193{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001194 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001195 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001196 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1197
Luc Ferron1617e692018-07-11 11:08:19 -04001198 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1199 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001200
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001201 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001202 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1203 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001204
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001205 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001206 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001207 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1208 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001209 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001210 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001211 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001212 submitInfo.signalSemaphoreCount = 0;
1213 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001214
Jamie Madill21061022018-07-12 23:56:30 -04001215 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001216 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001217
Jamie Madill4c26fc22017-02-24 11:04:10 -05001218 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001219 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001220 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001221
1222 if (mGpuEventsEnabled)
1223 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001224 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001225 while (mInFlightGpuEventQueries.size() > 0)
1226 {
1227 ANGLE_TRY(checkCompletedGpuEvents(context));
1228 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001229 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1230 // synchronization if there is no event to be adjusted (happens when finish() gets called
1231 // multiple times towards the end of the application).
1232 if (mGpuEvents.size() > 0)
1233 {
1234 ANGLE_TRY(synchronizeCpuGpuTime(context));
1235 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001236 }
1237
Jamie Madill7c985f52018-11-29 18:16:17 -05001238 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001239}
1240
Jamie Madill0c0dc342017-03-24 14:18:51 -04001241void RendererVk::freeAllInFlightResources()
1242{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001243 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001244 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001245 // On device loss we need to wait for fence to be signaled before destroying it
1246 if (mDeviceLost)
1247 {
1248 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1249 // If wait times out, it is probably not possible to recover from lost device
1250 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1251 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001252 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001253 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001254 }
1255 mInFlightCommands.clear();
1256
1257 for (auto &garbage : mGarbage)
1258 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001259 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001260 }
1261 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001262
1263 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001264}
1265
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001266angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001267{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001268 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001269
Jamie Madill49ac74b2017-12-21 14:42:33 -05001270 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001271 {
Yuly Novikov27780292018-11-09 11:19:49 -05001272 VkResult result = batch.fence.getStatus(mDevice);
1273 if (result == VK_NOT_READY)
1274 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001275 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001276 }
1277 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001278
Jamie Madill49ac74b2017-12-21 14:42:33 -05001279 ASSERT(batch.serial > mLastCompletedQueueSerial);
1280 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001281
Jamie Madill49ac74b2017-12-21 14:42:33 -05001282 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001283 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
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