blob: ec830a7c5fb120007da605f180300d10a4c2f9d0 [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
Jamie Madill00f43c92019-02-09 11:41:12 -0500106constexpr const char *kSkippedMessages[] = {
107 // http://anglebug.com/2866
108 "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500109 // http://anglebug.com/2796
Jamie Madill00f43c92019-02-09 11:41:12 -0500110 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing",
111};
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500112
113// Suppress validation errors that are known
114// return "true" if given code/prefix/message is known, else return "false"
115bool IsIgnoredDebugMessage(const char *message)
116{
Michael Spang25839802019-01-30 18:02:51 -0500117 if (!message)
118 {
119 return false;
120 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500121 for (const char *msg : kSkippedMessages)
122 {
123 if (strstr(message, msg) != nullptr)
124 {
125 return true;
126 }
127 }
128 return false;
129}
130
131const char *GetVkObjectTypeName(VkObjectType type)
132{
133 switch (type)
134 {
135 case VK_OBJECT_TYPE_UNKNOWN:
136 return "Unknown";
137 case VK_OBJECT_TYPE_INSTANCE:
138 return "Instance";
139 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
140 return "Physical Device";
141 case VK_OBJECT_TYPE_DEVICE:
142 return "Device";
143 case VK_OBJECT_TYPE_QUEUE:
144 return "Queue";
145 case VK_OBJECT_TYPE_SEMAPHORE:
146 return "Semaphore";
147 case VK_OBJECT_TYPE_COMMAND_BUFFER:
148 return "Command Buffer";
149 case VK_OBJECT_TYPE_FENCE:
150 return "Fence";
151 case VK_OBJECT_TYPE_DEVICE_MEMORY:
152 return "Device Memory";
153 case VK_OBJECT_TYPE_BUFFER:
154 return "Buffer";
155 case VK_OBJECT_TYPE_IMAGE:
156 return "Image";
157 case VK_OBJECT_TYPE_EVENT:
158 return "Event";
159 case VK_OBJECT_TYPE_QUERY_POOL:
160 return "Query Pool";
161 case VK_OBJECT_TYPE_BUFFER_VIEW:
162 return "Buffer View";
163 case VK_OBJECT_TYPE_IMAGE_VIEW:
164 return "Image View";
165 case VK_OBJECT_TYPE_SHADER_MODULE:
166 return "Shader Module";
167 case VK_OBJECT_TYPE_PIPELINE_CACHE:
168 return "Pipeline Cache";
169 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
170 return "Pipeline Layout";
171 case VK_OBJECT_TYPE_RENDER_PASS:
172 return "Render Pass";
173 case VK_OBJECT_TYPE_PIPELINE:
174 return "Pipeline";
175 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
176 return "Descriptor Set Layout";
177 case VK_OBJECT_TYPE_SAMPLER:
178 return "Sampler";
179 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
180 return "Descriptor Pool";
181 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
182 return "Descriptor Set";
183 case VK_OBJECT_TYPE_FRAMEBUFFER:
184 return "Framebuffer";
185 case VK_OBJECT_TYPE_COMMAND_POOL:
186 return "Command Pool";
187 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
188 return "Sampler YCbCr Conversion";
189 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
190 return "Descriptor Update Template";
191 case VK_OBJECT_TYPE_SURFACE_KHR:
192 return "Surface";
193 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
194 return "Swapchain";
195 case VK_OBJECT_TYPE_DISPLAY_KHR:
196 return "Display";
197 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
198 return "Display Mode";
199 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
200 return "Debug Report Callback";
201 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
202 return "Object Table";
203 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
204 return "Indirect Commands Layout";
205 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
206 return "Debug Utils Messenger";
207 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
208 return "Validation Cache";
209 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
210 return "Acceleration Structure";
211 default:
212 return "<Unrecognized>";
213 }
214}
215
216VKAPI_ATTR VkBool32 VKAPI_CALL
217DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
218 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
219 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
220 void *userData)
221{
222 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
223 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
224 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
225
226 // Check if we even care about this message.
227 if ((messageSeverity & kSeveritiesToLog) == 0)
228 {
229 return VK_FALSE;
230 }
231
232 // See if it's an issue we are aware of and don't want to be spammed about.
233 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
234 {
235 return VK_FALSE;
236 }
237
238 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500239 if (callbackData->pMessageIdName)
240 {
241 log << "[ " << callbackData->pMessageIdName << " ] ";
242 }
243 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500244
245 // Aesthetic value based on length of the function name, line number, etc.
246 constexpr size_t kStartIndent = 28;
247
248 // Output the debug marker hierarchy under which this error has occured.
249 size_t indent = kStartIndent;
250 if (callbackData->queueLabelCount > 0)
251 {
252 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
253 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
254 {
255 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
256 << std::endl;
257 }
258 }
259 if (callbackData->cmdBufLabelCount > 0)
260 {
261 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
262 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
263 {
264 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
265 << std::endl;
266 }
267 }
268 // Output the objects involved in this error message.
269 if (callbackData->objectCount > 0)
270 {
271 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
272 {
273 const char *objectName = callbackData->pObjects[i].pObjectName;
274 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
275 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
276 log << std::string(indent, ' ') << "Object: ";
277 if (objectHandle == 0)
278 {
279 log << "VK_NULL_HANDLE";
280 }
281 else
282 {
283 log << "0x" << std::hex << objectHandle << std::dec;
284 }
285 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
286 if (objectName)
287 {
288 log << " [" << objectName << "]";
289 }
290 log << std::endl;
291 }
292 }
293
Jamie Madill54ed8f02019-02-11 12:32:04 -0500294 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
295 std::string msg = log.str();
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500296
297 if (isError)
298 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500299 ERR() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500300 }
301 else
302 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500303 WARN() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500304 }
305
306 return VK_FALSE;
307}
308
Yuly Novikov199f4292018-01-19 19:04:05 -0500309VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
310 VkDebugReportObjectTypeEXT objectType,
311 uint64_t object,
312 size_t location,
313 int32_t messageCode,
314 const char *layerPrefix,
315 const char *message,
316 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500317{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600318 if (IsIgnoredDebugMessage(message))
319 {
320 return VK_FALSE;
321 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500322 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
323 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500324 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500325#if !defined(NDEBUG)
326 // Abort the call in Debug builds.
327 return VK_TRUE;
328#endif
329 }
330 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
331 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500332 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500333 }
334 else
335 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500336 // Uncomment this if you want Vulkan spam.
337 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500338 }
339
340 return VK_FALSE;
341}
342
Yuly Novikov199f4292018-01-19 19:04:05 -0500343// If we're loading the validation layers, we could be running from any random directory.
344// Change to the executable directory so we can find the layers, then change back to the
345// previous directory to be safe we don't disrupt the application.
346class ScopedVkLoaderEnvironment : angle::NonCopyable
347{
348 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600349 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
350 : mEnableValidationLayers(enableValidationLayers),
351 mEnableMockICD(enableMockICD),
352 mChangedCWD(false),
353 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500354 {
355// Changing CWD and setting environment variables makes no sense on Android,
356// since this code is a part of Java application there.
357// Android Vulkan loader doesn't need this either.
358#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600359 if (enableMockICD)
360 {
361 // Override environment variable to use built Mock ICD
362 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
363 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
364 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
365 if (!mChangedICDPath)
366 {
367 ERR() << "Error setting Path for Mock/Null Driver.";
368 mEnableMockICD = false;
369 }
370 }
Jamie Madill46848422018-08-09 10:46:06 -0400371 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500372 {
373 const auto &cwd = angle::GetCWD();
374 if (!cwd.valid())
375 {
376 ERR() << "Error getting CWD for Vulkan layers init.";
377 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400378 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500379 }
380 else
381 {
382 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500383 std::string exeDir = angle::GetExecutableDirectory();
384 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500385 if (!mChangedCWD)
386 {
387 ERR() << "Error setting CWD for Vulkan layers init.";
388 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400389 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500390 }
391 }
392 }
393
394 // Override environment variable to use the ANGLE layers.
395 if (mEnableValidationLayers)
396 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700397 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500398 {
399 ERR() << "Error setting environment for Vulkan layers init.";
400 mEnableValidationLayers = false;
401 }
402 }
403#endif // !defined(ANGLE_PLATFORM_ANDROID)
404 }
405
406 ~ScopedVkLoaderEnvironment()
407 {
408 if (mChangedCWD)
409 {
410#if !defined(ANGLE_PLATFORM_ANDROID)
411 ASSERT(mPreviousCWD.valid());
412 angle::SetCWD(mPreviousCWD.value().c_str());
413#endif // !defined(ANGLE_PLATFORM_ANDROID)
414 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600415 if (mChangedICDPath)
416 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600417 if (mPreviousICDPath.value().empty())
418 {
419 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
420 }
421 else
422 {
423 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
424 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600425 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500426 }
427
Jamie Madillaaca96e2018-06-12 10:19:48 -0400428 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500429
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600430 bool canEnableMockICD() const { return mEnableMockICD; }
431
Yuly Novikov199f4292018-01-19 19:04:05 -0500432 private:
433 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600434 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500435 bool mChangedCWD;
436 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600437 bool mChangedICDPath;
438 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500439};
440
Jamie Madill21061022018-07-12 23:56:30 -0400441void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
442 bool preferMockICD,
443 VkPhysicalDevice *physicalDeviceOut,
444 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
445{
446 ASSERT(!physicalDevices.empty());
447 if (preferMockICD)
448 {
449 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
450 {
451 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
452 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
453 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
454 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
455 {
456 *physicalDeviceOut = physicalDevice;
457 return;
458 }
459 }
460 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
461 "physicalDevice instead.";
462 }
463
464 // Fall back to first device.
465 *physicalDeviceOut = physicalDevices[0];
466 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
467}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400468
469// Initially dumping the command graphs is disabled.
470constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700471
Jamie Madille09bd5d2016-11-29 16:20:35 -0500472} // anonymous namespace
473
Jamie Madill49ac74b2017-12-21 14:42:33 -0500474// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400475RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500476
Jamie Madillaaca96e2018-06-12 10:19:48 -0400477RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500478
479RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000480 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500481{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500482
483RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
484{
485 std::swap(commandPool, other.commandPool);
486 std::swap(fence, other.fence);
487 std::swap(serial, other.serial);
488 return *this;
489}
490
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000491void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400492{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000493 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400494 fence.destroy(device);
495}
496
Jamie Madill9f2a8612017-11-30 12:43:09 -0500497// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500498RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400499 : mDisplay(nullptr),
500 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700501 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500502 mInstance(VK_NULL_HANDLE),
503 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400504 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500505 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500506 mDebugReportCallback(VK_NULL_HANDLE),
507 mPhysicalDevice(VK_NULL_HANDLE),
508 mQueue(VK_NULL_HANDLE),
509 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
510 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400511 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400512 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400513 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400514 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400515 mCommandGraph(kEnableCommandGraphDiagnostics),
516 mGpuEventsEnabled(false),
517 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
518 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500519{
520 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
521 mFormatProperties.fill(invalid);
522}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400523
Jamie Madillb980c562018-11-27 11:34:27 -0500524RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400525
526void RendererVk::onDestroy(vk::Context *context)
527{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500528 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500529 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500530 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400531 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500532 }
533
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100534 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500535
Jamie Madillc7918ce2018-06-13 13:25:31 -0400536 mPipelineLayoutCache.destroy(mDevice);
537 mDescriptorSetLayoutCache.destroy(mDevice);
538
Jamie Madill9f2a8612017-11-30 12:43:09 -0500539 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500540 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400541 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400542 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400543 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500544
Jamie Madill06ca6342018-07-12 15:56:53 -0400545 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500546
Jamie Madill5deea722017-02-16 10:44:46 -0500547 if (mCommandPool.valid())
548 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000549 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500550 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500551
552 if (mDevice)
553 {
554 vkDestroyDevice(mDevice, nullptr);
555 mDevice = VK_NULL_HANDLE;
556 }
557
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500558 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500559 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500560 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
561 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
562
563 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
564 }
565 else if (mDebugReportCallback)
566 {
567 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
568 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500569 }
570
Jamie Madill4d0bf552016-12-28 15:45:24 -0500571 if (mInstance)
572 {
573 vkDestroyInstance(mInstance, nullptr);
574 mInstance = VK_NULL_HANDLE;
575 }
576
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600577 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500578 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500579}
580
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400581void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400582{
583 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400584
585 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500586 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400587 freeAllInFlightResources();
588
589 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400590}
591
592bool RendererVk::isDeviceLost() const
593{
594 return mDeviceLost;
595}
596
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400597angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400598 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500599 const char *wsiExtension,
600 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500601{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400602 mDisplay = display;
603 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600604 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
605 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500606 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400607 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500608
Jamie Madill0448ec82016-12-23 13:41:47 -0500609 // Gather global layer properties.
610 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400611 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500612
613 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
614 if (instanceLayerCount > 0)
615 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400616 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
617 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500618 }
619
Michael Spang6c13c702019-02-06 15:59:44 -0500620 VulkanLayerVector enabledInstanceLayerNames;
621 if (mEnableValidationLayers)
622 {
623 bool layersRequested =
624 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
625 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
626 &enabledInstanceLayerNames);
627 }
628
629 if (wsiLayer)
630 {
631 enabledInstanceLayerNames.push_back(wsiLayer);
632 }
633
634 // Enumerate instance extensions that are provided by the vulkan
635 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500636 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400637 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400638 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500639
640 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
641 if (instanceExtensionCount > 0)
642 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400643 ANGLE_VK_TRY(displayVk,
644 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
645 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500646 }
647
Michael Spang6c13c702019-02-06 15:59:44 -0500648 // Enumerate instance extensions that are provided by explicit layers.
649 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500650 {
Michael Spang6c13c702019-02-06 15:59:44 -0500651 uint32_t previousExtensionCount = instanceExtensionProps.size();
652 uint32_t instanceLayerExtensionCount = 0;
653 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
654 layerName, &instanceLayerExtensionCount, nullptr));
655 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
656 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
657 layerName, &instanceLayerExtensionCount,
658 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500659 }
660
Jamie Madille09bd5d2016-11-29 16:20:35 -0500661 std::vector<const char *> enabledInstanceExtensions;
662 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500663 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500664
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500665 bool enableDebugUtils =
666 mEnableValidationLayers &&
667 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
668 bool enableDebugReport =
669 mEnableValidationLayers && !enableDebugUtils &&
670 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
671
672 if (enableDebugUtils)
673 {
674 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
675 }
676 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500677 {
678 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
679 }
680
Jamie Madille09bd5d2016-11-29 16:20:35 -0500681 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400682 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400683 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500684
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400685 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500686 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500687 applicationInfo.pApplicationName = "ANGLE";
688 applicationInfo.applicationVersion = 1;
689 applicationInfo.pEngineName = "ANGLE";
690 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700691
692 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
693 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
694 if (!enumerateInstanceVersion)
695 {
696 applicationInfo.apiVersion = VK_API_VERSION_1_0;
697 }
698 else
699 {
700 uint32_t apiVersion = VK_API_VERSION_1_0;
701 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
702 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
703 {
704 // Note: will need to revisit this with Vulkan 1.2+.
705 applicationInfo.apiVersion = VK_API_VERSION_1_1;
706 }
707 else
708 {
709 applicationInfo.apiVersion = VK_API_VERSION_1_0;
710 }
711 }
Jamie Madill327ba852016-11-30 12:38:28 -0500712
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400713 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500714 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
715 instanceInfo.flags = 0;
716 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500717
Jamie Madille09bd5d2016-11-29 16:20:35 -0500718 // Enable requested layers and extensions.
719 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
720 instanceInfo.ppEnabledExtensionNames =
721 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500722 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
723 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500724
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400725 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500726
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500727 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500728 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500729 // Try to use the newer EXT_debug_utils if it exists.
730 InitDebugUtilsEXTFunctions(mInstance);
731
732 // Create the messenger callback.
733 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
734
735 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
736 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
737 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
738 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
739 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
740 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
741 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
742 messengerInfo.pUserData = this;
743
744 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
745 &mDebugUtilsMessenger));
746 }
747 else if (enableDebugReport)
748 {
749 // Fallback to EXT_debug_report.
750 InitDebugReportEXTFunctions(mInstance);
751
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400752 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500753
754 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500755 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500756 debugReportInfo.pfnCallback = &DebugReportCallback;
757 debugReportInfo.pUserData = this;
758
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500759 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
760 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500761 }
762
Jamie Madill4d0bf552016-12-28 15:45:24 -0500763 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400764 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
765 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500766
767 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700768 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400769 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
770 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400771 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700772 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500773
Jamie Madill30b5d842018-08-31 17:19:12 -0400774 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
775
Jamie Madill4d0bf552016-12-28 15:45:24 -0500776 // Ensure we can find a graphics queue family.
777 uint32_t queueCount = 0;
778 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
779
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400780 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500781
782 mQueueFamilyProperties.resize(queueCount);
783 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
784 mQueueFamilyProperties.data());
785
Jamie Madillb980c562018-11-27 11:34:27 -0500786 size_t graphicsQueueFamilyCount = false;
787 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500788 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500789 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
790 {
791 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500792 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500793 {
794 ASSERT(queueInfo.queueCount > 0);
795 graphicsQueueFamilyCount++;
796 if (firstGraphicsQueueFamily == 0)
797 {
798 firstGraphicsQueueFamily = familyIndex;
799 }
800 break;
801 }
802 }
803
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400804 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500805
806 // If only one queue family, go ahead and initialize the device. If there is more than one
807 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
808 if (graphicsQueueFamilyCount == 1)
809 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400810 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500811 }
812
Jamie Madill035fd6b2017-10-03 15:43:22 -0400813 // Store the physical device memory properties so we can find the right memory pools.
814 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500815
Jamie Madill06ca6342018-07-12 15:56:53 -0400816 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500817
Jamie Madill6a89d222017-11-02 11:59:51 -0400818 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500819 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400820
Jamie Madill7c985f52018-11-29 18:16:17 -0500821 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400822}
823
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400824angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500825{
826 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400827 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400828 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500829
830 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
831 if (deviceLayerCount > 0)
832 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400833 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
834 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500835 }
836
Michael Spang6c13c702019-02-06 15:59:44 -0500837 VulkanLayerVector enabledDeviceLayerNames;
838 if (mEnableValidationLayers)
839 {
840 mEnableValidationLayers =
841 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
842 }
843
844 const char *wsiLayer = displayVk->getWSILayer();
845 if (wsiLayer)
846 {
847 enabledDeviceLayerNames.push_back(wsiLayer);
848 }
849
850 // Enumerate device extensions that are provided by the vulkan
851 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500852 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400853 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
854 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500855
856 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
857 if (deviceExtensionCount > 0)
858 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400859 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
860 &deviceExtensionCount,
861 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862 }
863
Michael Spang6c13c702019-02-06 15:59:44 -0500864 // Enumerate device extensions that are provided by explicit layers.
865 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500866 {
Michael Spang6c13c702019-02-06 15:59:44 -0500867 uint32_t previousExtensionCount = deviceExtensionProps.size();
868 uint32_t deviceLayerExtensionCount = 0;
869 ANGLE_VK_TRY(displayVk,
870 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
871 &deviceLayerExtensionCount, nullptr));
872 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
873 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
874 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
875 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500876 }
877
878 std::vector<const char *> enabledDeviceExtensions;
879 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
880
Ian Elliottbcb78902018-12-19 11:46:29 -0700881 initFeatures(deviceExtensionProps);
882 mFeaturesInitialized = true;
883
Luc Ferronbf6dc372018-06-28 15:24:19 -0400884 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700885 if ((getFeatures().flipViewportY) &&
886 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400887 {
888 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
889 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700890 if (getFeatures().supportsIncrementalPresent)
891 {
892 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
893 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400894
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400895 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500896
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400897 // Select additional features to be enabled
898 VkPhysicalDeviceFeatures enabledFeatures = {};
899 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500900 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400901
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400902 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500903
904 float zeroPriority = 0.0f;
905
906 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500907 queueCreateInfo.flags = 0;
908 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
909 queueCreateInfo.queueCount = 1;
910 queueCreateInfo.pQueuePriorities = &zeroPriority;
911
912 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400913 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500914
Jamie Madill50cf2be2018-06-15 09:46:57 -0400915 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400916 createInfo.flags = 0;
917 createInfo.queueCreateInfoCount = 1;
918 createInfo.pQueueCreateInfos = &queueCreateInfo;
Michael Spang6c13c702019-02-06 15:59:44 -0500919 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
920 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500921 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
922 createInfo.ppEnabledExtensionNames =
923 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400924 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500925
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400926 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500927
928 mCurrentQueueFamilyIndex = queueFamilyIndex;
929
930 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
931
932 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400933 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500934 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
935 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
936 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500937
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000938 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400939
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400940 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500941 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500942
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400943 // Initialize the submission semaphore pool.
944 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
945
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400946#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
947 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
948 ASSERT(platform);
949
950 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
951 // platform discovery.
952 const unsigned char *gpuEventsEnabled =
953 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
954 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
955#endif
956
957 if (mGpuEventsEnabled)
958 {
959 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
960 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
961 vk::kDefaultTimestampQueryPoolSize));
962 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
963 }
964
Jamie Madill7c985f52018-11-29 18:16:17 -0500965 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500966}
967
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400968angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400969 VkSurfaceKHR surface,
970 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500971{
972 // We've already initialized a device, and can't re-create it unless it's never been used.
973 // TODO(jmadill): Handle the re-creation case if necessary.
974 if (mDevice != VK_NULL_HANDLE)
975 {
976 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
977
978 // Check if the current device supports present on this surface.
979 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400980 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400981 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500982 surface, &supportsPresent));
983
Jamie Madill6cad7732018-07-11 09:01:17 -0400984 if (supportsPresent == VK_TRUE)
985 {
986 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500987 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400988 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500989 }
990
991 // Find a graphics and present queue.
992 Optional<uint32_t> newPresentQueue;
993 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500994 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500995 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
996 {
997 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500998 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500999 {
1000 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001001 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
1002 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001003
1004 if (supportsPresent == VK_TRUE)
1005 {
1006 newPresentQueue = queueIndex;
1007 break;
1008 }
1009 }
1010 }
1011
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001012 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1013 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001014
Jamie Madill6cad7732018-07-11 09:01:17 -04001015 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001016 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001017}
1018
1019std::string RendererVk::getVendorString() const
1020{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001021 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001022}
1023
Jamie Madille09bd5d2016-11-29 16:20:35 -05001024std::string RendererVk::getRendererDescription() const
1025{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001026 std::stringstream strstr;
1027
1028 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1029
1030 strstr << "Vulkan ";
1031 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1032 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1033 strstr << VK_VERSION_PATCH(apiVersion);
1034
Olli Etuahoc6a06182018-04-13 14:11:46 +03001035 strstr << "(";
1036
1037 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1038 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1039 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1040 // driver detection.
1041 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1042 {
1043 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1044 }
1045
Geoff Langa7af56b2018-12-14 14:20:28 -05001046 strstr << mPhysicalDeviceProperties.deviceName;
1047 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1048
1049 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001050
1051 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001052}
1053
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001054gl::Version RendererVk::getMaxSupportedESVersion() const
1055{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001056 // Current highest supported version
1057 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1058 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001059
Geoff Lang0c2c9232019-01-14 16:01:38 -05001060 // Vulkan inherited queries are required to support any GL query type
1061 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001062 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001063 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001064 }
1065
Geoff Lang0c2c9232019-01-14 16:01:38 -05001066 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001067}
1068
Ian Elliottbcb78902018-12-19 11:46:29 -07001069void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001070{
Jamie Madillb36a4812018-09-25 10:15:11 -04001071// Use OpenGL line rasterization rules by default.
1072// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1073#if defined(ANGLE_PLATFORM_ANDROID)
1074 mFeatures.basicGLLineRasterization = false;
1075#else
Jamie Madill12222072018-07-11 14:59:48 -04001076 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001077#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001078
Ian Elliott52f5da42018-12-21 09:02:09 -07001079 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1080 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001081 {
1082 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1083 // investigation. http://anglebug.com/2728
1084 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1085 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001086
1087#ifdef ANGLE_PLATFORM_WINDOWS
1088 // http://anglebug.com/2838
1089 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001090
1091 // http://anglebug.com/3055
1092 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001093#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001094
1095 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1096 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001097
1098 // Work around incorrect NVIDIA point size range clamping.
1099 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1100 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1101 {
1102 mFeatures.clampPointSize = true;
1103 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001104
Jamie Madillfa7ca182019-01-15 11:20:58 -05001105 // We also need to clamp point size on several Android drivers.
1106 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1107 if (IsAndroid())
1108 {
1109 mFeatures.clampPointSize = true;
1110 }
1111
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001112#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001113 // Work around ineffective compute-graphics barriers on Nexus 5X.
1114 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1115 // http://anglebug.com/3019
1116 mFeatures.flushAfterVertexConversion =
1117 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001118#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001119
1120 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1121 {
1122 mFeatures.supportsIncrementalPresent = true;
1123 }
Jamie Madill12222072018-07-11 14:59:48 -04001124}
1125
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001126void RendererVk::initPipelineCacheVkKey()
1127{
1128 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1129 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1130 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1131 // there is no '\0' in the result.
1132 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1133 {
1134 hashStream << std::hex << c;
1135 }
1136 // Add the vendor and device id too for good measure.
1137 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1138 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1139
1140 const std::string &hashString = hashStream.str();
1141 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1142 hashString.length(), mPipelineCacheVkBlobKey.data());
1143}
1144
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001145angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001146{
1147 initPipelineCacheVkKey();
1148
1149 egl::BlobCache::Value initialData;
1150 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1151 mPipelineCacheVkBlobKey, &initialData);
1152
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001153 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001154
1155 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001156 pipelineCacheCreateInfo.flags = 0;
1157 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1158 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1159
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001160 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001161 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001162}
1163
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001164void RendererVk::getSubmitWaitSemaphores(
1165 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001166 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1167 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001168{
1169 if (mSubmitLastSignaledSemaphore.getSemaphore())
1170 {
1171 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001172 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001173
1174 // Return the semaphore to the pool (which will remain valid and unused until the
1175 // queue it's about to be waited on has finished execution).
1176 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1177 }
1178
1179 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1180 {
1181 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001182 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1183
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001184 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1185 }
1186 mSubmitWaitSemaphores.clear();
1187}
1188
Jamie Madillacccc6c2016-05-03 17:22:10 -04001189const gl::Caps &RendererVk::getNativeCaps() const
1190{
1191 ensureCapsInitialized();
1192 return mNativeCaps;
1193}
1194
1195const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1196{
1197 ensureCapsInitialized();
1198 return mNativeTextureCaps;
1199}
1200
1201const gl::Extensions &RendererVk::getNativeExtensions() const
1202{
1203 ensureCapsInitialized();
1204 return mNativeExtensions;
1205}
1206
1207const gl::Limitations &RendererVk::getNativeLimitations() const
1208{
1209 ensureCapsInitialized();
1210 return mNativeLimitations;
1211}
1212
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001213uint32_t RendererVk::getMaxActiveTextures()
1214{
1215 // TODO(lucferron): expose this limitation to GL in Context Caps
1216 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1217 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1218}
1219
Jamie Madill49ac74b2017-12-21 14:42:33 -05001220const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001221{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001222 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001223}
1224
Jamie Madill21061022018-07-12 23:56:30 -04001225angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001226{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001227 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001228 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001229 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1230
Luc Ferron1617e692018-07-11 11:08:19 -04001231 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1232 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001233
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001234 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001235 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1236 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001237
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001238 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001239 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001240 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1241 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001242 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001243 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001244 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001245 submitInfo.signalSemaphoreCount = 0;
1246 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001247
Jamie Madill21061022018-07-12 23:56:30 -04001248 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001249 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001250
Jamie Madill4c26fc22017-02-24 11:04:10 -05001251 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001252 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001253 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001254
1255 if (mGpuEventsEnabled)
1256 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001257 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001258 while (mInFlightGpuEventQueries.size() > 0)
1259 {
1260 ANGLE_TRY(checkCompletedGpuEvents(context));
1261 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001262 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1263 // synchronization if there is no event to be adjusted (happens when finish() gets called
1264 // multiple times towards the end of the application).
1265 if (mGpuEvents.size() > 0)
1266 {
1267 ANGLE_TRY(synchronizeCpuGpuTime(context));
1268 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001269 }
1270
Jamie Madill7c985f52018-11-29 18:16:17 -05001271 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001272}
1273
Jamie Madill0c0dc342017-03-24 14:18:51 -04001274void RendererVk::freeAllInFlightResources()
1275{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001276 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001277 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001278 // On device loss we need to wait for fence to be signaled before destroying it
1279 if (mDeviceLost)
1280 {
1281 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1282 // If wait times out, it is probably not possible to recover from lost device
1283 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1284 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001285 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001286 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001287 }
1288 mInFlightCommands.clear();
1289
1290 for (auto &garbage : mGarbage)
1291 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001292 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001293 }
1294 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001295
1296 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001297}
1298
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001299angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001300{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001301 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001302
Jamie Madill49ac74b2017-12-21 14:42:33 -05001303 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001304 {
Yuly Novikov27780292018-11-09 11:19:49 -05001305 VkResult result = batch.fence.getStatus(mDevice);
1306 if (result == VK_NOT_READY)
1307 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001308 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001309 }
1310 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001311
Jamie Madill49ac74b2017-12-21 14:42:33 -05001312 ASSERT(batch.serial > mLastCompletedQueueSerial);
1313 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001314
Jamie Madill49ac74b2017-12-21 14:42:33 -05001315 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001316 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001317 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001319 }
1320
Jamie Madill49ac74b2017-12-21 14:42:33 -05001321 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001322
1323 size_t freeIndex = 0;
1324 for (; freeIndex < mGarbage.size(); ++freeIndex)
1325 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001326 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001327 break;
1328 }
1329
1330 // Remove the entries from the garbage list - they should be ready to go.
1331 if (freeIndex > 0)
1332 {
1333 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001334 }
1335
Jamie Madill7c985f52018-11-29 18:16:17 -05001336 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001337}
1338
Jamie Madill21061022018-07-12 23:56:30 -04001339angle::Result RendererVk::submitFrame(vk::Context *context,
1340 const VkSubmitInfo &submitInfo,
1341 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001342{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001343 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001344 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001345 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1346 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001347
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001348 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001349 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001350 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001351
Jamie Madill21061022018-07-12 23:56:30 -04001352 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001353
1354 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001355 batch.commandPool = std::move(mCommandPool);
1356 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001357
Jamie Madillbea35a62018-07-05 11:54:10 -04001358 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001359
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001360 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1361 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001362 // so the limit is larger than the expected number of images. The
1363 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001364 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001365
Jamie Madill85ca1892019-01-16 13:27:15 -05001366 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001367
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001368 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001369
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001370 if (mGpuEventsEnabled)
1371 {
1372 ANGLE_TRY(checkCompletedGpuEvents(context));
1373 }
1374
Jamie Madill49ac74b2017-12-21 14:42:33 -05001375 // Simply null out the command buffer here - it was allocated using the command pool.
1376 commandBuffer.releaseHandle();
1377
1378 // Reallocate the command pool for next frame.
1379 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001380 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001381 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001382 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001383 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001384
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001385 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001386 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001387}
1388
Jamie Madill85ca1892019-01-16 13:27:15 -05001389void RendererVk::nextSerial()
1390{
1391 // Increment the queue serial. If this fails, we should restart ANGLE.
1392 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1393 mCurrentQueueSerial = mQueueSerialFactory.generate();
1394
1395 // Notify the Contexts that they should be starting new command buffers.
1396 // We use one command pool per serial/submit associated with this VkQueue. We can also
1397 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1398 // check for a new serial when starting a new command buffer. We just check that the current
1399 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1400 // using this VkQueue that they their current command buffer is no longer valid.
1401 for (gl::Context *context : mDisplay->getContextSet())
1402 {
1403 ContextVk *contextVk = vk::GetImpl(context);
1404 contextVk->onCommandBufferFinished();
1405 }
1406}
1407
Jamie Madillaaca96e2018-06-12 10:19:48 -04001408bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001409{
1410 return serial > mLastCompletedQueueSerial;
1411}
1412
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001413angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1414{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001415 bool timedOut = false;
1416 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1417
1418 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1419 if (timedOut)
1420 {
1421 result = angle::Result::Stop;
1422 }
1423 return result;
1424}
1425
1426angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1427 Serial serial,
1428 uint64_t timeout,
1429 bool *outTimedOut)
1430{
1431 *outTimedOut = false;
1432
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001433 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1434 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001435 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001436 }
1437
1438 // Find the first batch with serial equal to or bigger than given serial (note that
1439 // the batch serials are unique, otherwise upper-bound would have been necessary).
1440 size_t batchIndex = mInFlightCommands.size() - 1;
1441 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1442 {
1443 if (mInFlightCommands[i].serial >= serial)
1444 {
1445 batchIndex = i;
1446 break;
1447 }
1448 }
1449 const CommandBatch &batch = mInFlightCommands[batchIndex];
1450
1451 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001452 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1453
1454 // If timed out, report it as such.
1455 if (status == VK_TIMEOUT)
1456 {
1457 *outTimedOut = true;
1458 return angle::Result::Continue;
1459 }
1460
1461 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001462
1463 // Clean up finished batches.
1464 return checkCompletedCommands(context);
1465}
1466
Jamie Madill21061022018-07-12 23:56:30 -04001467angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1468 const vk::RenderPassDesc &desc,
1469 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001470{
Jamie Madill21061022018-07-12 23:56:30 -04001471 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001472 renderPassOut);
1473}
1474
Jamie Madill21061022018-07-12 23:56:30 -04001475angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1476 const vk::RenderPassDesc &desc,
1477 const vk::AttachmentOpsArray &ops,
1478 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001479{
Jamie Madill21061022018-07-12 23:56:30 -04001480 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001481 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001482}
1483
Jamie Madilla5e06072018-05-18 14:36:05 -04001484vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001485{
Jamie Madilla5e06072018-05-18 14:36:05 -04001486 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001487}
1488
Jamie Madill21061022018-07-12 23:56:30 -04001489angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001490{
Jamie Madill21061022018-07-12 23:56:30 -04001491 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001492 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001493}
1494
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001495angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001496{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001497 if (mCommandGraph.empty())
1498 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001499 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001500 }
1501
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001502 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1503
Jamie Madillbea35a62018-07-05 11:54:10 -04001504 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1505 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001506
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001507 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001508 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1509 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001510
1511 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1512 // will be waited on.
1513 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001514
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001515 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001516 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001517 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1518 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001519 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001520 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001521 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001522 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001523 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001524
Jamie Madill21061022018-07-12 23:56:30 -04001525 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001526
Jamie Madill7c985f52018-11-29 18:16:17 -05001527 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001528}
1529
Jamie Madill78feddc2018-04-27 11:45:05 -04001530Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001531{
Jamie Madill78feddc2018-04-27 11:45:05 -04001532 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001533}
1534
Jamie Madill21061022018-07-12 23:56:30 -04001535angle::Result RendererVk::getDescriptorSetLayout(
1536 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001537 const vk::DescriptorSetLayoutDesc &desc,
1538 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1539{
Jamie Madill21061022018-07-12 23:56:30 -04001540 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001541}
1542
Jamie Madill21061022018-07-12 23:56:30 -04001543angle::Result RendererVk::getPipelineLayout(
1544 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001545 const vk::PipelineLayoutDesc &desc,
1546 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1547 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1548{
Jamie Madill21061022018-07-12 23:56:30 -04001549 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001550 pipelineLayoutOut);
1551}
1552
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001553angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1554{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001555 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001556
1557 if (--mPipelineCacheVkUpdateTimeout > 0)
1558 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001559 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001560 }
1561
1562 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1563
1564 // Get the size of the cache.
1565 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001566 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001567 if (result != VK_INCOMPLETE)
1568 {
1569 ANGLE_VK_TRY(displayVk, result);
1570 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001571
1572 angle::MemoryBuffer *pipelineCacheData = nullptr;
1573 ANGLE_VK_CHECK_ALLOC(displayVk,
1574 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1575
1576 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001577 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001578 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1579 // was determined just above), so receiving it hints at an implementation bug we would want
1580 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001581 ASSERT(result != VK_INCOMPLETE);
1582 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001583
1584 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1585 // the buffer to avoid leaking garbage memory.
1586 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1587 if (pipelineCacheSize < originalPipelineCacheSize)
1588 {
1589 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1590 originalPipelineCacheSize - pipelineCacheSize);
1591 }
1592
1593 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1594
Jamie Madill7c985f52018-11-29 18:16:17 -05001595 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001596}
1597
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001598angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1599 const vk::Semaphore **outSemaphore)
1600{
1601 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1602
1603 vk::SemaphoreHelper semaphore;
1604 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1605
1606 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1607 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1608
Jamie Madill7c985f52018-11-29 18:16:17 -05001609 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001610}
1611
1612const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1613{
1614 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1615
1616 // Return the semaphore to the pool (which will remain valid and unused until the
1617 // queue it's about to be waited on has finished execution). The caller is about
1618 // to wait on it.
1619 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1620
1621 return semaphore;
1622}
1623
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001624angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1625{
1626 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1627 // that seems impossible, so instead, we are going to make a small submission with just a
1628 // timestamp query. First, the disjoint timer query extension says:
1629 //
1630 // > This will return the GL time after all previous commands have reached the GL server but
1631 // have not yet necessarily executed.
1632 //
1633 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1634 // The wording allows us to make a submission to get the timestamp without performing a flush.
1635 //
1636 // Second:
1637 //
1638 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1639 // object target, applications can measure the latency between when commands reach the GL server
1640 // and when they are realized in the framebuffer.
1641 //
1642 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1643 // GPU bubble. This function directly generates a command buffer and submits it instead of
1644 // using the other member functions. This is to avoid changing any state, such as the queue
1645 // serial.
1646
1647 // Create a query used to receive the GPU timestamp
1648 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1649 vk::QueryHelper timestampQuery;
1650 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1651 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1652
1653 // Record the command buffer
1654 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1655 vk::CommandBuffer &commandBuffer = commandBatch.get();
1656
1657 VkCommandBufferAllocateInfo commandBufferInfo = {};
1658 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1659 commandBufferInfo.commandPool = mCommandPool.getHandle();
1660 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1661 commandBufferInfo.commandBufferCount = 1;
1662
Yuly Novikov27780292018-11-09 11:19:49 -05001663 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001664
1665 VkCommandBufferBeginInfo beginInfo = {};
1666 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1667 beginInfo.flags = 0;
1668 beginInfo.pInheritanceInfo = nullptr;
1669
Yuly Novikov27780292018-11-09 11:19:49 -05001670 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001671
1672 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1673 timestampQuery.getQuery(), 1);
1674 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1675 timestampQuery.getQueryPool()->getHandle(),
1676 timestampQuery.getQuery());
1677
Yuly Novikov27780292018-11-09 11:19:49 -05001678 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001679
1680 // Create fence for the submission
1681 VkFenceCreateInfo fenceInfo = {};
1682 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1683 fenceInfo.flags = 0;
1684
1685 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001686 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001687
1688 // Submit the command buffer
1689 VkSubmitInfo submitInfo = {};
1690 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1691 submitInfo.waitSemaphoreCount = 0;
1692 submitInfo.pWaitSemaphores = nullptr;
1693 submitInfo.pWaitDstStageMask = nullptr;
1694 submitInfo.commandBufferCount = 1;
1695 submitInfo.pCommandBuffers = commandBuffer.ptr();
1696 submitInfo.signalSemaphoreCount = 0;
1697 submitInfo.pSignalSemaphores = nullptr;
1698
1699 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1700
1701 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1702 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001703 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001704
1705 // Get the query results
1706 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1707
Yuly Novikov27780292018-11-09 11:19:49 -05001708 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1709 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1710 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001711
1712 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1713
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001714 // Convert results to nanoseconds.
1715 *timestampOut = static_cast<uint64_t>(
1716 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1717
Jamie Madill7c985f52018-11-29 18:16:17 -05001718 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001719}
1720
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001721// These functions look at the mandatory format for support, and fallback to querying the device (if
1722// necessary) to test the availability of the bits.
1723bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1724 const VkFormatFeatureFlags featureBits)
1725{
1726 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1727}
1728
1729bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1730 const VkFormatFeatureFlags featureBits)
1731{
1732 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1733}
1734
1735bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1736{
1737 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1738}
1739
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001740angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1741{
1742 ASSERT(mGpuEventsEnabled);
1743
1744 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1745 ASSERT(platform);
1746
1747 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1748 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1749 //
1750 // CPU GPU
1751 //
1752 // Record command buffer
1753 // with timestamp query
1754 //
1755 // Submit command buffer
1756 //
1757 // Post-submission work Begin execution
1758 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001759 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001760 //
1761 // ???? End execution
1762 //
1763 // ???? Return query results
1764 //
1765 // ????
1766 //
1767 // Get query results
1768 //
1769 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1770 // finished post-submission work while the GPU is executing in parallel. With no further work,
1771 // querying CPU timestamps before submission and after getting query results give the bounds to
1772 // Tgpu, which could be quite large.
1773 //
1774 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1775 // reduce this range. This function implements the following procedure:
1776 //
1777 // CPU GPU
1778 //
1779 // Record command buffer
1780 // with timestamp query
1781 //
1782 // Submit command buffer
1783 //
1784 // Post-submission work Begin execution
1785 //
1786 // ???? Set Event GPUReady
1787 //
1788 // Wait on Event GPUReady Wait on Event CPUReady
1789 //
1790 // Get CPU Time Ts Wait on Event CPUReady
1791 //
1792 // Set Event CPUReady Wait on Event CPUReady
1793 //
1794 // Get CPU Time Tcpu Get GPU Time Tgpu
1795 //
1796 // Wait on Event GPUDone Set Event GPUDone
1797 //
1798 // Get CPU Time Te End Execution
1799 //
1800 // Idle Return query results
1801 //
1802 // Get query results
1803 //
1804 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1805 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1806 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1807 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1808 // calibration.
1809 //
1810 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1811
1812 // Make sure nothing is running
1813 ASSERT(mCommandGraph.empty());
1814
1815 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1816
1817 // Create a query used to receive the GPU timestamp
1818 vk::QueryHelper timestampQuery;
1819 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1820
1821 // Create the three events
1822 VkEventCreateInfo eventCreateInfo = {};
1823 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1824 eventCreateInfo.flags = 0;
1825
1826 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001827 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1828 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1829 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001830
1831 constexpr uint32_t kRetries = 10;
1832
1833 // Time suffixes used are S for seconds and Cycles for cycles
1834 double tightestRangeS = 1e6f;
1835 double TcpuS = 0;
1836 uint64_t TgpuCycles = 0;
1837 for (uint32_t i = 0; i < kRetries; ++i)
1838 {
1839 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001840 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1841 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1842 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001843
1844 // Record the command buffer
1845 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1846 vk::CommandBuffer &commandBuffer = commandBatch.get();
1847
1848 VkCommandBufferAllocateInfo commandBufferInfo = {};
1849 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1850 commandBufferInfo.commandPool = mCommandPool.getHandle();
1851 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1852 commandBufferInfo.commandBufferCount = 1;
1853
Yuly Novikov27780292018-11-09 11:19:49 -05001854 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001855
1856 VkCommandBufferBeginInfo beginInfo = {};
1857 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1858 beginInfo.flags = 0;
1859 beginInfo.pInheritanceInfo = nullptr;
1860
Yuly Novikov27780292018-11-09 11:19:49 -05001861 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001862
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001863 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001864 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1865 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1866 nullptr);
1867
1868 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1869 timestampQuery.getQuery(), 1);
1870 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1871 timestampQuery.getQueryPool()->getHandle(),
1872 timestampQuery.getQuery());
1873
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001874 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001875
Yuly Novikov27780292018-11-09 11:19:49 -05001876 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001877
1878 // Submit the command buffer
1879 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1880 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1881 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1882
1883 VkSubmitInfo submitInfo = {};
1884 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1885 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1886 submitInfo.pWaitSemaphores = waitSemaphores.data();
1887 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1888 submitInfo.commandBufferCount = 1;
1889 submitInfo.pCommandBuffers = commandBuffer.ptr();
1890 submitInfo.signalSemaphoreCount = 0;
1891 submitInfo.pSignalSemaphores = nullptr;
1892
1893 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1894
1895 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001896 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001897 do
1898 {
Yuly Novikov27780292018-11-09 11:19:49 -05001899 result = gpuReady.get().getStatus(mDevice);
1900 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1901 {
1902 ANGLE_VK_TRY(context, result);
1903 }
1904 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001905
1906 double TsS = platform->monotonicallyIncreasingTime(platform);
1907
1908 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001909 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001910 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1911
1912 // Wait for GPU to be done. Another short busy wait.
1913 do
1914 {
Yuly Novikov27780292018-11-09 11:19:49 -05001915 result = gpuDone.get().getStatus(mDevice);
1916 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1917 {
1918 ANGLE_VK_TRY(context, result);
1919 }
1920 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001921
1922 double TeS = platform->monotonicallyIncreasingTime(platform);
1923
1924 // Get the query results
1925 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1926
1927 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1928
1929 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001930 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1931 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1932 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001933
1934 // Use the first timestamp queried as origin.
1935 if (mGpuEventTimestampOrigin == 0)
1936 {
1937 mGpuEventTimestampOrigin = gpuTimestampCycles;
1938 }
1939
1940 // Take these CPU and GPU timestamps if there is better confidence.
1941 double confidenceRangeS = TeS - TsS;
1942 if (confidenceRangeS < tightestRangeS)
1943 {
1944 tightestRangeS = confidenceRangeS;
1945 TcpuS = cpuTimestampS;
1946 TgpuCycles = gpuTimestampCycles;
1947 }
1948 }
1949
1950 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1951
1952 // timestampPeriod gives nanoseconds/cycle.
1953 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1954 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1955 1'000'000'000.0;
1956
1957 flushGpuEvents(TgpuS, TcpuS);
1958
1959 mGpuClockSync.gpuTimestampS = TgpuS;
1960 mGpuClockSync.cpuTimestampS = TcpuS;
1961
Jamie Madill7c985f52018-11-29 18:16:17 -05001962 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001963}
1964
1965angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1966 vk::CommandBuffer *commandBuffer,
1967 char phase,
1968 const char *name)
1969{
1970 ASSERT(mGpuEventsEnabled);
1971
1972 GpuEventQuery event;
1973
1974 event.name = name;
1975 event.phase = phase;
1976 event.serial = mCurrentQueueSerial;
1977
1978 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1979
1980 commandBuffer->resetQueryPool(
1981 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1982 commandBuffer->writeTimestamp(
1983 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1984 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1985
1986 mInFlightGpuEventQueries.push_back(std::move(event));
1987
Jamie Madill7c985f52018-11-29 18:16:17 -05001988 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001989}
1990
1991angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1992{
1993 ASSERT(mGpuEventsEnabled);
1994
1995 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1996 ASSERT(platform);
1997
1998 int finishedCount = 0;
1999
2000 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2001 {
2002 // Only check the timestamp query if the submission has finished.
2003 if (eventQuery.serial > mLastCompletedQueueSerial)
2004 {
2005 break;
2006 }
2007
2008 // See if the results are available.
2009 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002010 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2011 ->getResults(mDevice, eventQuery.queryIndex, 1,
2012 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2013 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2014 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002015 {
2016 break;
2017 }
Yuly Novikov27780292018-11-09 11:19:49 -05002018 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002019
2020 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2021
2022 GpuEvent event;
2023 event.gpuTimestampCycles = gpuTimestampCycles;
2024 event.name = eventQuery.name;
2025 event.phase = eventQuery.phase;
2026
2027 mGpuEvents.emplace_back(event);
2028
2029 ++finishedCount;
2030 }
2031
2032 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2033 mInFlightGpuEventQueries.begin() + finishedCount);
2034
Jamie Madill7c985f52018-11-29 18:16:17 -05002035 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002036}
2037
2038void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2039{
2040 if (mGpuEvents.size() == 0)
2041 {
2042 return;
2043 }
2044
2045 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2046 ASSERT(platform);
2047
2048 // Find the slope of the clock drift for adjustment
2049 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2050 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2051 double gpuSyncDriftSlope = 0;
2052
2053 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2054 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2055
2056 // No gpu trace events should have been generated before the clock sync, so if there is no
2057 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2058 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2059 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2060
2061 gpuSyncDriftSlope =
2062 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2063
2064 for (const GpuEvent &event : mGpuEvents)
2065 {
2066 double gpuTimestampS =
2067 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2068 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2069
2070 // Account for clock drift.
2071 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2072
2073 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2074 // for.
2075 static long long eventId = 1;
2076 static const unsigned char *categoryEnabled =
2077 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2078 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2079 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2080 }
2081
2082 mGpuEvents.clear();
2083}
2084
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002085template <VkFormatFeatureFlags VkFormatProperties::*features>
2086bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2087{
2088 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2089 VkFormatProperties &deviceProperties = mFormatProperties[format];
2090
2091 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2092 {
2093 // If we don't have the actual device features, see if the requested features are mandatory.
2094 // If so, there's no need to query the device.
2095 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2096 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2097 {
2098 return true;
2099 }
2100
2101 // Otherwise query the format features and cache it.
2102 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2103 }
2104
2105 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2106}
2107
Jamie Madillaaca96e2018-06-12 10:19:48 -04002108uint32_t GetUniformBufferDescriptorCount()
2109{
2110 return kUniformBufferDescriptorsPerDescriptorSet;
2111}
2112
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002113} // namespace rx