blob: 5c0c84749da47e9535ff621b119f75bc6d8d0825 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Shahbaz Youssefi61656022018-10-24 15:00:50 -040034#include "third_party/trace_event/trace_event.h"
35
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070036// Consts
37namespace
38{
Jamie Madill7c985f52018-11-29 18:16:17 -050039const uint32_t kMockVendorID = 0xba5eba11;
40const uint32_t kMockDeviceID = 0xf005ba11;
41constexpr char kMockDeviceName[] = "Vulkan Mock Device";
42constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050043constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070044} // anonymous namespace
45
Jamie Madill9e54b5a2016-05-25 12:57:39 -040046namespace rx
47{
48
Jamie Madille09bd5d2016-11-29 16:20:35 -050049namespace
50{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040051// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
52// one for the vertex shader.
53constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040054// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050055constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040056// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050057constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050058
Omar El Sheikh26c61b22018-06-29 12:50:59 -060059bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
60{
61#if !defined(ANGLE_PLATFORM_ANDROID)
62 // Mock ICD does not currently run on Android
63 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
64 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
66#else
67 return false;
68#endif // !defined(ANGLE_PLATFORM_ANDROID)
69}
70
Jamie Madille09bd5d2016-11-29 16:20:35 -050071VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
72 const std::vector<const char *> &enabledExtensionNames)
73{
74 // Compile the extensions names into a set.
75 std::set<std::string> extensionNames;
76 for (const auto &extensionProp : extensionProps)
77 {
78 extensionNames.insert(extensionProp.extensionName);
79 }
80
Jamie Madillacf2f3a2017-11-21 19:22:44 -050081 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050082 {
83 if (extensionNames.count(extensionName) == 0)
84 {
85 return VK_ERROR_EXTENSION_NOT_PRESENT;
86 }
87 }
88
89 return VK_SUCCESS;
90}
91
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050092bool ExtensionFound(const char *extensionName,
93 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060094{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050095 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060096 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050097 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060098 {
99 return true;
100 }
101 }
102 return false;
103}
104
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500105// Array of Validation error/warning messages that will be ignored, should include bugID
106constexpr std::array<const char *, 1> kSkippedMessages = {
107 // http://anglebug.com/2796
108 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
109
110// Suppress validation errors that are known
111// return "true" if given code/prefix/message is known, else return "false"
112bool IsIgnoredDebugMessage(const char *message)
113{
Michael Spang25839802019-01-30 18:02:51 -0500114 if (!message)
115 {
116 return false;
117 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500118 for (const char *msg : kSkippedMessages)
119 {
120 if (strstr(message, msg) != nullptr)
121 {
122 return true;
123 }
124 }
125 return false;
126}
127
128const char *GetVkObjectTypeName(VkObjectType type)
129{
130 switch (type)
131 {
132 case VK_OBJECT_TYPE_UNKNOWN:
133 return "Unknown";
134 case VK_OBJECT_TYPE_INSTANCE:
135 return "Instance";
136 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
137 return "Physical Device";
138 case VK_OBJECT_TYPE_DEVICE:
139 return "Device";
140 case VK_OBJECT_TYPE_QUEUE:
141 return "Queue";
142 case VK_OBJECT_TYPE_SEMAPHORE:
143 return "Semaphore";
144 case VK_OBJECT_TYPE_COMMAND_BUFFER:
145 return "Command Buffer";
146 case VK_OBJECT_TYPE_FENCE:
147 return "Fence";
148 case VK_OBJECT_TYPE_DEVICE_MEMORY:
149 return "Device Memory";
150 case VK_OBJECT_TYPE_BUFFER:
151 return "Buffer";
152 case VK_OBJECT_TYPE_IMAGE:
153 return "Image";
154 case VK_OBJECT_TYPE_EVENT:
155 return "Event";
156 case VK_OBJECT_TYPE_QUERY_POOL:
157 return "Query Pool";
158 case VK_OBJECT_TYPE_BUFFER_VIEW:
159 return "Buffer View";
160 case VK_OBJECT_TYPE_IMAGE_VIEW:
161 return "Image View";
162 case VK_OBJECT_TYPE_SHADER_MODULE:
163 return "Shader Module";
164 case VK_OBJECT_TYPE_PIPELINE_CACHE:
165 return "Pipeline Cache";
166 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
167 return "Pipeline Layout";
168 case VK_OBJECT_TYPE_RENDER_PASS:
169 return "Render Pass";
170 case VK_OBJECT_TYPE_PIPELINE:
171 return "Pipeline";
172 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
173 return "Descriptor Set Layout";
174 case VK_OBJECT_TYPE_SAMPLER:
175 return "Sampler";
176 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
177 return "Descriptor Pool";
178 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
179 return "Descriptor Set";
180 case VK_OBJECT_TYPE_FRAMEBUFFER:
181 return "Framebuffer";
182 case VK_OBJECT_TYPE_COMMAND_POOL:
183 return "Command Pool";
184 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
185 return "Sampler YCbCr Conversion";
186 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
187 return "Descriptor Update Template";
188 case VK_OBJECT_TYPE_SURFACE_KHR:
189 return "Surface";
190 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
191 return "Swapchain";
192 case VK_OBJECT_TYPE_DISPLAY_KHR:
193 return "Display";
194 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
195 return "Display Mode";
196 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
197 return "Debug Report Callback";
198 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
199 return "Object Table";
200 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
201 return "Indirect Commands Layout";
202 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
203 return "Debug Utils Messenger";
204 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
205 return "Validation Cache";
206 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
207 return "Acceleration Structure";
208 default:
209 return "<Unrecognized>";
210 }
211}
212
213VKAPI_ATTR VkBool32 VKAPI_CALL
214DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
215 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
216 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
217 void *userData)
218{
219 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
220 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
221 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
222
223 // Check if we even care about this message.
224 if ((messageSeverity & kSeveritiesToLog) == 0)
225 {
226 return VK_FALSE;
227 }
228
229 // See if it's an issue we are aware of and don't want to be spammed about.
230 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
231 {
232 return VK_FALSE;
233 }
234
235 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500236 if (callbackData->pMessageIdName)
237 {
238 log << "[ " << callbackData->pMessageIdName << " ] ";
239 }
240 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500241
242 // Aesthetic value based on length of the function name, line number, etc.
243 constexpr size_t kStartIndent = 28;
244
245 // Output the debug marker hierarchy under which this error has occured.
246 size_t indent = kStartIndent;
247 if (callbackData->queueLabelCount > 0)
248 {
249 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
250 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
251 {
252 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
253 << std::endl;
254 }
255 }
256 if (callbackData->cmdBufLabelCount > 0)
257 {
258 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
259 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
260 {
261 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
262 << std::endl;
263 }
264 }
265 // Output the objects involved in this error message.
266 if (callbackData->objectCount > 0)
267 {
268 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
269 {
270 const char *objectName = callbackData->pObjects[i].pObjectName;
271 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
272 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
273 log << std::string(indent, ' ') << "Object: ";
274 if (objectHandle == 0)
275 {
276 log << "VK_NULL_HANDLE";
277 }
278 else
279 {
280 log << "0x" << std::hex << objectHandle << std::dec;
281 }
282 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
283 if (objectName)
284 {
285 log << " [" << objectName << "]";
286 }
287 log << std::endl;
288 }
289 }
290
291 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
292
293 if (isError)
294 {
295 ERR() << log.str();
296 }
297 else
298 {
299 WARN() << log.str();
300 }
301
302 return VK_FALSE;
303}
304
Yuly Novikov199f4292018-01-19 19:04:05 -0500305VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
306 VkDebugReportObjectTypeEXT objectType,
307 uint64_t object,
308 size_t location,
309 int32_t messageCode,
310 const char *layerPrefix,
311 const char *message,
312 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500313{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600314 if (IsIgnoredDebugMessage(message))
315 {
316 return VK_FALSE;
317 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500318 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
319 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500320 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500321#if !defined(NDEBUG)
322 // Abort the call in Debug builds.
323 return VK_TRUE;
324#endif
325 }
326 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
327 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500328 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500329 }
330 else
331 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500332 // Uncomment this if you want Vulkan spam.
333 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500334 }
335
336 return VK_FALSE;
337}
338
Yuly Novikov199f4292018-01-19 19:04:05 -0500339// If we're loading the validation layers, we could be running from any random directory.
340// Change to the executable directory so we can find the layers, then change back to the
341// previous directory to be safe we don't disrupt the application.
342class ScopedVkLoaderEnvironment : angle::NonCopyable
343{
344 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600345 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
346 : mEnableValidationLayers(enableValidationLayers),
347 mEnableMockICD(enableMockICD),
348 mChangedCWD(false),
349 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500350 {
351// Changing CWD and setting environment variables makes no sense on Android,
352// since this code is a part of Java application there.
353// Android Vulkan loader doesn't need this either.
354#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600355 if (enableMockICD)
356 {
357 // Override environment variable to use built Mock ICD
358 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
359 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
360 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
361 if (!mChangedICDPath)
362 {
363 ERR() << "Error setting Path for Mock/Null Driver.";
364 mEnableMockICD = false;
365 }
366 }
Jamie Madill46848422018-08-09 10:46:06 -0400367 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500368 {
369 const auto &cwd = angle::GetCWD();
370 if (!cwd.valid())
371 {
372 ERR() << "Error getting CWD for Vulkan layers init.";
373 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400374 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500375 }
376 else
377 {
378 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500379 std::string exeDir = angle::GetExecutableDirectory();
380 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500381 if (!mChangedCWD)
382 {
383 ERR() << "Error setting CWD for Vulkan layers init.";
384 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400385 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500386 }
387 }
388 }
389
390 // Override environment variable to use the ANGLE layers.
391 if (mEnableValidationLayers)
392 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700393 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500394 {
395 ERR() << "Error setting environment for Vulkan layers init.";
396 mEnableValidationLayers = false;
397 }
398 }
399#endif // !defined(ANGLE_PLATFORM_ANDROID)
400 }
401
402 ~ScopedVkLoaderEnvironment()
403 {
404 if (mChangedCWD)
405 {
406#if !defined(ANGLE_PLATFORM_ANDROID)
407 ASSERT(mPreviousCWD.valid());
408 angle::SetCWD(mPreviousCWD.value().c_str());
409#endif // !defined(ANGLE_PLATFORM_ANDROID)
410 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600411 if (mChangedICDPath)
412 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600413 if (mPreviousICDPath.value().empty())
414 {
415 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
416 }
417 else
418 {
419 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
420 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600421 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500422 }
423
Jamie Madillaaca96e2018-06-12 10:19:48 -0400424 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500425
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool canEnableMockICD() const { return mEnableMockICD; }
427
Yuly Novikov199f4292018-01-19 19:04:05 -0500428 private:
429 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600430 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500431 bool mChangedCWD;
432 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600433 bool mChangedICDPath;
434 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500435};
436
Jamie Madill21061022018-07-12 23:56:30 -0400437void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
438 bool preferMockICD,
439 VkPhysicalDevice *physicalDeviceOut,
440 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
441{
442 ASSERT(!physicalDevices.empty());
443 if (preferMockICD)
444 {
445 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
446 {
447 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
448 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
449 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
450 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
451 {
452 *physicalDeviceOut = physicalDevice;
453 return;
454 }
455 }
456 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
457 "physicalDevice instead.";
458 }
459
460 // Fall back to first device.
461 *physicalDeviceOut = physicalDevices[0];
462 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
463}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400464
465// Initially dumping the command graphs is disabled.
466constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700467
Jamie Madille09bd5d2016-11-29 16:20:35 -0500468} // anonymous namespace
469
Jamie Madill49ac74b2017-12-21 14:42:33 -0500470// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400471RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500472
Jamie Madillaaca96e2018-06-12 10:19:48 -0400473RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500474
475RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000476 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500477{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500478
479RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
480{
481 std::swap(commandPool, other.commandPool);
482 std::swap(fence, other.fence);
483 std::swap(serial, other.serial);
484 return *this;
485}
486
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000487void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400488{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000489 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400490 fence.destroy(device);
491}
492
Jamie Madill9f2a8612017-11-30 12:43:09 -0500493// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500494RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400495 : mDisplay(nullptr),
496 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700497 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500498 mInstance(VK_NULL_HANDLE),
499 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400500 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500501 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500502 mDebugReportCallback(VK_NULL_HANDLE),
503 mPhysicalDevice(VK_NULL_HANDLE),
504 mQueue(VK_NULL_HANDLE),
505 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
506 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400507 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400508 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400509 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400510 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400511 mCommandGraph(kEnableCommandGraphDiagnostics),
512 mGpuEventsEnabled(false),
513 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
514 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500515{
516 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
517 mFormatProperties.fill(invalid);
518}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400519
Jamie Madillb980c562018-11-27 11:34:27 -0500520RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400521
522void RendererVk::onDestroy(vk::Context *context)
523{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500524 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500525 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500526 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400527 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500528 }
529
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100530 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500531
Jamie Madillc7918ce2018-06-13 13:25:31 -0400532 mPipelineLayoutCache.destroy(mDevice);
533 mDescriptorSetLayoutCache.destroy(mDevice);
534
Jamie Madill9f2a8612017-11-30 12:43:09 -0500535 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500536 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400537 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400538 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400539 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500540
Jamie Madill06ca6342018-07-12 15:56:53 -0400541 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500542
Jamie Madill5deea722017-02-16 10:44:46 -0500543 if (mCommandPool.valid())
544 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000545 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500546 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500547
548 if (mDevice)
549 {
550 vkDestroyDevice(mDevice, nullptr);
551 mDevice = VK_NULL_HANDLE;
552 }
553
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500554 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500555 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500556 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
557 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
558
559 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
560 }
561 else if (mDebugReportCallback)
562 {
563 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
564 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500565 }
566
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 if (mInstance)
568 {
569 vkDestroyInstance(mInstance, nullptr);
570 mInstance = VK_NULL_HANDLE;
571 }
572
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600573 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500574 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500575}
576
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400577void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400578{
579 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400580
581 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500582 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400583 freeAllInFlightResources();
584
585 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400586}
587
588bool RendererVk::isDeviceLost() const
589{
590 return mDeviceLost;
591}
592
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400593angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400594 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500595 const char *wsiExtension,
596 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500597{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400598 mDisplay = display;
599 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600600 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
601 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500602 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400603 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500604
Jamie Madill0448ec82016-12-23 13:41:47 -0500605 // Gather global layer properties.
606 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400607 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500608
609 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
610 if (instanceLayerCount > 0)
611 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400612 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
613 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500614 }
615
Michael Spang6c13c702019-02-06 15:59:44 -0500616 VulkanLayerVector enabledInstanceLayerNames;
617 if (mEnableValidationLayers)
618 {
619 bool layersRequested =
620 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
621 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
622 &enabledInstanceLayerNames);
623 }
624
625 if (wsiLayer)
626 {
627 enabledInstanceLayerNames.push_back(wsiLayer);
628 }
629
630 // Enumerate instance extensions that are provided by the vulkan
631 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500632 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400633 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400634 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500635
636 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
637 if (instanceExtensionCount > 0)
638 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400639 ANGLE_VK_TRY(displayVk,
640 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
641 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500642 }
643
Michael Spang6c13c702019-02-06 15:59:44 -0500644 // Enumerate instance extensions that are provided by explicit layers.
645 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500646 {
Michael Spang6c13c702019-02-06 15:59:44 -0500647 uint32_t previousExtensionCount = instanceExtensionProps.size();
648 uint32_t instanceLayerExtensionCount = 0;
649 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
650 layerName, &instanceLayerExtensionCount, nullptr));
651 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
652 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
653 layerName, &instanceLayerExtensionCount,
654 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500655 }
656
Jamie Madille09bd5d2016-11-29 16:20:35 -0500657 std::vector<const char *> enabledInstanceExtensions;
658 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500659 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500660
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500661 bool enableDebugUtils =
662 mEnableValidationLayers &&
663 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
664 bool enableDebugReport =
665 mEnableValidationLayers && !enableDebugUtils &&
666 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
667
668 if (enableDebugUtils)
669 {
670 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
671 }
672 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500673 {
674 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
675 }
676
Jamie Madille09bd5d2016-11-29 16:20:35 -0500677 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400678 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400679 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500680
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400681 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500682 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500683 applicationInfo.pApplicationName = "ANGLE";
684 applicationInfo.applicationVersion = 1;
685 applicationInfo.pEngineName = "ANGLE";
686 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700687
688 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
689 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
690 if (!enumerateInstanceVersion)
691 {
692 applicationInfo.apiVersion = VK_API_VERSION_1_0;
693 }
694 else
695 {
696 uint32_t apiVersion = VK_API_VERSION_1_0;
697 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
698 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
699 {
700 // Note: will need to revisit this with Vulkan 1.2+.
701 applicationInfo.apiVersion = VK_API_VERSION_1_1;
702 }
703 else
704 {
705 applicationInfo.apiVersion = VK_API_VERSION_1_0;
706 }
707 }
Jamie Madill327ba852016-11-30 12:38:28 -0500708
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400709 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500710 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
711 instanceInfo.flags = 0;
712 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500713
Jamie Madille09bd5d2016-11-29 16:20:35 -0500714 // Enable requested layers and extensions.
715 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
716 instanceInfo.ppEnabledExtensionNames =
717 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500718 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
719 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500720
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400721 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500722
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500723 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500724 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500725 // Try to use the newer EXT_debug_utils if it exists.
726 InitDebugUtilsEXTFunctions(mInstance);
727
728 // Create the messenger callback.
729 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
730
731 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
732 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
733 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
734 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
735 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
736 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
737 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
738 messengerInfo.pUserData = this;
739
740 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
741 &mDebugUtilsMessenger));
742 }
743 else if (enableDebugReport)
744 {
745 // Fallback to EXT_debug_report.
746 InitDebugReportEXTFunctions(mInstance);
747
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400748 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500749
750 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500751 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500752 debugReportInfo.pfnCallback = &DebugReportCallback;
753 debugReportInfo.pUserData = this;
754
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500755 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
756 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500757 }
758
Jamie Madill4d0bf552016-12-28 15:45:24 -0500759 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400760 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
761 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500762
763 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700764 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400765 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
766 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400767 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700768 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500769
Jamie Madill30b5d842018-08-31 17:19:12 -0400770 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
771
Jamie Madill4d0bf552016-12-28 15:45:24 -0500772 // Ensure we can find a graphics queue family.
773 uint32_t queueCount = 0;
774 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
775
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400776 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500777
778 mQueueFamilyProperties.resize(queueCount);
779 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
780 mQueueFamilyProperties.data());
781
Jamie Madillb980c562018-11-27 11:34:27 -0500782 size_t graphicsQueueFamilyCount = false;
783 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500784 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500785 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
786 {
787 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500788 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500789 {
790 ASSERT(queueInfo.queueCount > 0);
791 graphicsQueueFamilyCount++;
792 if (firstGraphicsQueueFamily == 0)
793 {
794 firstGraphicsQueueFamily = familyIndex;
795 }
796 break;
797 }
798 }
799
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400800 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500801
802 // If only one queue family, go ahead and initialize the device. If there is more than one
803 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
804 if (graphicsQueueFamilyCount == 1)
805 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400806 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500807 }
808
Jamie Madill035fd6b2017-10-03 15:43:22 -0400809 // Store the physical device memory properties so we can find the right memory pools.
810 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500811
Jamie Madill06ca6342018-07-12 15:56:53 -0400812 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500813
Jamie Madill6a89d222017-11-02 11:59:51 -0400814 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500815 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400816
Jamie Madill7c985f52018-11-29 18:16:17 -0500817 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400818}
819
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400820angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500821{
822 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400823 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400824 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500825
826 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
827 if (deviceLayerCount > 0)
828 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400829 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
830 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500831 }
832
Michael Spang6c13c702019-02-06 15:59:44 -0500833 VulkanLayerVector enabledDeviceLayerNames;
834 if (mEnableValidationLayers)
835 {
836 mEnableValidationLayers =
837 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
838 }
839
840 const char *wsiLayer = displayVk->getWSILayer();
841 if (wsiLayer)
842 {
843 enabledDeviceLayerNames.push_back(wsiLayer);
844 }
845
846 // Enumerate device extensions that are provided by the vulkan
847 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500848 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400849 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
850 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500851
852 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
853 if (deviceExtensionCount > 0)
854 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400855 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
856 &deviceExtensionCount,
857 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500858 }
859
Michael Spang6c13c702019-02-06 15:59:44 -0500860 // Enumerate device extensions that are provided by explicit layers.
861 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862 {
Michael Spang6c13c702019-02-06 15:59:44 -0500863 uint32_t previousExtensionCount = deviceExtensionProps.size();
864 uint32_t deviceLayerExtensionCount = 0;
865 ANGLE_VK_TRY(displayVk,
866 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
867 &deviceLayerExtensionCount, nullptr));
868 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
869 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
870 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
871 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500872 }
873
874 std::vector<const char *> enabledDeviceExtensions;
875 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
876
Ian Elliottbcb78902018-12-19 11:46:29 -0700877 initFeatures(deviceExtensionProps);
878 mFeaturesInitialized = true;
879
Luc Ferronbf6dc372018-06-28 15:24:19 -0400880 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700881 if ((getFeatures().flipViewportY) &&
882 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400883 {
884 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
885 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700886 if (getFeatures().supportsIncrementalPresent)
887 {
888 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
889 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400890
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400891 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500892
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400893 // Select additional features to be enabled
894 VkPhysicalDeviceFeatures enabledFeatures = {};
895 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500896 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400897
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400898 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500899
900 float zeroPriority = 0.0f;
901
902 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500903 queueCreateInfo.flags = 0;
904 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
905 queueCreateInfo.queueCount = 1;
906 queueCreateInfo.pQueuePriorities = &zeroPriority;
907
908 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400909 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500910
Jamie Madill50cf2be2018-06-15 09:46:57 -0400911 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400912 createInfo.flags = 0;
913 createInfo.queueCreateInfoCount = 1;
914 createInfo.pQueueCreateInfos = &queueCreateInfo;
Michael Spang6c13c702019-02-06 15:59:44 -0500915 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
916 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500917 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
918 createInfo.ppEnabledExtensionNames =
919 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400920 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500921
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400922 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500923
924 mCurrentQueueFamilyIndex = queueFamilyIndex;
925
926 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
927
928 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400929 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500930 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
931 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
932 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500933
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000934 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400935
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400936 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500937 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500938
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400939 // Initialize the submission semaphore pool.
940 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
941
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400942#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
943 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
944 ASSERT(platform);
945
946 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
947 // platform discovery.
948 const unsigned char *gpuEventsEnabled =
949 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
950 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
951#endif
952
953 if (mGpuEventsEnabled)
954 {
955 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
956 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
957 vk::kDefaultTimestampQueryPoolSize));
958 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
959 }
960
Jamie Madill7c985f52018-11-29 18:16:17 -0500961 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500962}
963
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400964angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400965 VkSurfaceKHR surface,
966 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500967{
968 // We've already initialized a device, and can't re-create it unless it's never been used.
969 // TODO(jmadill): Handle the re-creation case if necessary.
970 if (mDevice != VK_NULL_HANDLE)
971 {
972 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
973
974 // Check if the current device supports present on this surface.
975 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400976 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400977 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500978 surface, &supportsPresent));
979
Jamie Madill6cad7732018-07-11 09:01:17 -0400980 if (supportsPresent == VK_TRUE)
981 {
982 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500983 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400984 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500985 }
986
987 // Find a graphics and present queue.
988 Optional<uint32_t> newPresentQueue;
989 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500990 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500991 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
992 {
993 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500994 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500995 {
996 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400997 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
998 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500999
1000 if (supportsPresent == VK_TRUE)
1001 {
1002 newPresentQueue = queueIndex;
1003 break;
1004 }
1005 }
1006 }
1007
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001008 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1009 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001010
Jamie Madill6cad7732018-07-11 09:01:17 -04001011 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001012 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001013}
1014
1015std::string RendererVk::getVendorString() const
1016{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001017 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001018}
1019
Jamie Madille09bd5d2016-11-29 16:20:35 -05001020std::string RendererVk::getRendererDescription() const
1021{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001022 std::stringstream strstr;
1023
1024 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1025
1026 strstr << "Vulkan ";
1027 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1028 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1029 strstr << VK_VERSION_PATCH(apiVersion);
1030
Olli Etuahoc6a06182018-04-13 14:11:46 +03001031 strstr << "(";
1032
1033 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1034 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1035 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1036 // driver detection.
1037 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1038 {
1039 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1040 }
1041
Geoff Langa7af56b2018-12-14 14:20:28 -05001042 strstr << mPhysicalDeviceProperties.deviceName;
1043 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1044
1045 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001046
1047 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001048}
1049
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001050gl::Version RendererVk::getMaxSupportedESVersion() const
1051{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001052 // Current highest supported version
1053 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1054 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001055
Geoff Lang0c2c9232019-01-14 16:01:38 -05001056 // Vulkan inherited queries are required to support any GL query type
1057 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001058 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001059 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001060 }
1061
Geoff Lang0c2c9232019-01-14 16:01:38 -05001062 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001063}
1064
Ian Elliottbcb78902018-12-19 11:46:29 -07001065void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001066{
Jamie Madillb36a4812018-09-25 10:15:11 -04001067// Use OpenGL line rasterization rules by default.
1068// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1069#if defined(ANGLE_PLATFORM_ANDROID)
1070 mFeatures.basicGLLineRasterization = false;
1071#else
Jamie Madill12222072018-07-11 14:59:48 -04001072 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001073#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001074
Ian Elliott52f5da42018-12-21 09:02:09 -07001075 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1076 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001077 {
1078 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1079 // investigation. http://anglebug.com/2728
1080 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1081 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001082
1083#ifdef ANGLE_PLATFORM_WINDOWS
1084 // http://anglebug.com/2838
1085 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001086
1087 // http://anglebug.com/3055
1088 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001089#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001090
1091 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1092 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001093
1094 // Work around incorrect NVIDIA point size range clamping.
1095 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1096 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1097 {
1098 mFeatures.clampPointSize = true;
1099 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001100
Jamie Madillfa7ca182019-01-15 11:20:58 -05001101 // We also need to clamp point size on several Android drivers.
1102 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1103 if (IsAndroid())
1104 {
1105 mFeatures.clampPointSize = true;
1106 }
1107
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001108#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001109 // Work around ineffective compute-graphics barriers on Nexus 5X.
1110 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1111 // http://anglebug.com/3019
1112 mFeatures.flushAfterVertexConversion =
1113 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001114#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001115
1116 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1117 {
1118 mFeatures.supportsIncrementalPresent = true;
1119 }
Jamie Madill12222072018-07-11 14:59:48 -04001120}
1121
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001122void RendererVk::initPipelineCacheVkKey()
1123{
1124 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1125 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1126 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1127 // there is no '\0' in the result.
1128 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1129 {
1130 hashStream << std::hex << c;
1131 }
1132 // Add the vendor and device id too for good measure.
1133 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1134 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1135
1136 const std::string &hashString = hashStream.str();
1137 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1138 hashString.length(), mPipelineCacheVkBlobKey.data());
1139}
1140
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001141angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001142{
1143 initPipelineCacheVkKey();
1144
1145 egl::BlobCache::Value initialData;
1146 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1147 mPipelineCacheVkBlobKey, &initialData);
1148
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001149 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001150
1151 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001152 pipelineCacheCreateInfo.flags = 0;
1153 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1154 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1155
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001156 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001157 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001158}
1159
Jamie Madillacccc6c2016-05-03 17:22:10 -04001160void RendererVk::ensureCapsInitialized() const
1161{
1162 if (!mCapsInitialized)
1163 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001164 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1165 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1166 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001167 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001168 mCapsInitialized = true;
1169 }
1170}
1171
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001172void RendererVk::getSubmitWaitSemaphores(
1173 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001174 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1175 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001176{
1177 if (mSubmitLastSignaledSemaphore.getSemaphore())
1178 {
1179 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001180 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001181
1182 // Return the semaphore to the pool (which will remain valid and unused until the
1183 // queue it's about to be waited on has finished execution).
1184 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1185 }
1186
1187 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1188 {
1189 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001190 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1191
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001192 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1193 }
1194 mSubmitWaitSemaphores.clear();
1195}
1196
Jamie Madillacccc6c2016-05-03 17:22:10 -04001197const gl::Caps &RendererVk::getNativeCaps() const
1198{
1199 ensureCapsInitialized();
1200 return mNativeCaps;
1201}
1202
1203const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1204{
1205 ensureCapsInitialized();
1206 return mNativeTextureCaps;
1207}
1208
1209const gl::Extensions &RendererVk::getNativeExtensions() const
1210{
1211 ensureCapsInitialized();
1212 return mNativeExtensions;
1213}
1214
1215const gl::Limitations &RendererVk::getNativeLimitations() const
1216{
1217 ensureCapsInitialized();
1218 return mNativeLimitations;
1219}
1220
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001221uint32_t RendererVk::getMaxActiveTextures()
1222{
1223 // TODO(lucferron): expose this limitation to GL in Context Caps
1224 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1225 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1226}
1227
Jamie Madill49ac74b2017-12-21 14:42:33 -05001228const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001229{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001230 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001231}
1232
Jamie Madill21061022018-07-12 23:56:30 -04001233angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001234{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001235 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001236 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001237 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1238
Luc Ferron1617e692018-07-11 11:08:19 -04001239 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1240 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001241
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001242 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001243 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1244 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001245
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001246 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001247 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001248 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1249 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001250 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001251 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001252 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001253 submitInfo.signalSemaphoreCount = 0;
1254 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001255
Jamie Madill21061022018-07-12 23:56:30 -04001256 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001257 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001258
Jamie Madill4c26fc22017-02-24 11:04:10 -05001259 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001260 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001261 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001262
1263 if (mGpuEventsEnabled)
1264 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001265 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001266 while (mInFlightGpuEventQueries.size() > 0)
1267 {
1268 ANGLE_TRY(checkCompletedGpuEvents(context));
1269 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001270 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1271 // synchronization if there is no event to be adjusted (happens when finish() gets called
1272 // multiple times towards the end of the application).
1273 if (mGpuEvents.size() > 0)
1274 {
1275 ANGLE_TRY(synchronizeCpuGpuTime(context));
1276 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001277 }
1278
Jamie Madill7c985f52018-11-29 18:16:17 -05001279 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001280}
1281
Jamie Madill0c0dc342017-03-24 14:18:51 -04001282void RendererVk::freeAllInFlightResources()
1283{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001284 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001285 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001286 // On device loss we need to wait for fence to be signaled before destroying it
1287 if (mDeviceLost)
1288 {
1289 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1290 // If wait times out, it is probably not possible to recover from lost device
1291 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1292 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001293 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001294 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001295 }
1296 mInFlightCommands.clear();
1297
1298 for (auto &garbage : mGarbage)
1299 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001300 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001301 }
1302 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001303
1304 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001305}
1306
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001307angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001308{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001309 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001310
Jamie Madill49ac74b2017-12-21 14:42:33 -05001311 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001312 {
Yuly Novikov27780292018-11-09 11:19:49 -05001313 VkResult result = batch.fence.getStatus(mDevice);
1314 if (result == VK_NOT_READY)
1315 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001316 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001317 }
1318 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001319
Jamie Madill49ac74b2017-12-21 14:42:33 -05001320 ASSERT(batch.serial > mLastCompletedQueueSerial);
1321 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001322
Jamie Madill49ac74b2017-12-21 14:42:33 -05001323 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001324 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001325 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001326 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001327 }
1328
Jamie Madill49ac74b2017-12-21 14:42:33 -05001329 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001330
1331 size_t freeIndex = 0;
1332 for (; freeIndex < mGarbage.size(); ++freeIndex)
1333 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001334 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001335 break;
1336 }
1337
1338 // Remove the entries from the garbage list - they should be ready to go.
1339 if (freeIndex > 0)
1340 {
1341 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001342 }
1343
Jamie Madill7c985f52018-11-29 18:16:17 -05001344 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001345}
1346
Jamie Madill21061022018-07-12 23:56:30 -04001347angle::Result RendererVk::submitFrame(vk::Context *context,
1348 const VkSubmitInfo &submitInfo,
1349 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001350{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001351 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001352 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001353 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1354 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001355
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001356 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001357 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001358 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001359
Jamie Madill21061022018-07-12 23:56:30 -04001360 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001361
1362 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001363 batch.commandPool = std::move(mCommandPool);
1364 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001365
Jamie Madillbea35a62018-07-05 11:54:10 -04001366 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001367
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001368 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1369 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001370 // so the limit is larger than the expected number of images. The
1371 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001372 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001373
Jamie Madill85ca1892019-01-16 13:27:15 -05001374 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001375
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001376 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001377
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001378 if (mGpuEventsEnabled)
1379 {
1380 ANGLE_TRY(checkCompletedGpuEvents(context));
1381 }
1382
Jamie Madill49ac74b2017-12-21 14:42:33 -05001383 // Simply null out the command buffer here - it was allocated using the command pool.
1384 commandBuffer.releaseHandle();
1385
1386 // Reallocate the command pool for next frame.
1387 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001388 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001389 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001390 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001391 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001392
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001393 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001394 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001395}
1396
Jamie Madill85ca1892019-01-16 13:27:15 -05001397void RendererVk::nextSerial()
1398{
1399 // Increment the queue serial. If this fails, we should restart ANGLE.
1400 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1401 mCurrentQueueSerial = mQueueSerialFactory.generate();
1402
1403 // Notify the Contexts that they should be starting new command buffers.
1404 // We use one command pool per serial/submit associated with this VkQueue. We can also
1405 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1406 // check for a new serial when starting a new command buffer. We just check that the current
1407 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1408 // using this VkQueue that they their current command buffer is no longer valid.
1409 for (gl::Context *context : mDisplay->getContextSet())
1410 {
1411 ContextVk *contextVk = vk::GetImpl(context);
1412 contextVk->onCommandBufferFinished();
1413 }
1414}
1415
Jamie Madillaaca96e2018-06-12 10:19:48 -04001416bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001417{
1418 return serial > mLastCompletedQueueSerial;
1419}
1420
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001421angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1422{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001423 bool timedOut = false;
1424 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1425
1426 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1427 if (timedOut)
1428 {
1429 result = angle::Result::Stop;
1430 }
1431 return result;
1432}
1433
1434angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1435 Serial serial,
1436 uint64_t timeout,
1437 bool *outTimedOut)
1438{
1439 *outTimedOut = false;
1440
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001441 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1442 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001443 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001444 }
1445
1446 // Find the first batch with serial equal to or bigger than given serial (note that
1447 // the batch serials are unique, otherwise upper-bound would have been necessary).
1448 size_t batchIndex = mInFlightCommands.size() - 1;
1449 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1450 {
1451 if (mInFlightCommands[i].serial >= serial)
1452 {
1453 batchIndex = i;
1454 break;
1455 }
1456 }
1457 const CommandBatch &batch = mInFlightCommands[batchIndex];
1458
1459 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001460 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1461
1462 // If timed out, report it as such.
1463 if (status == VK_TIMEOUT)
1464 {
1465 *outTimedOut = true;
1466 return angle::Result::Continue;
1467 }
1468
1469 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001470
1471 // Clean up finished batches.
1472 return checkCompletedCommands(context);
1473}
1474
Jamie Madill21061022018-07-12 23:56:30 -04001475angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1476 const vk::RenderPassDesc &desc,
1477 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001478{
Jamie Madill21061022018-07-12 23:56:30 -04001479 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001480 renderPassOut);
1481}
1482
Jamie Madill21061022018-07-12 23:56:30 -04001483angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1484 const vk::RenderPassDesc &desc,
1485 const vk::AttachmentOpsArray &ops,
1486 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001487{
Jamie Madill21061022018-07-12 23:56:30 -04001488 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001489 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001490}
1491
Jamie Madilla5e06072018-05-18 14:36:05 -04001492vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001493{
Jamie Madilla5e06072018-05-18 14:36:05 -04001494 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001495}
1496
Jamie Madill21061022018-07-12 23:56:30 -04001497angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001498{
Jamie Madill21061022018-07-12 23:56:30 -04001499 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001500 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001501}
1502
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001503angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001504{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001505 if (mCommandGraph.empty())
1506 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001507 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001508 }
1509
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001510 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1511
Jamie Madillbea35a62018-07-05 11:54:10 -04001512 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1513 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001514
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001515 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001516 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1517 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001518
1519 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1520 // will be waited on.
1521 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001522
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001523 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001524 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001525 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1526 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001527 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001528 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001529 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001530 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001531 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001532
Jamie Madill21061022018-07-12 23:56:30 -04001533 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001534
Jamie Madill7c985f52018-11-29 18:16:17 -05001535 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001536}
1537
Jamie Madill78feddc2018-04-27 11:45:05 -04001538Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001539{
Jamie Madill78feddc2018-04-27 11:45:05 -04001540 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001541}
1542
Jamie Madill21061022018-07-12 23:56:30 -04001543angle::Result RendererVk::getDescriptorSetLayout(
1544 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001545 const vk::DescriptorSetLayoutDesc &desc,
1546 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1547{
Jamie Madill21061022018-07-12 23:56:30 -04001548 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001549}
1550
Jamie Madill21061022018-07-12 23:56:30 -04001551angle::Result RendererVk::getPipelineLayout(
1552 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001553 const vk::PipelineLayoutDesc &desc,
1554 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1555 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1556{
Jamie Madill21061022018-07-12 23:56:30 -04001557 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001558 pipelineLayoutOut);
1559}
1560
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001561angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1562{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001563 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001564
1565 if (--mPipelineCacheVkUpdateTimeout > 0)
1566 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001567 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001568 }
1569
1570 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1571
1572 // Get the size of the cache.
1573 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001574 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001575 if (result != VK_INCOMPLETE)
1576 {
1577 ANGLE_VK_TRY(displayVk, result);
1578 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001579
1580 angle::MemoryBuffer *pipelineCacheData = nullptr;
1581 ANGLE_VK_CHECK_ALLOC(displayVk,
1582 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1583
1584 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001585 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001586 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1587 // was determined just above), so receiving it hints at an implementation bug we would want
1588 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001589 ASSERT(result != VK_INCOMPLETE);
1590 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001591
1592 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1593 // the buffer to avoid leaking garbage memory.
1594 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1595 if (pipelineCacheSize < originalPipelineCacheSize)
1596 {
1597 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1598 originalPipelineCacheSize - pipelineCacheSize);
1599 }
1600
1601 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1602
Jamie Madill7c985f52018-11-29 18:16:17 -05001603 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001604}
1605
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001606angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1607 const vk::Semaphore **outSemaphore)
1608{
1609 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1610
1611 vk::SemaphoreHelper semaphore;
1612 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1613
1614 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1615 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1616
Jamie Madill7c985f52018-11-29 18:16:17 -05001617 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001618}
1619
1620const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1621{
1622 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1623
1624 // Return the semaphore to the pool (which will remain valid and unused until the
1625 // queue it's about to be waited on has finished execution). The caller is about
1626 // to wait on it.
1627 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1628
1629 return semaphore;
1630}
1631
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001632angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1633{
1634 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1635 // that seems impossible, so instead, we are going to make a small submission with just a
1636 // timestamp query. First, the disjoint timer query extension says:
1637 //
1638 // > This will return the GL time after all previous commands have reached the GL server but
1639 // have not yet necessarily executed.
1640 //
1641 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1642 // The wording allows us to make a submission to get the timestamp without performing a flush.
1643 //
1644 // Second:
1645 //
1646 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1647 // object target, applications can measure the latency between when commands reach the GL server
1648 // and when they are realized in the framebuffer.
1649 //
1650 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1651 // GPU bubble. This function directly generates a command buffer and submits it instead of
1652 // using the other member functions. This is to avoid changing any state, such as the queue
1653 // serial.
1654
1655 // Create a query used to receive the GPU timestamp
1656 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1657 vk::QueryHelper timestampQuery;
1658 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1659 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1660
1661 // Record the command buffer
1662 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1663 vk::CommandBuffer &commandBuffer = commandBatch.get();
1664
1665 VkCommandBufferAllocateInfo commandBufferInfo = {};
1666 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1667 commandBufferInfo.commandPool = mCommandPool.getHandle();
1668 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1669 commandBufferInfo.commandBufferCount = 1;
1670
Yuly Novikov27780292018-11-09 11:19:49 -05001671 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001672
1673 VkCommandBufferBeginInfo beginInfo = {};
1674 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1675 beginInfo.flags = 0;
1676 beginInfo.pInheritanceInfo = nullptr;
1677
Yuly Novikov27780292018-11-09 11:19:49 -05001678 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001679
1680 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1681 timestampQuery.getQuery(), 1);
1682 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1683 timestampQuery.getQueryPool()->getHandle(),
1684 timestampQuery.getQuery());
1685
Yuly Novikov27780292018-11-09 11:19:49 -05001686 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001687
1688 // Create fence for the submission
1689 VkFenceCreateInfo fenceInfo = {};
1690 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1691 fenceInfo.flags = 0;
1692
1693 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001694 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001695
1696 // Submit the command buffer
1697 VkSubmitInfo submitInfo = {};
1698 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1699 submitInfo.waitSemaphoreCount = 0;
1700 submitInfo.pWaitSemaphores = nullptr;
1701 submitInfo.pWaitDstStageMask = nullptr;
1702 submitInfo.commandBufferCount = 1;
1703 submitInfo.pCommandBuffers = commandBuffer.ptr();
1704 submitInfo.signalSemaphoreCount = 0;
1705 submitInfo.pSignalSemaphores = nullptr;
1706
1707 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1708
1709 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1710 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001711 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001712
1713 // Get the query results
1714 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1715
Yuly Novikov27780292018-11-09 11:19:49 -05001716 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1717 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1718 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001719
1720 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1721
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001722 // Convert results to nanoseconds.
1723 *timestampOut = static_cast<uint64_t>(
1724 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1725
Jamie Madill7c985f52018-11-29 18:16:17 -05001726 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001727}
1728
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001729// These functions look at the mandatory format for support, and fallback to querying the device (if
1730// necessary) to test the availability of the bits.
1731bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1732 const VkFormatFeatureFlags featureBits)
1733{
1734 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1735}
1736
1737bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1738 const VkFormatFeatureFlags featureBits)
1739{
1740 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1741}
1742
1743bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1744{
1745 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1746}
1747
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001748angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1749{
1750 ASSERT(mGpuEventsEnabled);
1751
1752 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1753 ASSERT(platform);
1754
1755 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1756 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1757 //
1758 // CPU GPU
1759 //
1760 // Record command buffer
1761 // with timestamp query
1762 //
1763 // Submit command buffer
1764 //
1765 // Post-submission work Begin execution
1766 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001767 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001768 //
1769 // ???? End execution
1770 //
1771 // ???? Return query results
1772 //
1773 // ????
1774 //
1775 // Get query results
1776 //
1777 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1778 // finished post-submission work while the GPU is executing in parallel. With no further work,
1779 // querying CPU timestamps before submission and after getting query results give the bounds to
1780 // Tgpu, which could be quite large.
1781 //
1782 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1783 // reduce this range. This function implements the following procedure:
1784 //
1785 // CPU GPU
1786 //
1787 // Record command buffer
1788 // with timestamp query
1789 //
1790 // Submit command buffer
1791 //
1792 // Post-submission work Begin execution
1793 //
1794 // ???? Set Event GPUReady
1795 //
1796 // Wait on Event GPUReady Wait on Event CPUReady
1797 //
1798 // Get CPU Time Ts Wait on Event CPUReady
1799 //
1800 // Set Event CPUReady Wait on Event CPUReady
1801 //
1802 // Get CPU Time Tcpu Get GPU Time Tgpu
1803 //
1804 // Wait on Event GPUDone Set Event GPUDone
1805 //
1806 // Get CPU Time Te End Execution
1807 //
1808 // Idle Return query results
1809 //
1810 // Get query results
1811 //
1812 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1813 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1814 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1815 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1816 // calibration.
1817 //
1818 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1819
1820 // Make sure nothing is running
1821 ASSERT(mCommandGraph.empty());
1822
1823 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1824
1825 // Create a query used to receive the GPU timestamp
1826 vk::QueryHelper timestampQuery;
1827 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1828
1829 // Create the three events
1830 VkEventCreateInfo eventCreateInfo = {};
1831 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1832 eventCreateInfo.flags = 0;
1833
1834 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001835 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1836 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1837 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001838
1839 constexpr uint32_t kRetries = 10;
1840
1841 // Time suffixes used are S for seconds and Cycles for cycles
1842 double tightestRangeS = 1e6f;
1843 double TcpuS = 0;
1844 uint64_t TgpuCycles = 0;
1845 for (uint32_t i = 0; i < kRetries; ++i)
1846 {
1847 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001848 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1849 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1850 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001851
1852 // Record the command buffer
1853 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1854 vk::CommandBuffer &commandBuffer = commandBatch.get();
1855
1856 VkCommandBufferAllocateInfo commandBufferInfo = {};
1857 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1858 commandBufferInfo.commandPool = mCommandPool.getHandle();
1859 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1860 commandBufferInfo.commandBufferCount = 1;
1861
Yuly Novikov27780292018-11-09 11:19:49 -05001862 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001863
1864 VkCommandBufferBeginInfo beginInfo = {};
1865 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1866 beginInfo.flags = 0;
1867 beginInfo.pInheritanceInfo = nullptr;
1868
Yuly Novikov27780292018-11-09 11:19:49 -05001869 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001870
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001871 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001872 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1873 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1874 nullptr);
1875
1876 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1877 timestampQuery.getQuery(), 1);
1878 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1879 timestampQuery.getQueryPool()->getHandle(),
1880 timestampQuery.getQuery());
1881
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001882 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001883
Yuly Novikov27780292018-11-09 11:19:49 -05001884 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001885
1886 // Submit the command buffer
1887 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1888 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1889 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1890
1891 VkSubmitInfo submitInfo = {};
1892 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1893 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1894 submitInfo.pWaitSemaphores = waitSemaphores.data();
1895 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1896 submitInfo.commandBufferCount = 1;
1897 submitInfo.pCommandBuffers = commandBuffer.ptr();
1898 submitInfo.signalSemaphoreCount = 0;
1899 submitInfo.pSignalSemaphores = nullptr;
1900
1901 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1902
1903 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001904 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001905 do
1906 {
Yuly Novikov27780292018-11-09 11:19:49 -05001907 result = gpuReady.get().getStatus(mDevice);
1908 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1909 {
1910 ANGLE_VK_TRY(context, result);
1911 }
1912 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001913
1914 double TsS = platform->monotonicallyIncreasingTime(platform);
1915
1916 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001917 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001918 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1919
1920 // Wait for GPU to be done. Another short busy wait.
1921 do
1922 {
Yuly Novikov27780292018-11-09 11:19:49 -05001923 result = gpuDone.get().getStatus(mDevice);
1924 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1925 {
1926 ANGLE_VK_TRY(context, result);
1927 }
1928 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001929
1930 double TeS = platform->monotonicallyIncreasingTime(platform);
1931
1932 // Get the query results
1933 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1934
1935 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1936
1937 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001938 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1939 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1940 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001941
1942 // Use the first timestamp queried as origin.
1943 if (mGpuEventTimestampOrigin == 0)
1944 {
1945 mGpuEventTimestampOrigin = gpuTimestampCycles;
1946 }
1947
1948 // Take these CPU and GPU timestamps if there is better confidence.
1949 double confidenceRangeS = TeS - TsS;
1950 if (confidenceRangeS < tightestRangeS)
1951 {
1952 tightestRangeS = confidenceRangeS;
1953 TcpuS = cpuTimestampS;
1954 TgpuCycles = gpuTimestampCycles;
1955 }
1956 }
1957
1958 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1959
1960 // timestampPeriod gives nanoseconds/cycle.
1961 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1962 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1963 1'000'000'000.0;
1964
1965 flushGpuEvents(TgpuS, TcpuS);
1966
1967 mGpuClockSync.gpuTimestampS = TgpuS;
1968 mGpuClockSync.cpuTimestampS = TcpuS;
1969
Jamie Madill7c985f52018-11-29 18:16:17 -05001970 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001971}
1972
1973angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1974 vk::CommandBuffer *commandBuffer,
1975 char phase,
1976 const char *name)
1977{
1978 ASSERT(mGpuEventsEnabled);
1979
1980 GpuEventQuery event;
1981
1982 event.name = name;
1983 event.phase = phase;
1984 event.serial = mCurrentQueueSerial;
1985
1986 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1987
1988 commandBuffer->resetQueryPool(
1989 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1990 commandBuffer->writeTimestamp(
1991 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1992 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1993
1994 mInFlightGpuEventQueries.push_back(std::move(event));
1995
Jamie Madill7c985f52018-11-29 18:16:17 -05001996 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001997}
1998
1999angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
2000{
2001 ASSERT(mGpuEventsEnabled);
2002
2003 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2004 ASSERT(platform);
2005
2006 int finishedCount = 0;
2007
2008 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2009 {
2010 // Only check the timestamp query if the submission has finished.
2011 if (eventQuery.serial > mLastCompletedQueueSerial)
2012 {
2013 break;
2014 }
2015
2016 // See if the results are available.
2017 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002018 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2019 ->getResults(mDevice, eventQuery.queryIndex, 1,
2020 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2021 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2022 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002023 {
2024 break;
2025 }
Yuly Novikov27780292018-11-09 11:19:49 -05002026 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002027
2028 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2029
2030 GpuEvent event;
2031 event.gpuTimestampCycles = gpuTimestampCycles;
2032 event.name = eventQuery.name;
2033 event.phase = eventQuery.phase;
2034
2035 mGpuEvents.emplace_back(event);
2036
2037 ++finishedCount;
2038 }
2039
2040 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2041 mInFlightGpuEventQueries.begin() + finishedCount);
2042
Jamie Madill7c985f52018-11-29 18:16:17 -05002043 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002044}
2045
2046void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2047{
2048 if (mGpuEvents.size() == 0)
2049 {
2050 return;
2051 }
2052
2053 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2054 ASSERT(platform);
2055
2056 // Find the slope of the clock drift for adjustment
2057 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2058 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2059 double gpuSyncDriftSlope = 0;
2060
2061 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2062 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2063
2064 // No gpu trace events should have been generated before the clock sync, so if there is no
2065 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2066 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2067 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2068
2069 gpuSyncDriftSlope =
2070 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2071
2072 for (const GpuEvent &event : mGpuEvents)
2073 {
2074 double gpuTimestampS =
2075 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2076 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2077
2078 // Account for clock drift.
2079 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2080
2081 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2082 // for.
2083 static long long eventId = 1;
2084 static const unsigned char *categoryEnabled =
2085 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2086 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2087 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2088 }
2089
2090 mGpuEvents.clear();
2091}
2092
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002093template <VkFormatFeatureFlags VkFormatProperties::*features>
2094bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2095{
2096 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2097 VkFormatProperties &deviceProperties = mFormatProperties[format];
2098
2099 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2100 {
2101 // If we don't have the actual device features, see if the requested features are mandatory.
2102 // If so, there's no need to query the device.
2103 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2104 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2105 {
2106 return true;
2107 }
2108
2109 // Otherwise query the format features and cache it.
2110 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2111 }
2112
2113 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2114}
2115
Jamie Madillaaca96e2018-06-12 10:19:48 -04002116uint32_t GetUniformBufferDescriptorCount()
2117{
2118 return kUniformBufferDescriptorsPerDescriptorSet;
2119}
2120
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002121} // namespace rx