blob: 2184322fa5bb43abcbb207d6d1e3bb3a5e1b9c53 [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
Jamie Madille09bd5d2016-11-29 16:20:35 -0500616 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400617 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400618 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500619
620 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
621 if (instanceExtensionCount > 0)
622 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400623 ANGLE_VK_TRY(displayVk,
624 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
625 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500626 }
627
Michael Spang740db7f2019-02-06 09:40:13 -0500628 VulkanLayerVector enabledLayerNames;
Jamie Madill0448ec82016-12-23 13:41:47 -0500629 if (mEnableValidationLayers)
630 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500631 bool layersRequested =
632 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
Michael Spang740db7f2019-02-06 09:40:13 -0500633 mEnableValidationLayers =
634 GetAvailableValidationLayers(instanceLayerProps, layersRequested, &enabledLayerNames);
635 }
636
637 if (wsiLayer)
638 {
639 enabledLayerNames.push_back(wsiLayer);
Jamie Madill0448ec82016-12-23 13:41:47 -0500640 }
641
Jamie Madille09bd5d2016-11-29 16:20:35 -0500642 std::vector<const char *> enabledInstanceExtensions;
643 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500644 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500645
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500646 bool enableDebugUtils =
647 mEnableValidationLayers &&
648 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
649 bool enableDebugReport =
650 mEnableValidationLayers && !enableDebugUtils &&
651 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
652
653 if (enableDebugUtils)
654 {
655 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
656 }
657 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500658 {
659 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
660 }
661
Jamie Madille09bd5d2016-11-29 16:20:35 -0500662 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400663 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400664 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500665
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400666 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500667 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500668 applicationInfo.pApplicationName = "ANGLE";
669 applicationInfo.applicationVersion = 1;
670 applicationInfo.pEngineName = "ANGLE";
671 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700672
673 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
674 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
675 if (!enumerateInstanceVersion)
676 {
677 applicationInfo.apiVersion = VK_API_VERSION_1_0;
678 }
679 else
680 {
681 uint32_t apiVersion = VK_API_VERSION_1_0;
682 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
683 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
684 {
685 // Note: will need to revisit this with Vulkan 1.2+.
686 applicationInfo.apiVersion = VK_API_VERSION_1_1;
687 }
688 else
689 {
690 applicationInfo.apiVersion = VK_API_VERSION_1_0;
691 }
692 }
Jamie Madill327ba852016-11-30 12:38:28 -0500693
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400694 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500695 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
696 instanceInfo.flags = 0;
697 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500698
Jamie Madille09bd5d2016-11-29 16:20:35 -0500699 // Enable requested layers and extensions.
700 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
701 instanceInfo.ppEnabledExtensionNames =
702 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang740db7f2019-02-06 09:40:13 -0500703 instanceInfo.enabledLayerCount = enabledLayerNames.size();
704 instanceInfo.ppEnabledLayerNames = enabledLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500705
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400706 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500707
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500708 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500709 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500710 // Try to use the newer EXT_debug_utils if it exists.
711 InitDebugUtilsEXTFunctions(mInstance);
712
713 // Create the messenger callback.
714 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
715
716 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
717 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
718 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
719 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
720 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
721 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
722 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
723 messengerInfo.pUserData = this;
724
725 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
726 &mDebugUtilsMessenger));
727 }
728 else if (enableDebugReport)
729 {
730 // Fallback to EXT_debug_report.
731 InitDebugReportEXTFunctions(mInstance);
732
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400733 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500734
735 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500736 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500737 debugReportInfo.pfnCallback = &DebugReportCallback;
738 debugReportInfo.pUserData = this;
739
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500740 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
741 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500742 }
743
Jamie Madill4d0bf552016-12-28 15:45:24 -0500744 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400745 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
746 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500747
748 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700749 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400750 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
751 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400752 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700753 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500754
Jamie Madill30b5d842018-08-31 17:19:12 -0400755 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
756
Jamie Madill4d0bf552016-12-28 15:45:24 -0500757 // Ensure we can find a graphics queue family.
758 uint32_t queueCount = 0;
759 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
760
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400761 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500762
763 mQueueFamilyProperties.resize(queueCount);
764 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
765 mQueueFamilyProperties.data());
766
Jamie Madillb980c562018-11-27 11:34:27 -0500767 size_t graphicsQueueFamilyCount = false;
768 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500769 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500770 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
771 {
772 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500773 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500774 {
775 ASSERT(queueInfo.queueCount > 0);
776 graphicsQueueFamilyCount++;
777 if (firstGraphicsQueueFamily == 0)
778 {
779 firstGraphicsQueueFamily = familyIndex;
780 }
781 break;
782 }
783 }
784
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400785 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500786
787 // If only one queue family, go ahead and initialize the device. If there is more than one
788 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
789 if (graphicsQueueFamilyCount == 1)
790 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400791 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500792 }
793
Jamie Madill035fd6b2017-10-03 15:43:22 -0400794 // Store the physical device memory properties so we can find the right memory pools.
795 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500796
Jamie Madill06ca6342018-07-12 15:56:53 -0400797 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500798
Jamie Madill6a89d222017-11-02 11:59:51 -0400799 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500800 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400801
Jamie Madill7c985f52018-11-29 18:16:17 -0500802 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400803}
804
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400805angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500806{
807 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400808 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400809 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500810
811 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
812 if (deviceLayerCount > 0)
813 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400814 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
815 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500816 }
817
818 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400819 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
820 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500821
822 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
823 if (deviceExtensionCount > 0)
824 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400825 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
826 &deviceExtensionCount,
827 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500828 }
829
Michael Spang740db7f2019-02-06 09:40:13 -0500830 VulkanLayerVector enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500831 if (mEnableValidationLayers)
832 {
Michael Spang740db7f2019-02-06 09:40:13 -0500833 mEnableValidationLayers =
834 GetAvailableValidationLayers(deviceLayerProps, false, &enabledLayerNames);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500835 }
836
837 std::vector<const char *> enabledDeviceExtensions;
838 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
839
Ian Elliottbcb78902018-12-19 11:46:29 -0700840 initFeatures(deviceExtensionProps);
841 mFeaturesInitialized = true;
842
Luc Ferronbf6dc372018-06-28 15:24:19 -0400843 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700844 if ((getFeatures().flipViewportY) &&
845 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400846 {
847 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
848 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700849 if (getFeatures().supportsIncrementalPresent)
850 {
851 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
852 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400853
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400854 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500855
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400856 // Select additional features to be enabled
857 VkPhysicalDeviceFeatures enabledFeatures = {};
858 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500859 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400860
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400861 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862
863 float zeroPriority = 0.0f;
864
865 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500866 queueCreateInfo.flags = 0;
867 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
868 queueCreateInfo.queueCount = 1;
869 queueCreateInfo.pQueuePriorities = &zeroPriority;
870
871 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400872 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873
Jamie Madill50cf2be2018-06-15 09:46:57 -0400874 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400875 createInfo.flags = 0;
876 createInfo.queueCreateInfoCount = 1;
877 createInfo.pQueueCreateInfos = &queueCreateInfo;
Michael Spang740db7f2019-02-06 09:40:13 -0500878 createInfo.enabledLayerCount = enabledLayerNames.size();
879 createInfo.ppEnabledLayerNames = enabledLayerNames.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500880 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
881 createInfo.ppEnabledExtensionNames =
882 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400883 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500884
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400885 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500886
887 mCurrentQueueFamilyIndex = queueFamilyIndex;
888
889 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
890
891 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400892 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500893 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
894 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
895 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500896
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000897 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400898
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400899 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500900 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500901
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400902 // Initialize the submission semaphore pool.
903 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
904
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400905#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
906 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
907 ASSERT(platform);
908
909 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
910 // platform discovery.
911 const unsigned char *gpuEventsEnabled =
912 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
913 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
914#endif
915
916 if (mGpuEventsEnabled)
917 {
918 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
919 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
920 vk::kDefaultTimestampQueryPoolSize));
921 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
922 }
923
Jamie Madill7c985f52018-11-29 18:16:17 -0500924 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500925}
926
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400927angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400928 VkSurfaceKHR surface,
929 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500930{
931 // We've already initialized a device, and can't re-create it unless it's never been used.
932 // TODO(jmadill): Handle the re-creation case if necessary.
933 if (mDevice != VK_NULL_HANDLE)
934 {
935 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
936
937 // Check if the current device supports present on this surface.
938 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400939 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400940 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500941 surface, &supportsPresent));
942
Jamie Madill6cad7732018-07-11 09:01:17 -0400943 if (supportsPresent == VK_TRUE)
944 {
945 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500946 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400947 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500948 }
949
950 // Find a graphics and present queue.
951 Optional<uint32_t> newPresentQueue;
952 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500953 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500954 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
955 {
956 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500957 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500958 {
959 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400960 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
961 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500962
963 if (supportsPresent == VK_TRUE)
964 {
965 newPresentQueue = queueIndex;
966 break;
967 }
968 }
969 }
970
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400971 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
972 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500973
Jamie Madill6cad7732018-07-11 09:01:17 -0400974 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500975 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500976}
977
978std::string RendererVk::getVendorString() const
979{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300980 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500981}
982
Jamie Madille09bd5d2016-11-29 16:20:35 -0500983std::string RendererVk::getRendererDescription() const
984{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500985 std::stringstream strstr;
986
987 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
988
989 strstr << "Vulkan ";
990 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
991 strstr << VK_VERSION_MINOR(apiVersion) << ".";
992 strstr << VK_VERSION_PATCH(apiVersion);
993
Olli Etuahoc6a06182018-04-13 14:11:46 +0300994 strstr << "(";
995
996 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
997 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
998 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
999 // driver detection.
1000 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1001 {
1002 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1003 }
1004
Geoff Langa7af56b2018-12-14 14:20:28 -05001005 strstr << mPhysicalDeviceProperties.deviceName;
1006 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1007
1008 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001009
1010 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001011}
1012
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001013gl::Version RendererVk::getMaxSupportedESVersion() const
1014{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001015 // Current highest supported version
1016 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1017 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001018
Geoff Lang0c2c9232019-01-14 16:01:38 -05001019 // Vulkan inherited queries are required to support any GL query type
1020 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001021 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001022 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001023 }
1024
Geoff Lang0c2c9232019-01-14 16:01:38 -05001025 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001026}
1027
Ian Elliottbcb78902018-12-19 11:46:29 -07001028void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001029{
Jamie Madillb36a4812018-09-25 10:15:11 -04001030// Use OpenGL line rasterization rules by default.
1031// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1032#if defined(ANGLE_PLATFORM_ANDROID)
1033 mFeatures.basicGLLineRasterization = false;
1034#else
Jamie Madill12222072018-07-11 14:59:48 -04001035 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001036#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001037
Ian Elliott52f5da42018-12-21 09:02:09 -07001038 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1039 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001040 {
1041 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1042 // investigation. http://anglebug.com/2728
1043 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1044 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001045
1046#ifdef ANGLE_PLATFORM_WINDOWS
1047 // http://anglebug.com/2838
1048 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001049
1050 // http://anglebug.com/3055
1051 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001052#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001053
1054 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1055 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001056
1057 // Work around incorrect NVIDIA point size range clamping.
1058 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1059 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1060 {
1061 mFeatures.clampPointSize = true;
1062 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001063
Jamie Madillfa7ca182019-01-15 11:20:58 -05001064 // We also need to clamp point size on several Android drivers.
1065 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1066 if (IsAndroid())
1067 {
1068 mFeatures.clampPointSize = true;
1069 }
1070
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001071#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001072 // Work around ineffective compute-graphics barriers on Nexus 5X.
1073 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1074 // http://anglebug.com/3019
1075 mFeatures.flushAfterVertexConversion =
1076 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001077#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001078
1079 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1080 {
1081 mFeatures.supportsIncrementalPresent = true;
1082 }
Jamie Madill12222072018-07-11 14:59:48 -04001083}
1084
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001085void RendererVk::initPipelineCacheVkKey()
1086{
1087 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1088 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1089 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1090 // there is no '\0' in the result.
1091 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1092 {
1093 hashStream << std::hex << c;
1094 }
1095 // Add the vendor and device id too for good measure.
1096 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1097 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1098
1099 const std::string &hashString = hashStream.str();
1100 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1101 hashString.length(), mPipelineCacheVkBlobKey.data());
1102}
1103
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001104angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001105{
1106 initPipelineCacheVkKey();
1107
1108 egl::BlobCache::Value initialData;
1109 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1110 mPipelineCacheVkBlobKey, &initialData);
1111
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001112 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001113
1114 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001115 pipelineCacheCreateInfo.flags = 0;
1116 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1117 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1118
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001119 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001120 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001121}
1122
Jamie Madillacccc6c2016-05-03 17:22:10 -04001123void RendererVk::ensureCapsInitialized() const
1124{
1125 if (!mCapsInitialized)
1126 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001127 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1128 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1129 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001130 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001131 mCapsInitialized = true;
1132 }
1133}
1134
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001135void RendererVk::getSubmitWaitSemaphores(
1136 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001137 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1138 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001139{
1140 if (mSubmitLastSignaledSemaphore.getSemaphore())
1141 {
1142 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001143 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001144
1145 // Return the semaphore to the pool (which will remain valid and unused until the
1146 // queue it's about to be waited on has finished execution).
1147 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1148 }
1149
1150 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1151 {
1152 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001153 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1154
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001155 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1156 }
1157 mSubmitWaitSemaphores.clear();
1158}
1159
Jamie Madillacccc6c2016-05-03 17:22:10 -04001160const gl::Caps &RendererVk::getNativeCaps() const
1161{
1162 ensureCapsInitialized();
1163 return mNativeCaps;
1164}
1165
1166const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1167{
1168 ensureCapsInitialized();
1169 return mNativeTextureCaps;
1170}
1171
1172const gl::Extensions &RendererVk::getNativeExtensions() const
1173{
1174 ensureCapsInitialized();
1175 return mNativeExtensions;
1176}
1177
1178const gl::Limitations &RendererVk::getNativeLimitations() const
1179{
1180 ensureCapsInitialized();
1181 return mNativeLimitations;
1182}
1183
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001184uint32_t RendererVk::getMaxActiveTextures()
1185{
1186 // TODO(lucferron): expose this limitation to GL in Context Caps
1187 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1188 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1189}
1190
Jamie Madill49ac74b2017-12-21 14:42:33 -05001191const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001192{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001193 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001194}
1195
Jamie Madill21061022018-07-12 23:56:30 -04001196angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001197{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001198 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001199 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001200 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1201
Luc Ferron1617e692018-07-11 11:08:19 -04001202 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1203 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001204
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001205 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001206 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1207 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001208
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001209 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001210 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001211 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1212 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001213 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001214 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001215 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001216 submitInfo.signalSemaphoreCount = 0;
1217 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001218
Jamie Madill21061022018-07-12 23:56:30 -04001219 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001220 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001221
Jamie Madill4c26fc22017-02-24 11:04:10 -05001222 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001223 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001224 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001225
1226 if (mGpuEventsEnabled)
1227 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001228 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001229 while (mInFlightGpuEventQueries.size() > 0)
1230 {
1231 ANGLE_TRY(checkCompletedGpuEvents(context));
1232 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001233 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1234 // synchronization if there is no event to be adjusted (happens when finish() gets called
1235 // multiple times towards the end of the application).
1236 if (mGpuEvents.size() > 0)
1237 {
1238 ANGLE_TRY(synchronizeCpuGpuTime(context));
1239 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001240 }
1241
Jamie Madill7c985f52018-11-29 18:16:17 -05001242 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001243}
1244
Jamie Madill0c0dc342017-03-24 14:18:51 -04001245void RendererVk::freeAllInFlightResources()
1246{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001247 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001248 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001249 // On device loss we need to wait for fence to be signaled before destroying it
1250 if (mDeviceLost)
1251 {
1252 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1253 // If wait times out, it is probably not possible to recover from lost device
1254 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1255 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001256 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001257 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001258 }
1259 mInFlightCommands.clear();
1260
1261 for (auto &garbage : mGarbage)
1262 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001263 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001264 }
1265 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001266
1267 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001268}
1269
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001270angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001271{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001272 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001273
Jamie Madill49ac74b2017-12-21 14:42:33 -05001274 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001275 {
Yuly Novikov27780292018-11-09 11:19:49 -05001276 VkResult result = batch.fence.getStatus(mDevice);
1277 if (result == VK_NOT_READY)
1278 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001279 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001280 }
1281 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001282
Jamie Madill49ac74b2017-12-21 14:42:33 -05001283 ASSERT(batch.serial > mLastCompletedQueueSerial);
1284 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001285
Jamie Madill49ac74b2017-12-21 14:42:33 -05001286 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001287 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001288 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001289 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001290 }
1291
Jamie Madill49ac74b2017-12-21 14:42:33 -05001292 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001293
1294 size_t freeIndex = 0;
1295 for (; freeIndex < mGarbage.size(); ++freeIndex)
1296 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001297 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001298 break;
1299 }
1300
1301 // Remove the entries from the garbage list - they should be ready to go.
1302 if (freeIndex > 0)
1303 {
1304 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001305 }
1306
Jamie Madill7c985f52018-11-29 18:16:17 -05001307 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001308}
1309
Jamie Madill21061022018-07-12 23:56:30 -04001310angle::Result RendererVk::submitFrame(vk::Context *context,
1311 const VkSubmitInfo &submitInfo,
1312 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001313{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001314 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001315 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001316 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1317 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001319 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001320 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001321 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001322
Jamie Madill21061022018-07-12 23:56:30 -04001323 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001324
1325 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001326 batch.commandPool = std::move(mCommandPool);
1327 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001328
Jamie Madillbea35a62018-07-05 11:54:10 -04001329 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001330
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001331 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1332 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001333 // so the limit is larger than the expected number of images. The
1334 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001335 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001336
Jamie Madill85ca1892019-01-16 13:27:15 -05001337 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001338
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001339 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001340
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001341 if (mGpuEventsEnabled)
1342 {
1343 ANGLE_TRY(checkCompletedGpuEvents(context));
1344 }
1345
Jamie Madill49ac74b2017-12-21 14:42:33 -05001346 // Simply null out the command buffer here - it was allocated using the command pool.
1347 commandBuffer.releaseHandle();
1348
1349 // Reallocate the command pool for next frame.
1350 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001351 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001352 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001353 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001354 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001355
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001356 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001357 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001358}
1359
Jamie Madill85ca1892019-01-16 13:27:15 -05001360void RendererVk::nextSerial()
1361{
1362 // Increment the queue serial. If this fails, we should restart ANGLE.
1363 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1364 mCurrentQueueSerial = mQueueSerialFactory.generate();
1365
1366 // Notify the Contexts that they should be starting new command buffers.
1367 // We use one command pool per serial/submit associated with this VkQueue. We can also
1368 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1369 // check for a new serial when starting a new command buffer. We just check that the current
1370 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1371 // using this VkQueue that they their current command buffer is no longer valid.
1372 for (gl::Context *context : mDisplay->getContextSet())
1373 {
1374 ContextVk *contextVk = vk::GetImpl(context);
1375 contextVk->onCommandBufferFinished();
1376 }
1377}
1378
Jamie Madillaaca96e2018-06-12 10:19:48 -04001379bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001380{
1381 return serial > mLastCompletedQueueSerial;
1382}
1383
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001384angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1385{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001386 bool timedOut = false;
1387 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1388
1389 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1390 if (timedOut)
1391 {
1392 result = angle::Result::Stop;
1393 }
1394 return result;
1395}
1396
1397angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1398 Serial serial,
1399 uint64_t timeout,
1400 bool *outTimedOut)
1401{
1402 *outTimedOut = false;
1403
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001404 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1405 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001406 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001407 }
1408
1409 // Find the first batch with serial equal to or bigger than given serial (note that
1410 // the batch serials are unique, otherwise upper-bound would have been necessary).
1411 size_t batchIndex = mInFlightCommands.size() - 1;
1412 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1413 {
1414 if (mInFlightCommands[i].serial >= serial)
1415 {
1416 batchIndex = i;
1417 break;
1418 }
1419 }
1420 const CommandBatch &batch = mInFlightCommands[batchIndex];
1421
1422 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001423 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1424
1425 // If timed out, report it as such.
1426 if (status == VK_TIMEOUT)
1427 {
1428 *outTimedOut = true;
1429 return angle::Result::Continue;
1430 }
1431
1432 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001433
1434 // Clean up finished batches.
1435 return checkCompletedCommands(context);
1436}
1437
Jamie Madill21061022018-07-12 23:56:30 -04001438angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1439 const vk::RenderPassDesc &desc,
1440 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001441{
Jamie Madill21061022018-07-12 23:56:30 -04001442 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001443 renderPassOut);
1444}
1445
Jamie Madill21061022018-07-12 23:56:30 -04001446angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1447 const vk::RenderPassDesc &desc,
1448 const vk::AttachmentOpsArray &ops,
1449 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001450{
Jamie Madill21061022018-07-12 23:56:30 -04001451 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001452 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001453}
1454
Jamie Madilla5e06072018-05-18 14:36:05 -04001455vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001456{
Jamie Madilla5e06072018-05-18 14:36:05 -04001457 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001458}
1459
Jamie Madill21061022018-07-12 23:56:30 -04001460angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001461{
Jamie Madill21061022018-07-12 23:56:30 -04001462 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001463 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001464}
1465
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001466angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001467{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001468 if (mCommandGraph.empty())
1469 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001470 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001471 }
1472
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001473 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1474
Jamie Madillbea35a62018-07-05 11:54:10 -04001475 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1476 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001477
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001478 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001479 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1480 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001481
1482 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1483 // will be waited on.
1484 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001485
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001486 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001487 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001488 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1489 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001490 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001491 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001492 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001493 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001494 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001495
Jamie Madill21061022018-07-12 23:56:30 -04001496 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001497
Jamie Madill7c985f52018-11-29 18:16:17 -05001498 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001499}
1500
Jamie Madill78feddc2018-04-27 11:45:05 -04001501Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001502{
Jamie Madill78feddc2018-04-27 11:45:05 -04001503 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001504}
1505
Jamie Madill21061022018-07-12 23:56:30 -04001506angle::Result RendererVk::getDescriptorSetLayout(
1507 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001508 const vk::DescriptorSetLayoutDesc &desc,
1509 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1510{
Jamie Madill21061022018-07-12 23:56:30 -04001511 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001512}
1513
Jamie Madill21061022018-07-12 23:56:30 -04001514angle::Result RendererVk::getPipelineLayout(
1515 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001516 const vk::PipelineLayoutDesc &desc,
1517 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1518 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1519{
Jamie Madill21061022018-07-12 23:56:30 -04001520 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001521 pipelineLayoutOut);
1522}
1523
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001524angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1525{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001526 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001527
1528 if (--mPipelineCacheVkUpdateTimeout > 0)
1529 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001530 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001531 }
1532
1533 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1534
1535 // Get the size of the cache.
1536 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001537 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001538 if (result != VK_INCOMPLETE)
1539 {
1540 ANGLE_VK_TRY(displayVk, result);
1541 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001542
1543 angle::MemoryBuffer *pipelineCacheData = nullptr;
1544 ANGLE_VK_CHECK_ALLOC(displayVk,
1545 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1546
1547 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001548 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001549 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1550 // was determined just above), so receiving it hints at an implementation bug we would want
1551 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001552 ASSERT(result != VK_INCOMPLETE);
1553 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001554
1555 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1556 // the buffer to avoid leaking garbage memory.
1557 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1558 if (pipelineCacheSize < originalPipelineCacheSize)
1559 {
1560 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1561 originalPipelineCacheSize - pipelineCacheSize);
1562 }
1563
1564 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1565
Jamie Madill7c985f52018-11-29 18:16:17 -05001566 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001567}
1568
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001569angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1570 const vk::Semaphore **outSemaphore)
1571{
1572 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1573
1574 vk::SemaphoreHelper semaphore;
1575 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1576
1577 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1578 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1579
Jamie Madill7c985f52018-11-29 18:16:17 -05001580 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001581}
1582
1583const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1584{
1585 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1586
1587 // Return the semaphore to the pool (which will remain valid and unused until the
1588 // queue it's about to be waited on has finished execution). The caller is about
1589 // to wait on it.
1590 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1591
1592 return semaphore;
1593}
1594
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001595angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1596{
1597 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1598 // that seems impossible, so instead, we are going to make a small submission with just a
1599 // timestamp query. First, the disjoint timer query extension says:
1600 //
1601 // > This will return the GL time after all previous commands have reached the GL server but
1602 // have not yet necessarily executed.
1603 //
1604 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1605 // The wording allows us to make a submission to get the timestamp without performing a flush.
1606 //
1607 // Second:
1608 //
1609 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1610 // object target, applications can measure the latency between when commands reach the GL server
1611 // and when they are realized in the framebuffer.
1612 //
1613 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1614 // GPU bubble. This function directly generates a command buffer and submits it instead of
1615 // using the other member functions. This is to avoid changing any state, such as the queue
1616 // serial.
1617
1618 // Create a query used to receive the GPU timestamp
1619 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1620 vk::QueryHelper timestampQuery;
1621 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1622 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1623
1624 // Record the command buffer
1625 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1626 vk::CommandBuffer &commandBuffer = commandBatch.get();
1627
1628 VkCommandBufferAllocateInfo commandBufferInfo = {};
1629 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1630 commandBufferInfo.commandPool = mCommandPool.getHandle();
1631 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1632 commandBufferInfo.commandBufferCount = 1;
1633
Yuly Novikov27780292018-11-09 11:19:49 -05001634 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001635
1636 VkCommandBufferBeginInfo beginInfo = {};
1637 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1638 beginInfo.flags = 0;
1639 beginInfo.pInheritanceInfo = nullptr;
1640
Yuly Novikov27780292018-11-09 11:19:49 -05001641 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001642
1643 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1644 timestampQuery.getQuery(), 1);
1645 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1646 timestampQuery.getQueryPool()->getHandle(),
1647 timestampQuery.getQuery());
1648
Yuly Novikov27780292018-11-09 11:19:49 -05001649 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001650
1651 // Create fence for the submission
1652 VkFenceCreateInfo fenceInfo = {};
1653 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1654 fenceInfo.flags = 0;
1655
1656 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001657 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001658
1659 // Submit the command buffer
1660 VkSubmitInfo submitInfo = {};
1661 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1662 submitInfo.waitSemaphoreCount = 0;
1663 submitInfo.pWaitSemaphores = nullptr;
1664 submitInfo.pWaitDstStageMask = nullptr;
1665 submitInfo.commandBufferCount = 1;
1666 submitInfo.pCommandBuffers = commandBuffer.ptr();
1667 submitInfo.signalSemaphoreCount = 0;
1668 submitInfo.pSignalSemaphores = nullptr;
1669
1670 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1671
1672 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1673 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001674 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001675
1676 // Get the query results
1677 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1678
Yuly Novikov27780292018-11-09 11:19:49 -05001679 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1680 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1681 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001682
1683 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1684
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001685 // Convert results to nanoseconds.
1686 *timestampOut = static_cast<uint64_t>(
1687 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1688
Jamie Madill7c985f52018-11-29 18:16:17 -05001689 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001690}
1691
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001692// These functions look at the mandatory format for support, and fallback to querying the device (if
1693// necessary) to test the availability of the bits.
1694bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1695 const VkFormatFeatureFlags featureBits)
1696{
1697 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1698}
1699
1700bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1701 const VkFormatFeatureFlags featureBits)
1702{
1703 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1704}
1705
1706bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1707{
1708 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1709}
1710
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001711angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1712{
1713 ASSERT(mGpuEventsEnabled);
1714
1715 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1716 ASSERT(platform);
1717
1718 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1719 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1720 //
1721 // CPU GPU
1722 //
1723 // Record command buffer
1724 // with timestamp query
1725 //
1726 // Submit command buffer
1727 //
1728 // Post-submission work Begin execution
1729 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001730 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001731 //
1732 // ???? End execution
1733 //
1734 // ???? Return query results
1735 //
1736 // ????
1737 //
1738 // Get query results
1739 //
1740 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1741 // finished post-submission work while the GPU is executing in parallel. With no further work,
1742 // querying CPU timestamps before submission and after getting query results give the bounds to
1743 // Tgpu, which could be quite large.
1744 //
1745 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1746 // reduce this range. This function implements the following procedure:
1747 //
1748 // CPU GPU
1749 //
1750 // Record command buffer
1751 // with timestamp query
1752 //
1753 // Submit command buffer
1754 //
1755 // Post-submission work Begin execution
1756 //
1757 // ???? Set Event GPUReady
1758 //
1759 // Wait on Event GPUReady Wait on Event CPUReady
1760 //
1761 // Get CPU Time Ts Wait on Event CPUReady
1762 //
1763 // Set Event CPUReady Wait on Event CPUReady
1764 //
1765 // Get CPU Time Tcpu Get GPU Time Tgpu
1766 //
1767 // Wait on Event GPUDone Set Event GPUDone
1768 //
1769 // Get CPU Time Te End Execution
1770 //
1771 // Idle Return query results
1772 //
1773 // Get query results
1774 //
1775 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1776 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1777 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1778 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1779 // calibration.
1780 //
1781 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1782
1783 // Make sure nothing is running
1784 ASSERT(mCommandGraph.empty());
1785
1786 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1787
1788 // Create a query used to receive the GPU timestamp
1789 vk::QueryHelper timestampQuery;
1790 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1791
1792 // Create the three events
1793 VkEventCreateInfo eventCreateInfo = {};
1794 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1795 eventCreateInfo.flags = 0;
1796
1797 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001798 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1799 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1800 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001801
1802 constexpr uint32_t kRetries = 10;
1803
1804 // Time suffixes used are S for seconds and Cycles for cycles
1805 double tightestRangeS = 1e6f;
1806 double TcpuS = 0;
1807 uint64_t TgpuCycles = 0;
1808 for (uint32_t i = 0; i < kRetries; ++i)
1809 {
1810 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001811 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1812 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1813 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001814
1815 // Record the command buffer
1816 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1817 vk::CommandBuffer &commandBuffer = commandBatch.get();
1818
1819 VkCommandBufferAllocateInfo commandBufferInfo = {};
1820 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1821 commandBufferInfo.commandPool = mCommandPool.getHandle();
1822 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1823 commandBufferInfo.commandBufferCount = 1;
1824
Yuly Novikov27780292018-11-09 11:19:49 -05001825 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001826
1827 VkCommandBufferBeginInfo beginInfo = {};
1828 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1829 beginInfo.flags = 0;
1830 beginInfo.pInheritanceInfo = nullptr;
1831
Yuly Novikov27780292018-11-09 11:19:49 -05001832 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001833
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001834 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001835 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1836 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1837 nullptr);
1838
1839 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1840 timestampQuery.getQuery(), 1);
1841 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1842 timestampQuery.getQueryPool()->getHandle(),
1843 timestampQuery.getQuery());
1844
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001845 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001846
Yuly Novikov27780292018-11-09 11:19:49 -05001847 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001848
1849 // Submit the command buffer
1850 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1851 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1852 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1853
1854 VkSubmitInfo submitInfo = {};
1855 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1856 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1857 submitInfo.pWaitSemaphores = waitSemaphores.data();
1858 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1859 submitInfo.commandBufferCount = 1;
1860 submitInfo.pCommandBuffers = commandBuffer.ptr();
1861 submitInfo.signalSemaphoreCount = 0;
1862 submitInfo.pSignalSemaphores = nullptr;
1863
1864 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1865
1866 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001867 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001868 do
1869 {
Yuly Novikov27780292018-11-09 11:19:49 -05001870 result = gpuReady.get().getStatus(mDevice);
1871 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1872 {
1873 ANGLE_VK_TRY(context, result);
1874 }
1875 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001876
1877 double TsS = platform->monotonicallyIncreasingTime(platform);
1878
1879 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001880 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001881 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1882
1883 // Wait for GPU to be done. Another short busy wait.
1884 do
1885 {
Yuly Novikov27780292018-11-09 11:19:49 -05001886 result = gpuDone.get().getStatus(mDevice);
1887 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1888 {
1889 ANGLE_VK_TRY(context, result);
1890 }
1891 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001892
1893 double TeS = platform->monotonicallyIncreasingTime(platform);
1894
1895 // Get the query results
1896 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1897
1898 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1899
1900 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001901 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1902 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1903 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001904
1905 // Use the first timestamp queried as origin.
1906 if (mGpuEventTimestampOrigin == 0)
1907 {
1908 mGpuEventTimestampOrigin = gpuTimestampCycles;
1909 }
1910
1911 // Take these CPU and GPU timestamps if there is better confidence.
1912 double confidenceRangeS = TeS - TsS;
1913 if (confidenceRangeS < tightestRangeS)
1914 {
1915 tightestRangeS = confidenceRangeS;
1916 TcpuS = cpuTimestampS;
1917 TgpuCycles = gpuTimestampCycles;
1918 }
1919 }
1920
1921 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1922
1923 // timestampPeriod gives nanoseconds/cycle.
1924 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1925 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1926 1'000'000'000.0;
1927
1928 flushGpuEvents(TgpuS, TcpuS);
1929
1930 mGpuClockSync.gpuTimestampS = TgpuS;
1931 mGpuClockSync.cpuTimestampS = TcpuS;
1932
Jamie Madill7c985f52018-11-29 18:16:17 -05001933 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001934}
1935
1936angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1937 vk::CommandBuffer *commandBuffer,
1938 char phase,
1939 const char *name)
1940{
1941 ASSERT(mGpuEventsEnabled);
1942
1943 GpuEventQuery event;
1944
1945 event.name = name;
1946 event.phase = phase;
1947 event.serial = mCurrentQueueSerial;
1948
1949 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1950
1951 commandBuffer->resetQueryPool(
1952 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1953 commandBuffer->writeTimestamp(
1954 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1955 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1956
1957 mInFlightGpuEventQueries.push_back(std::move(event));
1958
Jamie Madill7c985f52018-11-29 18:16:17 -05001959 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001960}
1961
1962angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1963{
1964 ASSERT(mGpuEventsEnabled);
1965
1966 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1967 ASSERT(platform);
1968
1969 int finishedCount = 0;
1970
1971 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1972 {
1973 // Only check the timestamp query if the submission has finished.
1974 if (eventQuery.serial > mLastCompletedQueueSerial)
1975 {
1976 break;
1977 }
1978
1979 // See if the results are available.
1980 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001981 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1982 ->getResults(mDevice, eventQuery.queryIndex, 1,
1983 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1984 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1985 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001986 {
1987 break;
1988 }
Yuly Novikov27780292018-11-09 11:19:49 -05001989 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001990
1991 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1992
1993 GpuEvent event;
1994 event.gpuTimestampCycles = gpuTimestampCycles;
1995 event.name = eventQuery.name;
1996 event.phase = eventQuery.phase;
1997
1998 mGpuEvents.emplace_back(event);
1999
2000 ++finishedCount;
2001 }
2002
2003 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2004 mInFlightGpuEventQueries.begin() + finishedCount);
2005
Jamie Madill7c985f52018-11-29 18:16:17 -05002006 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002007}
2008
2009void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2010{
2011 if (mGpuEvents.size() == 0)
2012 {
2013 return;
2014 }
2015
2016 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2017 ASSERT(platform);
2018
2019 // Find the slope of the clock drift for adjustment
2020 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2021 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2022 double gpuSyncDriftSlope = 0;
2023
2024 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2025 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2026
2027 // No gpu trace events should have been generated before the clock sync, so if there is no
2028 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2029 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2030 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2031
2032 gpuSyncDriftSlope =
2033 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2034
2035 for (const GpuEvent &event : mGpuEvents)
2036 {
2037 double gpuTimestampS =
2038 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2039 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2040
2041 // Account for clock drift.
2042 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2043
2044 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2045 // for.
2046 static long long eventId = 1;
2047 static const unsigned char *categoryEnabled =
2048 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2049 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2050 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2051 }
2052
2053 mGpuEvents.clear();
2054}
2055
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002056template <VkFormatFeatureFlags VkFormatProperties::*features>
2057bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2058{
2059 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2060 VkFormatProperties &deviceProperties = mFormatProperties[format];
2061
2062 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2063 {
2064 // If we don't have the actual device features, see if the requested features are mandatory.
2065 // If so, there's no need to query the device.
2066 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2067 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2068 {
2069 return true;
2070 }
2071
2072 // Otherwise query the format features and cache it.
2073 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2074 }
2075
2076 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2077}
2078
Jamie Madillaaca96e2018-06-12 10:19:48 -04002079uint32_t GetUniformBufferDescriptorCount()
2080{
2081 return kUniformBufferDescriptorsPerDescriptorSet;
2082}
2083
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002084} // namespace rx