blob: 57f78085691747f0367c19403d423865b9162ad7 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040034
Shahbaz Youssefi61656022018-10-24 15:00:50 -040035#include "third_party/trace_event/trace_event.h"
36
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070037// Consts
38namespace
39{
Jamie Madill7c985f52018-11-29 18:16:17 -050040const uint32_t kMockVendorID = 0xba5eba11;
41const uint32_t kMockDeviceID = 0xf005ba11;
42constexpr char kMockDeviceName[] = "Vulkan Mock Device";
43constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050044constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070045} // anonymous namespace
46
Jamie Madill9e54b5a2016-05-25 12:57:39 -040047namespace rx
48{
49
Jamie Madille09bd5d2016-11-29 16:20:35 -050050namespace
51{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040052// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
53// one for the vertex shader.
54constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040055// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050056constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040057// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050058constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050059
Omar El Sheikh26c61b22018-06-29 12:50:59 -060060bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
61{
62#if !defined(ANGLE_PLATFORM_ANDROID)
63 // Mock ICD does not currently run on Android
64 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
66 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
67#else
68 return false;
69#endif // !defined(ANGLE_PLATFORM_ANDROID)
70}
71
Jamie Madille09bd5d2016-11-29 16:20:35 -050072VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
73 const std::vector<const char *> &enabledExtensionNames)
74{
75 // Compile the extensions names into a set.
76 std::set<std::string> extensionNames;
77 for (const auto &extensionProp : extensionProps)
78 {
79 extensionNames.insert(extensionProp.extensionName);
80 }
81
Jamie Madillacf2f3a2017-11-21 19:22:44 -050082 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050083 {
84 if (extensionNames.count(extensionName) == 0)
85 {
86 return VK_ERROR_EXTENSION_NOT_PRESENT;
87 }
88 }
89
90 return VK_SUCCESS;
91}
92
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050093bool ExtensionFound(const char *extensionName,
94 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060095{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050096 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060097 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050098 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060099 {
100 return true;
101 }
102 }
103 return false;
104}
105
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500106// Array of Validation error/warning messages that will be ignored, should include bugID
107constexpr std::array<const char *, 1> kSkippedMessages = {
108 // http://anglebug.com/2796
109 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
110
111// Suppress validation errors that are known
112// return "true" if given code/prefix/message is known, else return "false"
113bool IsIgnoredDebugMessage(const char *message)
114{
115 for (const char *msg : kSkippedMessages)
116 {
117 if (strstr(message, msg) != nullptr)
118 {
119 return true;
120 }
121 }
122 return false;
123}
124
125const char *GetVkObjectTypeName(VkObjectType type)
126{
127 switch (type)
128 {
129 case VK_OBJECT_TYPE_UNKNOWN:
130 return "Unknown";
131 case VK_OBJECT_TYPE_INSTANCE:
132 return "Instance";
133 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
134 return "Physical Device";
135 case VK_OBJECT_TYPE_DEVICE:
136 return "Device";
137 case VK_OBJECT_TYPE_QUEUE:
138 return "Queue";
139 case VK_OBJECT_TYPE_SEMAPHORE:
140 return "Semaphore";
141 case VK_OBJECT_TYPE_COMMAND_BUFFER:
142 return "Command Buffer";
143 case VK_OBJECT_TYPE_FENCE:
144 return "Fence";
145 case VK_OBJECT_TYPE_DEVICE_MEMORY:
146 return "Device Memory";
147 case VK_OBJECT_TYPE_BUFFER:
148 return "Buffer";
149 case VK_OBJECT_TYPE_IMAGE:
150 return "Image";
151 case VK_OBJECT_TYPE_EVENT:
152 return "Event";
153 case VK_OBJECT_TYPE_QUERY_POOL:
154 return "Query Pool";
155 case VK_OBJECT_TYPE_BUFFER_VIEW:
156 return "Buffer View";
157 case VK_OBJECT_TYPE_IMAGE_VIEW:
158 return "Image View";
159 case VK_OBJECT_TYPE_SHADER_MODULE:
160 return "Shader Module";
161 case VK_OBJECT_TYPE_PIPELINE_CACHE:
162 return "Pipeline Cache";
163 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
164 return "Pipeline Layout";
165 case VK_OBJECT_TYPE_RENDER_PASS:
166 return "Render Pass";
167 case VK_OBJECT_TYPE_PIPELINE:
168 return "Pipeline";
169 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
170 return "Descriptor Set Layout";
171 case VK_OBJECT_TYPE_SAMPLER:
172 return "Sampler";
173 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
174 return "Descriptor Pool";
175 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
176 return "Descriptor Set";
177 case VK_OBJECT_TYPE_FRAMEBUFFER:
178 return "Framebuffer";
179 case VK_OBJECT_TYPE_COMMAND_POOL:
180 return "Command Pool";
181 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
182 return "Sampler YCbCr Conversion";
183 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
184 return "Descriptor Update Template";
185 case VK_OBJECT_TYPE_SURFACE_KHR:
186 return "Surface";
187 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
188 return "Swapchain";
189 case VK_OBJECT_TYPE_DISPLAY_KHR:
190 return "Display";
191 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
192 return "Display Mode";
193 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
194 return "Debug Report Callback";
195 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
196 return "Object Table";
197 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
198 return "Indirect Commands Layout";
199 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
200 return "Debug Utils Messenger";
201 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
202 return "Validation Cache";
203 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
204 return "Acceleration Structure";
205 default:
206 return "<Unrecognized>";
207 }
208}
209
210VKAPI_ATTR VkBool32 VKAPI_CALL
211DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
212 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
213 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
214 void *userData)
215{
216 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
217 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
218 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
219
220 // Check if we even care about this message.
221 if ((messageSeverity & kSeveritiesToLog) == 0)
222 {
223 return VK_FALSE;
224 }
225
226 // See if it's an issue we are aware of and don't want to be spammed about.
227 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
228 {
229 return VK_FALSE;
230 }
231
232 std::ostringstream log;
233 log << "[ " << callbackData->pMessageIdName << " ] " << callbackData->pMessage << std::endl;
234
235 // Aesthetic value based on length of the function name, line number, etc.
236 constexpr size_t kStartIndent = 28;
237
238 // Output the debug marker hierarchy under which this error has occured.
239 size_t indent = kStartIndent;
240 if (callbackData->queueLabelCount > 0)
241 {
242 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
243 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
244 {
245 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
246 << std::endl;
247 }
248 }
249 if (callbackData->cmdBufLabelCount > 0)
250 {
251 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
252 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
253 {
254 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
255 << std::endl;
256 }
257 }
258 // Output the objects involved in this error message.
259 if (callbackData->objectCount > 0)
260 {
261 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
262 {
263 const char *objectName = callbackData->pObjects[i].pObjectName;
264 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
265 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
266 log << std::string(indent, ' ') << "Object: ";
267 if (objectHandle == 0)
268 {
269 log << "VK_NULL_HANDLE";
270 }
271 else
272 {
273 log << "0x" << std::hex << objectHandle << std::dec;
274 }
275 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
276 if (objectName)
277 {
278 log << " [" << objectName << "]";
279 }
280 log << std::endl;
281 }
282 }
283
284 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
285
286 if (isError)
287 {
288 ERR() << log.str();
289 }
290 else
291 {
292 WARN() << log.str();
293 }
294
295 return VK_FALSE;
296}
297
Yuly Novikov199f4292018-01-19 19:04:05 -0500298VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
299 VkDebugReportObjectTypeEXT objectType,
300 uint64_t object,
301 size_t location,
302 int32_t messageCode,
303 const char *layerPrefix,
304 const char *message,
305 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500306{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600307 if (IsIgnoredDebugMessage(message))
308 {
309 return VK_FALSE;
310 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500311 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
312 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500313 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500314#if !defined(NDEBUG)
315 // Abort the call in Debug builds.
316 return VK_TRUE;
317#endif
318 }
319 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
320 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500321 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500322 }
323 else
324 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500325 // Uncomment this if you want Vulkan spam.
326 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500327 }
328
329 return VK_FALSE;
330}
331
Yuly Novikov199f4292018-01-19 19:04:05 -0500332// If we're loading the validation layers, we could be running from any random directory.
333// Change to the executable directory so we can find the layers, then change back to the
334// previous directory to be safe we don't disrupt the application.
335class ScopedVkLoaderEnvironment : angle::NonCopyable
336{
337 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600338 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
339 : mEnableValidationLayers(enableValidationLayers),
340 mEnableMockICD(enableMockICD),
341 mChangedCWD(false),
342 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500343 {
344// Changing CWD and setting environment variables makes no sense on Android,
345// since this code is a part of Java application there.
346// Android Vulkan loader doesn't need this either.
347#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600348 if (enableMockICD)
349 {
350 // Override environment variable to use built Mock ICD
351 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
352 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
353 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
354 if (!mChangedICDPath)
355 {
356 ERR() << "Error setting Path for Mock/Null Driver.";
357 mEnableMockICD = false;
358 }
359 }
Jamie Madill46848422018-08-09 10:46:06 -0400360 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500361 {
362 const auto &cwd = angle::GetCWD();
363 if (!cwd.valid())
364 {
365 ERR() << "Error getting CWD for Vulkan layers init.";
366 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400367 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500368 }
369 else
370 {
371 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500372 std::string exeDir = angle::GetExecutableDirectory();
373 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500374 if (!mChangedCWD)
375 {
376 ERR() << "Error setting CWD for Vulkan layers init.";
377 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400378 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500379 }
380 }
381 }
382
383 // Override environment variable to use the ANGLE layers.
384 if (mEnableValidationLayers)
385 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700386 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500387 {
388 ERR() << "Error setting environment for Vulkan layers init.";
389 mEnableValidationLayers = false;
390 }
391 }
392#endif // !defined(ANGLE_PLATFORM_ANDROID)
393 }
394
395 ~ScopedVkLoaderEnvironment()
396 {
397 if (mChangedCWD)
398 {
399#if !defined(ANGLE_PLATFORM_ANDROID)
400 ASSERT(mPreviousCWD.valid());
401 angle::SetCWD(mPreviousCWD.value().c_str());
402#endif // !defined(ANGLE_PLATFORM_ANDROID)
403 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600404 if (mChangedICDPath)
405 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600406 if (mPreviousICDPath.value().empty())
407 {
408 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
409 }
410 else
411 {
412 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
413 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600414 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500415 }
416
Jamie Madillaaca96e2018-06-12 10:19:48 -0400417 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500418
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600419 bool canEnableMockICD() const { return mEnableMockICD; }
420
Yuly Novikov199f4292018-01-19 19:04:05 -0500421 private:
422 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600423 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500424 bool mChangedCWD;
425 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool mChangedICDPath;
427 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500428};
429
Jamie Madill21061022018-07-12 23:56:30 -0400430void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
431 bool preferMockICD,
432 VkPhysicalDevice *physicalDeviceOut,
433 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
434{
435 ASSERT(!physicalDevices.empty());
436 if (preferMockICD)
437 {
438 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
439 {
440 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
441 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
442 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
443 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
444 {
445 *physicalDeviceOut = physicalDevice;
446 return;
447 }
448 }
449 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
450 "physicalDevice instead.";
451 }
452
453 // Fall back to first device.
454 *physicalDeviceOut = physicalDevices[0];
455 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
456}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400457
458// Initially dumping the command graphs is disabled.
459constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700460
Jamie Madille09bd5d2016-11-29 16:20:35 -0500461} // anonymous namespace
462
Jamie Madill49ac74b2017-12-21 14:42:33 -0500463// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400464RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500465
Jamie Madillaaca96e2018-06-12 10:19:48 -0400466RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500467
468RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000469 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500470{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500471
472RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
473{
474 std::swap(commandPool, other.commandPool);
475 std::swap(fence, other.fence);
476 std::swap(serial, other.serial);
477 return *this;
478}
479
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000480void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400481{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000482 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400483 fence.destroy(device);
484}
485
Jamie Madill9f2a8612017-11-30 12:43:09 -0500486// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500487RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400488 : mDisplay(nullptr),
489 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700490 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500491 mInstance(VK_NULL_HANDLE),
492 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400493 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500494 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500495 mDebugReportCallback(VK_NULL_HANDLE),
496 mPhysicalDevice(VK_NULL_HANDLE),
497 mQueue(VK_NULL_HANDLE),
498 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
499 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400500 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400501 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400502 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400503 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400504 mCommandGraph(kEnableCommandGraphDiagnostics),
505 mGpuEventsEnabled(false),
506 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
507 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500508{
509 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
510 mFormatProperties.fill(invalid);
511}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400512
Jamie Madillb980c562018-11-27 11:34:27 -0500513RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400514
515void RendererVk::onDestroy(vk::Context *context)
516{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500517 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500518 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500519 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400520 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500521 }
522
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100523 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500524
Jamie Madillc7918ce2018-06-13 13:25:31 -0400525 mPipelineLayoutCache.destroy(mDevice);
526 mDescriptorSetLayoutCache.destroy(mDevice);
527
Jamie Madill9f2a8612017-11-30 12:43:09 -0500528 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500529 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400530 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400531 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400532 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500533
Jamie Madill06ca6342018-07-12 15:56:53 -0400534 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500535
Jamie Madill5deea722017-02-16 10:44:46 -0500536 if (mCommandPool.valid())
537 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000538 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500539 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500540
541 if (mDevice)
542 {
543 vkDestroyDevice(mDevice, nullptr);
544 mDevice = VK_NULL_HANDLE;
545 }
546
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500547 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500548 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500549 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
550 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
551
552 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
553 }
554 else if (mDebugReportCallback)
555 {
556 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
557 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500558 }
559
Jamie Madill4d0bf552016-12-28 15:45:24 -0500560 if (mInstance)
561 {
562 vkDestroyInstance(mInstance, nullptr);
563 mInstance = VK_NULL_HANDLE;
564 }
565
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600566 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500568}
569
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400570void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400571{
572 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400573
574 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500575 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400576 freeAllInFlightResources();
577
578 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400579}
580
581bool RendererVk::isDeviceLost() const
582{
583 return mDeviceLost;
584}
585
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400586angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400587 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400588 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500589{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400590 mDisplay = display;
591 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600592 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
593 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500594 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400595 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500596
Jamie Madill0448ec82016-12-23 13:41:47 -0500597 // Gather global layer properties.
598 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400599 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500600
601 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
602 if (instanceLayerCount > 0)
603 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400604 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
605 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500606 }
607
Jamie Madille09bd5d2016-11-29 16:20:35 -0500608 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400609 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400610 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500611
612 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
613 if (instanceExtensionCount > 0)
614 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400615 ANGLE_VK_TRY(displayVk,
616 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
617 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500618 }
619
Yuly Novikov199f4292018-01-19 19:04:05 -0500620 const char *const *enabledLayerNames = nullptr;
621 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500622 if (mEnableValidationLayers)
623 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500624 bool layersRequested =
625 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
626 mEnableValidationLayers = GetAvailableValidationLayers(
627 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500628 }
629
Jamie Madille09bd5d2016-11-29 16:20:35 -0500630 std::vector<const char *> enabledInstanceExtensions;
631 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500632 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500633
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500634 bool enableDebugUtils =
635 mEnableValidationLayers &&
636 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
637 bool enableDebugReport =
638 mEnableValidationLayers && !enableDebugUtils &&
639 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
640
641 if (enableDebugUtils)
642 {
643 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
644 }
645 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500646 {
647 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
648 }
649
Jamie Madille09bd5d2016-11-29 16:20:35 -0500650 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400651 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400652 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500653
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400654 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500655 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500656 applicationInfo.pApplicationName = "ANGLE";
657 applicationInfo.applicationVersion = 1;
658 applicationInfo.pEngineName = "ANGLE";
659 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700660
661 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
662 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
663 if (!enumerateInstanceVersion)
664 {
665 applicationInfo.apiVersion = VK_API_VERSION_1_0;
666 }
667 else
668 {
669 uint32_t apiVersion = VK_API_VERSION_1_0;
670 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
671 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
672 {
673 // Note: will need to revisit this with Vulkan 1.2+.
674 applicationInfo.apiVersion = VK_API_VERSION_1_1;
675 }
676 else
677 {
678 applicationInfo.apiVersion = VK_API_VERSION_1_0;
679 }
680 }
Jamie Madill327ba852016-11-30 12:38:28 -0500681
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400682 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500683 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
684 instanceInfo.flags = 0;
685 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500686
Jamie Madille09bd5d2016-11-29 16:20:35 -0500687 // Enable requested layers and extensions.
688 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
689 instanceInfo.ppEnabledExtensionNames =
690 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500691 instanceInfo.enabledLayerCount = enabledLayerCount;
692 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500693
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400694 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500695
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500696 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500697 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500698 // Try to use the newer EXT_debug_utils if it exists.
699 InitDebugUtilsEXTFunctions(mInstance);
700
701 // Create the messenger callback.
702 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
703
704 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
705 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
706 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
707 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
708 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
709 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
710 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
711 messengerInfo.pUserData = this;
712
713 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
714 &mDebugUtilsMessenger));
715 }
716 else if (enableDebugReport)
717 {
718 // Fallback to EXT_debug_report.
719 InitDebugReportEXTFunctions(mInstance);
720
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400721 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500722
723 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500724 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500725 debugReportInfo.pfnCallback = &DebugReportCallback;
726 debugReportInfo.pUserData = this;
727
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500728 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
729 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500730 }
731
Jamie Madill4d0bf552016-12-28 15:45:24 -0500732 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400733 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
734 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500735
736 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700737 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400738 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
739 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400740 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700741 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500742
Jamie Madill30b5d842018-08-31 17:19:12 -0400743 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
744
Jamie Madill4d0bf552016-12-28 15:45:24 -0500745 // Ensure we can find a graphics queue family.
746 uint32_t queueCount = 0;
747 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
748
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400749 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500750
751 mQueueFamilyProperties.resize(queueCount);
752 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
753 mQueueFamilyProperties.data());
754
Jamie Madillb980c562018-11-27 11:34:27 -0500755 size_t graphicsQueueFamilyCount = false;
756 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500757 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500758 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
759 {
760 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500761 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500762 {
763 ASSERT(queueInfo.queueCount > 0);
764 graphicsQueueFamilyCount++;
765 if (firstGraphicsQueueFamily == 0)
766 {
767 firstGraphicsQueueFamily = familyIndex;
768 }
769 break;
770 }
771 }
772
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400773 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500774
775 // If only one queue family, go ahead and initialize the device. If there is more than one
776 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
777 if (graphicsQueueFamilyCount == 1)
778 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400779 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500780 }
781
Jamie Madill035fd6b2017-10-03 15:43:22 -0400782 // Store the physical device memory properties so we can find the right memory pools.
783 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500784
Jamie Madill06ca6342018-07-12 15:56:53 -0400785 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500786
Jamie Madill6a89d222017-11-02 11:59:51 -0400787 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500788 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400789
Jamie Madill7c985f52018-11-29 18:16:17 -0500790 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400791}
792
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400793angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500794{
795 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400796 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400797 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500798
799 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
800 if (deviceLayerCount > 0)
801 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400802 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
803 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500804 }
805
806 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400807 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
808 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500809
810 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
811 if (deviceExtensionCount > 0)
812 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400813 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
814 &deviceExtensionCount,
815 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500816 }
817
Yuly Novikov199f4292018-01-19 19:04:05 -0500818 const char *const *enabledLayerNames = nullptr;
819 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500820 if (mEnableValidationLayers)
821 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500822 mEnableValidationLayers = GetAvailableValidationLayers(
823 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500824 }
825
826 std::vector<const char *> enabledDeviceExtensions;
827 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
828
Ian Elliottbcb78902018-12-19 11:46:29 -0700829 initFeatures(deviceExtensionProps);
830 mFeaturesInitialized = true;
831
Luc Ferronbf6dc372018-06-28 15:24:19 -0400832 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700833 if ((getFeatures().flipViewportY) &&
834 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400835 {
836 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
837 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700838 if (getFeatures().supportsIncrementalPresent)
839 {
840 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
841 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400842
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400843 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500844
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400845 // Select additional features to be enabled
846 VkPhysicalDeviceFeatures enabledFeatures = {};
847 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500848 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400849
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400850 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500851
852 float zeroPriority = 0.0f;
853
854 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500855 queueCreateInfo.flags = 0;
856 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
857 queueCreateInfo.queueCount = 1;
858 queueCreateInfo.pQueuePriorities = &zeroPriority;
859
860 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400861 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862
Jamie Madill50cf2be2018-06-15 09:46:57 -0400863 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400864 createInfo.flags = 0;
865 createInfo.queueCreateInfoCount = 1;
866 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500867 createInfo.enabledLayerCount = enabledLayerCount;
868 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500869 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
870 createInfo.ppEnabledExtensionNames =
871 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400872 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400874 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500875
876 mCurrentQueueFamilyIndex = queueFamilyIndex;
877
878 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
879
880 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400881 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500882 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
883 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
884 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500885
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000886 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400887
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400888 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500889 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500890
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400891 // Initialize the submission semaphore pool.
892 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
893
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400894#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
895 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
896 ASSERT(platform);
897
898 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
899 // platform discovery.
900 const unsigned char *gpuEventsEnabled =
901 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
902 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
903#endif
904
905 if (mGpuEventsEnabled)
906 {
907 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
908 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
909 vk::kDefaultTimestampQueryPoolSize));
910 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
911 }
912
Jamie Madill7c985f52018-11-29 18:16:17 -0500913 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500914}
915
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400916angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400917 VkSurfaceKHR surface,
918 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500919{
920 // We've already initialized a device, and can't re-create it unless it's never been used.
921 // TODO(jmadill): Handle the re-creation case if necessary.
922 if (mDevice != VK_NULL_HANDLE)
923 {
924 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
925
926 // Check if the current device supports present on this surface.
927 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400928 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400929 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500930 surface, &supportsPresent));
931
Jamie Madill6cad7732018-07-11 09:01:17 -0400932 if (supportsPresent == VK_TRUE)
933 {
934 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500935 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400936 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500937 }
938
939 // Find a graphics and present queue.
940 Optional<uint32_t> newPresentQueue;
941 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500942 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500943 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
944 {
945 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500946 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500947 {
948 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400949 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
950 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500951
952 if (supportsPresent == VK_TRUE)
953 {
954 newPresentQueue = queueIndex;
955 break;
956 }
957 }
958 }
959
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400960 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
961 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500962
Jamie Madill6cad7732018-07-11 09:01:17 -0400963 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500964 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500965}
966
967std::string RendererVk::getVendorString() const
968{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300969 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500970}
971
Jamie Madille09bd5d2016-11-29 16:20:35 -0500972std::string RendererVk::getRendererDescription() const
973{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500974 std::stringstream strstr;
975
976 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
977
978 strstr << "Vulkan ";
979 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
980 strstr << VK_VERSION_MINOR(apiVersion) << ".";
981 strstr << VK_VERSION_PATCH(apiVersion);
982
Olli Etuahoc6a06182018-04-13 14:11:46 +0300983 strstr << "(";
984
985 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
986 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
987 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
988 // driver detection.
989 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
990 {
991 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
992 }
993
Geoff Langa7af56b2018-12-14 14:20:28 -0500994 strstr << mPhysicalDeviceProperties.deviceName;
995 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
996
997 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500998
999 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001000}
1001
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001002gl::Version RendererVk::getMaxSupportedESVersion() const
1003{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001004 // Current highest supported version
1005 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1006 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001007
Geoff Lang0c2c9232019-01-14 16:01:38 -05001008 // Vulkan inherited queries are required to support any GL query type
1009 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001010 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001011 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001012 }
1013
Geoff Lang0c2c9232019-01-14 16:01:38 -05001014 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001015}
1016
Ian Elliottbcb78902018-12-19 11:46:29 -07001017void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001018{
Jamie Madillb36a4812018-09-25 10:15:11 -04001019// Use OpenGL line rasterization rules by default.
1020// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1021#if defined(ANGLE_PLATFORM_ANDROID)
1022 mFeatures.basicGLLineRasterization = false;
1023#else
Jamie Madill12222072018-07-11 14:59:48 -04001024 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001025#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001026
Ian Elliott52f5da42018-12-21 09:02:09 -07001027 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1028 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001029 {
1030 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1031 // investigation. http://anglebug.com/2728
1032 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1033 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001034
1035#ifdef ANGLE_PLATFORM_WINDOWS
1036 // http://anglebug.com/2838
1037 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001038
1039 // http://anglebug.com/3055
1040 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001041#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001042
1043 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1044 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001045
1046 // Work around incorrect NVIDIA point size range clamping.
1047 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1048 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1049 {
1050 mFeatures.clampPointSize = true;
1051 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001052
Jamie Madillfa7ca182019-01-15 11:20:58 -05001053 // We also need to clamp point size on several Android drivers.
1054 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1055 if (IsAndroid())
1056 {
1057 mFeatures.clampPointSize = true;
1058 }
1059
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001060#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001061 // Work around ineffective compute-graphics barriers on Nexus 5X.
1062 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1063 // http://anglebug.com/3019
1064 mFeatures.flushAfterVertexConversion =
1065 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001066#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001067
1068 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1069 {
1070 mFeatures.supportsIncrementalPresent = true;
1071 }
Jamie Madill12222072018-07-11 14:59:48 -04001072}
1073
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001074void RendererVk::initPipelineCacheVkKey()
1075{
1076 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1077 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1078 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1079 // there is no '\0' in the result.
1080 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1081 {
1082 hashStream << std::hex << c;
1083 }
1084 // Add the vendor and device id too for good measure.
1085 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1086 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1087
1088 const std::string &hashString = hashStream.str();
1089 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1090 hashString.length(), mPipelineCacheVkBlobKey.data());
1091}
1092
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001093angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001094{
1095 initPipelineCacheVkKey();
1096
1097 egl::BlobCache::Value initialData;
1098 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1099 mPipelineCacheVkBlobKey, &initialData);
1100
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001101 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001102
1103 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001104 pipelineCacheCreateInfo.flags = 0;
1105 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1106 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1107
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001108 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001109 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001110}
1111
Jamie Madillacccc6c2016-05-03 17:22:10 -04001112void RendererVk::ensureCapsInitialized() const
1113{
1114 if (!mCapsInitialized)
1115 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001116 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1117 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1118 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001119 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001120 mCapsInitialized = true;
1121 }
1122}
1123
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001124void RendererVk::getSubmitWaitSemaphores(
1125 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001126 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1127 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001128{
1129 if (mSubmitLastSignaledSemaphore.getSemaphore())
1130 {
1131 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001132 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001133
1134 // Return the semaphore to the pool (which will remain valid and unused until the
1135 // queue it's about to be waited on has finished execution).
1136 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1137 }
1138
1139 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1140 {
1141 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001142 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1143
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001144 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1145 }
1146 mSubmitWaitSemaphores.clear();
1147}
1148
Jamie Madillacccc6c2016-05-03 17:22:10 -04001149const gl::Caps &RendererVk::getNativeCaps() const
1150{
1151 ensureCapsInitialized();
1152 return mNativeCaps;
1153}
1154
1155const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1156{
1157 ensureCapsInitialized();
1158 return mNativeTextureCaps;
1159}
1160
1161const gl::Extensions &RendererVk::getNativeExtensions() const
1162{
1163 ensureCapsInitialized();
1164 return mNativeExtensions;
1165}
1166
1167const gl::Limitations &RendererVk::getNativeLimitations() const
1168{
1169 ensureCapsInitialized();
1170 return mNativeLimitations;
1171}
1172
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001173uint32_t RendererVk::getMaxActiveTextures()
1174{
1175 // TODO(lucferron): expose this limitation to GL in Context Caps
1176 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1177 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1178}
1179
Jamie Madill49ac74b2017-12-21 14:42:33 -05001180const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001181{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001182 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001183}
1184
Jamie Madill21061022018-07-12 23:56:30 -04001185angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001186{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001187 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001188 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001189 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1190
Luc Ferron1617e692018-07-11 11:08:19 -04001191 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1192 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001193
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001194 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001195 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1196 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001197
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001198 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001199 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001200 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1201 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001202 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001203 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001204 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001205 submitInfo.signalSemaphoreCount = 0;
1206 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001207
Jamie Madill21061022018-07-12 23:56:30 -04001208 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001209 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001210
Jamie Madill4c26fc22017-02-24 11:04:10 -05001211 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001212 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001213 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001214
1215 if (mGpuEventsEnabled)
1216 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001217 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001218 while (mInFlightGpuEventQueries.size() > 0)
1219 {
1220 ANGLE_TRY(checkCompletedGpuEvents(context));
1221 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001222 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1223 // synchronization if there is no event to be adjusted (happens when finish() gets called
1224 // multiple times towards the end of the application).
1225 if (mGpuEvents.size() > 0)
1226 {
1227 ANGLE_TRY(synchronizeCpuGpuTime(context));
1228 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001229 }
1230
Jamie Madill7c985f52018-11-29 18:16:17 -05001231 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001232}
1233
Jamie Madill0c0dc342017-03-24 14:18:51 -04001234void RendererVk::freeAllInFlightResources()
1235{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001236 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001237 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001238 // On device loss we need to wait for fence to be signaled before destroying it
1239 if (mDeviceLost)
1240 {
1241 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1242 // If wait times out, it is probably not possible to recover from lost device
1243 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1244 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001245 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001246 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001247 }
1248 mInFlightCommands.clear();
1249
1250 for (auto &garbage : mGarbage)
1251 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001252 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001253 }
1254 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001255
1256 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001257}
1258
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001259angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001260{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001261 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001262
Jamie Madill49ac74b2017-12-21 14:42:33 -05001263 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001264 {
Yuly Novikov27780292018-11-09 11:19:49 -05001265 VkResult result = batch.fence.getStatus(mDevice);
1266 if (result == VK_NOT_READY)
1267 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001268 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001269 }
1270 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001271
Jamie Madill49ac74b2017-12-21 14:42:33 -05001272 ASSERT(batch.serial > mLastCompletedQueueSerial);
1273 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001274
Jamie Madill49ac74b2017-12-21 14:42:33 -05001275 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001276 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001277 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001278 }
1279
Jamie Madill49ac74b2017-12-21 14:42:33 -05001280 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001281
1282 size_t freeIndex = 0;
1283 for (; freeIndex < mGarbage.size(); ++freeIndex)
1284 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001285 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001286 break;
1287 }
1288
1289 // Remove the entries from the garbage list - they should be ready to go.
1290 if (freeIndex > 0)
1291 {
1292 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001293 }
1294
Jamie Madill7c985f52018-11-29 18:16:17 -05001295 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001296}
1297
Jamie Madill21061022018-07-12 23:56:30 -04001298angle::Result RendererVk::submitFrame(vk::Context *context,
1299 const VkSubmitInfo &submitInfo,
1300 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001301{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001302 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001303 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001304 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1305 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001306
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001307 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001308 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001309 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001310
Jamie Madill21061022018-07-12 23:56:30 -04001311 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001312
1313 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001314 batch.commandPool = std::move(mCommandPool);
1315 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001316
Jamie Madillbea35a62018-07-05 11:54:10 -04001317 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001318
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001319 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1320 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001321 // so the limit is larger than the expected number of images. The
1322 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001323 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001324
Jamie Madill85ca1892019-01-16 13:27:15 -05001325 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001326
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001327 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001328
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001329 if (mGpuEventsEnabled)
1330 {
1331 ANGLE_TRY(checkCompletedGpuEvents(context));
1332 }
1333
Jamie Madill49ac74b2017-12-21 14:42:33 -05001334 // Simply null out the command buffer here - it was allocated using the command pool.
1335 commandBuffer.releaseHandle();
1336
1337 // Reallocate the command pool for next frame.
1338 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001339 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001340 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001341 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001342 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001343
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001344 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001345 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001346}
1347
Jamie Madill85ca1892019-01-16 13:27:15 -05001348void RendererVk::nextSerial()
1349{
1350 // Increment the queue serial. If this fails, we should restart ANGLE.
1351 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1352 mCurrentQueueSerial = mQueueSerialFactory.generate();
1353
1354 // Notify the Contexts that they should be starting new command buffers.
1355 // We use one command pool per serial/submit associated with this VkQueue. We can also
1356 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1357 // check for a new serial when starting a new command buffer. We just check that the current
1358 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1359 // using this VkQueue that they their current command buffer is no longer valid.
1360 for (gl::Context *context : mDisplay->getContextSet())
1361 {
1362 ContextVk *contextVk = vk::GetImpl(context);
1363 contextVk->onCommandBufferFinished();
1364 }
1365}
1366
Jamie Madillaaca96e2018-06-12 10:19:48 -04001367bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001368{
1369 return serial > mLastCompletedQueueSerial;
1370}
1371
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001372angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1373{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001374 bool timedOut = false;
1375 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1376
1377 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1378 if (timedOut)
1379 {
1380 result = angle::Result::Stop;
1381 }
1382 return result;
1383}
1384
1385angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1386 Serial serial,
1387 uint64_t timeout,
1388 bool *outTimedOut)
1389{
1390 *outTimedOut = false;
1391
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001392 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1393 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001394 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001395 }
1396
1397 // Find the first batch with serial equal to or bigger than given serial (note that
1398 // the batch serials are unique, otherwise upper-bound would have been necessary).
1399 size_t batchIndex = mInFlightCommands.size() - 1;
1400 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1401 {
1402 if (mInFlightCommands[i].serial >= serial)
1403 {
1404 batchIndex = i;
1405 break;
1406 }
1407 }
1408 const CommandBatch &batch = mInFlightCommands[batchIndex];
1409
1410 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001411 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1412
1413 // If timed out, report it as such.
1414 if (status == VK_TIMEOUT)
1415 {
1416 *outTimedOut = true;
1417 return angle::Result::Continue;
1418 }
1419
1420 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001421
1422 // Clean up finished batches.
1423 return checkCompletedCommands(context);
1424}
1425
Jamie Madill21061022018-07-12 23:56:30 -04001426angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1427 const vk::RenderPassDesc &desc,
1428 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001429{
Jamie Madill21061022018-07-12 23:56:30 -04001430 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001431 renderPassOut);
1432}
1433
Jamie Madill21061022018-07-12 23:56:30 -04001434angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1435 const vk::RenderPassDesc &desc,
1436 const vk::AttachmentOpsArray &ops,
1437 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001438{
Jamie Madill21061022018-07-12 23:56:30 -04001439 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001440 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001441}
1442
Jamie Madilla5e06072018-05-18 14:36:05 -04001443vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001444{
Jamie Madilla5e06072018-05-18 14:36:05 -04001445 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001446}
1447
Jamie Madill21061022018-07-12 23:56:30 -04001448angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001449{
Jamie Madill21061022018-07-12 23:56:30 -04001450 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001451 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001452}
1453
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001454angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001455{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001456 if (mCommandGraph.empty())
1457 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001458 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001459 }
1460
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001461 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1462
Jamie Madillbea35a62018-07-05 11:54:10 -04001463 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1464 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001465
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001466 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001467 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1468 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001469
1470 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1471 // will be waited on.
1472 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001473
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001474 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001475 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001476 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1477 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001478 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001479 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001480 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001481 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001482 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001483
Jamie Madill21061022018-07-12 23:56:30 -04001484 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001485
Jamie Madill7c985f52018-11-29 18:16:17 -05001486 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001487}
1488
Jamie Madill78feddc2018-04-27 11:45:05 -04001489Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001490{
Jamie Madill78feddc2018-04-27 11:45:05 -04001491 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001492}
1493
Jamie Madill21061022018-07-12 23:56:30 -04001494angle::Result RendererVk::getDescriptorSetLayout(
1495 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001496 const vk::DescriptorSetLayoutDesc &desc,
1497 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1498{
Jamie Madill21061022018-07-12 23:56:30 -04001499 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001500}
1501
Jamie Madill21061022018-07-12 23:56:30 -04001502angle::Result RendererVk::getPipelineLayout(
1503 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001504 const vk::PipelineLayoutDesc &desc,
1505 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1506 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1507{
Jamie Madill21061022018-07-12 23:56:30 -04001508 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001509 pipelineLayoutOut);
1510}
1511
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001512angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1513{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001514 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001515
1516 if (--mPipelineCacheVkUpdateTimeout > 0)
1517 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001518 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001519 }
1520
1521 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1522
1523 // Get the size of the cache.
1524 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001525 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001526 if (result != VK_INCOMPLETE)
1527 {
1528 ANGLE_VK_TRY(displayVk, result);
1529 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001530
1531 angle::MemoryBuffer *pipelineCacheData = nullptr;
1532 ANGLE_VK_CHECK_ALLOC(displayVk,
1533 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1534
1535 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001536 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001537 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1538 // was determined just above), so receiving it hints at an implementation bug we would want
1539 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001540 ASSERT(result != VK_INCOMPLETE);
1541 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001542
1543 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1544 // the buffer to avoid leaking garbage memory.
1545 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1546 if (pipelineCacheSize < originalPipelineCacheSize)
1547 {
1548 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1549 originalPipelineCacheSize - pipelineCacheSize);
1550 }
1551
1552 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1553
Jamie Madill7c985f52018-11-29 18:16:17 -05001554 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001555}
1556
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001557angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1558 const vk::Semaphore **outSemaphore)
1559{
1560 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1561
1562 vk::SemaphoreHelper semaphore;
1563 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1564
1565 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1566 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1567
Jamie Madill7c985f52018-11-29 18:16:17 -05001568 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001569}
1570
1571const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1572{
1573 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1574
1575 // Return the semaphore to the pool (which will remain valid and unused until the
1576 // queue it's about to be waited on has finished execution). The caller is about
1577 // to wait on it.
1578 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1579
1580 return semaphore;
1581}
1582
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001583angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1584{
1585 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1586 // that seems impossible, so instead, we are going to make a small submission with just a
1587 // timestamp query. First, the disjoint timer query extension says:
1588 //
1589 // > This will return the GL time after all previous commands have reached the GL server but
1590 // have not yet necessarily executed.
1591 //
1592 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1593 // The wording allows us to make a submission to get the timestamp without performing a flush.
1594 //
1595 // Second:
1596 //
1597 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1598 // object target, applications can measure the latency between when commands reach the GL server
1599 // and when they are realized in the framebuffer.
1600 //
1601 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1602 // GPU bubble. This function directly generates a command buffer and submits it instead of
1603 // using the other member functions. This is to avoid changing any state, such as the queue
1604 // serial.
1605
1606 // Create a query used to receive the GPU timestamp
1607 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1608 vk::QueryHelper timestampQuery;
1609 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1610 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1611
1612 // Record the command buffer
1613 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1614 vk::CommandBuffer &commandBuffer = commandBatch.get();
1615
1616 VkCommandBufferAllocateInfo commandBufferInfo = {};
1617 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1618 commandBufferInfo.commandPool = mCommandPool.getHandle();
1619 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1620 commandBufferInfo.commandBufferCount = 1;
1621
Yuly Novikov27780292018-11-09 11:19:49 -05001622 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001623
1624 VkCommandBufferBeginInfo beginInfo = {};
1625 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1626 beginInfo.flags = 0;
1627 beginInfo.pInheritanceInfo = nullptr;
1628
Yuly Novikov27780292018-11-09 11:19:49 -05001629 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001630
1631 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1632 timestampQuery.getQuery(), 1);
1633 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1634 timestampQuery.getQueryPool()->getHandle(),
1635 timestampQuery.getQuery());
1636
Yuly Novikov27780292018-11-09 11:19:49 -05001637 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001638
1639 // Create fence for the submission
1640 VkFenceCreateInfo fenceInfo = {};
1641 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1642 fenceInfo.flags = 0;
1643
1644 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001645 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001646
1647 // Submit the command buffer
1648 VkSubmitInfo submitInfo = {};
1649 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1650 submitInfo.waitSemaphoreCount = 0;
1651 submitInfo.pWaitSemaphores = nullptr;
1652 submitInfo.pWaitDstStageMask = nullptr;
1653 submitInfo.commandBufferCount = 1;
1654 submitInfo.pCommandBuffers = commandBuffer.ptr();
1655 submitInfo.signalSemaphoreCount = 0;
1656 submitInfo.pSignalSemaphores = nullptr;
1657
1658 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1659
1660 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1661 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001662 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001663
1664 // Get the query results
1665 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1666
Yuly Novikov27780292018-11-09 11:19:49 -05001667 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1668 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1669 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001670
1671 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1672
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001673 // Convert results to nanoseconds.
1674 *timestampOut = static_cast<uint64_t>(
1675 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1676
Jamie Madill7c985f52018-11-29 18:16:17 -05001677 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001678}
1679
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001680// These functions look at the mandatory format for support, and fallback to querying the device (if
1681// necessary) to test the availability of the bits.
1682bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1683 const VkFormatFeatureFlags featureBits)
1684{
1685 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1686}
1687
1688bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1689 const VkFormatFeatureFlags featureBits)
1690{
1691 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1692}
1693
1694bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1695{
1696 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1697}
1698
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001699angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1700{
1701 ASSERT(mGpuEventsEnabled);
1702
1703 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1704 ASSERT(platform);
1705
1706 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1707 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1708 //
1709 // CPU GPU
1710 //
1711 // Record command buffer
1712 // with timestamp query
1713 //
1714 // Submit command buffer
1715 //
1716 // Post-submission work Begin execution
1717 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001718 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001719 //
1720 // ???? End execution
1721 //
1722 // ???? Return query results
1723 //
1724 // ????
1725 //
1726 // Get query results
1727 //
1728 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1729 // finished post-submission work while the GPU is executing in parallel. With no further work,
1730 // querying CPU timestamps before submission and after getting query results give the bounds to
1731 // Tgpu, which could be quite large.
1732 //
1733 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1734 // reduce this range. This function implements the following procedure:
1735 //
1736 // CPU GPU
1737 //
1738 // Record command buffer
1739 // with timestamp query
1740 //
1741 // Submit command buffer
1742 //
1743 // Post-submission work Begin execution
1744 //
1745 // ???? Set Event GPUReady
1746 //
1747 // Wait on Event GPUReady Wait on Event CPUReady
1748 //
1749 // Get CPU Time Ts Wait on Event CPUReady
1750 //
1751 // Set Event CPUReady Wait on Event CPUReady
1752 //
1753 // Get CPU Time Tcpu Get GPU Time Tgpu
1754 //
1755 // Wait on Event GPUDone Set Event GPUDone
1756 //
1757 // Get CPU Time Te End Execution
1758 //
1759 // Idle Return query results
1760 //
1761 // Get query results
1762 //
1763 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1764 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1765 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1766 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1767 // calibration.
1768 //
1769 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1770
1771 // Make sure nothing is running
1772 ASSERT(mCommandGraph.empty());
1773
1774 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1775
1776 // Create a query used to receive the GPU timestamp
1777 vk::QueryHelper timestampQuery;
1778 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1779
1780 // Create the three events
1781 VkEventCreateInfo eventCreateInfo = {};
1782 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1783 eventCreateInfo.flags = 0;
1784
1785 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001786 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1787 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1788 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001789
1790 constexpr uint32_t kRetries = 10;
1791
1792 // Time suffixes used are S for seconds and Cycles for cycles
1793 double tightestRangeS = 1e6f;
1794 double TcpuS = 0;
1795 uint64_t TgpuCycles = 0;
1796 for (uint32_t i = 0; i < kRetries; ++i)
1797 {
1798 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001799 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1800 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1801 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001802
1803 // Record the command buffer
1804 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1805 vk::CommandBuffer &commandBuffer = commandBatch.get();
1806
1807 VkCommandBufferAllocateInfo commandBufferInfo = {};
1808 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1809 commandBufferInfo.commandPool = mCommandPool.getHandle();
1810 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1811 commandBufferInfo.commandBufferCount = 1;
1812
Yuly Novikov27780292018-11-09 11:19:49 -05001813 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001814
1815 VkCommandBufferBeginInfo beginInfo = {};
1816 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1817 beginInfo.flags = 0;
1818 beginInfo.pInheritanceInfo = nullptr;
1819
Yuly Novikov27780292018-11-09 11:19:49 -05001820 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001821
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001822 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001823 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1824 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1825 nullptr);
1826
1827 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1828 timestampQuery.getQuery(), 1);
1829 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1830 timestampQuery.getQueryPool()->getHandle(),
1831 timestampQuery.getQuery());
1832
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001833 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001834
Yuly Novikov27780292018-11-09 11:19:49 -05001835 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001836
1837 // Submit the command buffer
1838 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1839 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1840 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1841
1842 VkSubmitInfo submitInfo = {};
1843 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1844 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1845 submitInfo.pWaitSemaphores = waitSemaphores.data();
1846 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1847 submitInfo.commandBufferCount = 1;
1848 submitInfo.pCommandBuffers = commandBuffer.ptr();
1849 submitInfo.signalSemaphoreCount = 0;
1850 submitInfo.pSignalSemaphores = nullptr;
1851
1852 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1853
1854 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001855 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001856 do
1857 {
Yuly Novikov27780292018-11-09 11:19:49 -05001858 result = gpuReady.get().getStatus(mDevice);
1859 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1860 {
1861 ANGLE_VK_TRY(context, result);
1862 }
1863 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001864
1865 double TsS = platform->monotonicallyIncreasingTime(platform);
1866
1867 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001868 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001869 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1870
1871 // Wait for GPU to be done. Another short busy wait.
1872 do
1873 {
Yuly Novikov27780292018-11-09 11:19:49 -05001874 result = gpuDone.get().getStatus(mDevice);
1875 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1876 {
1877 ANGLE_VK_TRY(context, result);
1878 }
1879 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001880
1881 double TeS = platform->monotonicallyIncreasingTime(platform);
1882
1883 // Get the query results
1884 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1885
1886 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1887
1888 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001889 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1890 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1891 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001892
1893 // Use the first timestamp queried as origin.
1894 if (mGpuEventTimestampOrigin == 0)
1895 {
1896 mGpuEventTimestampOrigin = gpuTimestampCycles;
1897 }
1898
1899 // Take these CPU and GPU timestamps if there is better confidence.
1900 double confidenceRangeS = TeS - TsS;
1901 if (confidenceRangeS < tightestRangeS)
1902 {
1903 tightestRangeS = confidenceRangeS;
1904 TcpuS = cpuTimestampS;
1905 TgpuCycles = gpuTimestampCycles;
1906 }
1907 }
1908
1909 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1910
1911 // timestampPeriod gives nanoseconds/cycle.
1912 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1913 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1914 1'000'000'000.0;
1915
1916 flushGpuEvents(TgpuS, TcpuS);
1917
1918 mGpuClockSync.gpuTimestampS = TgpuS;
1919 mGpuClockSync.cpuTimestampS = TcpuS;
1920
Jamie Madill7c985f52018-11-29 18:16:17 -05001921 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001922}
1923
1924angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1925 vk::CommandBuffer *commandBuffer,
1926 char phase,
1927 const char *name)
1928{
1929 ASSERT(mGpuEventsEnabled);
1930
1931 GpuEventQuery event;
1932
1933 event.name = name;
1934 event.phase = phase;
1935 event.serial = mCurrentQueueSerial;
1936
1937 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1938
1939 commandBuffer->resetQueryPool(
1940 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1941 commandBuffer->writeTimestamp(
1942 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1943 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1944
1945 mInFlightGpuEventQueries.push_back(std::move(event));
1946
Jamie Madill7c985f52018-11-29 18:16:17 -05001947 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001948}
1949
1950angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1951{
1952 ASSERT(mGpuEventsEnabled);
1953
1954 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1955 ASSERT(platform);
1956
1957 int finishedCount = 0;
1958
1959 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1960 {
1961 // Only check the timestamp query if the submission has finished.
1962 if (eventQuery.serial > mLastCompletedQueueSerial)
1963 {
1964 break;
1965 }
1966
1967 // See if the results are available.
1968 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001969 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1970 ->getResults(mDevice, eventQuery.queryIndex, 1,
1971 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1972 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1973 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001974 {
1975 break;
1976 }
Yuly Novikov27780292018-11-09 11:19:49 -05001977 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001978
1979 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1980
1981 GpuEvent event;
1982 event.gpuTimestampCycles = gpuTimestampCycles;
1983 event.name = eventQuery.name;
1984 event.phase = eventQuery.phase;
1985
1986 mGpuEvents.emplace_back(event);
1987
1988 ++finishedCount;
1989 }
1990
1991 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1992 mInFlightGpuEventQueries.begin() + finishedCount);
1993
Jamie Madill7c985f52018-11-29 18:16:17 -05001994 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001995}
1996
1997void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1998{
1999 if (mGpuEvents.size() == 0)
2000 {
2001 return;
2002 }
2003
2004 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2005 ASSERT(platform);
2006
2007 // Find the slope of the clock drift for adjustment
2008 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2009 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2010 double gpuSyncDriftSlope = 0;
2011
2012 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2013 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2014
2015 // No gpu trace events should have been generated before the clock sync, so if there is no
2016 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2017 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2018 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2019
2020 gpuSyncDriftSlope =
2021 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2022
2023 for (const GpuEvent &event : mGpuEvents)
2024 {
2025 double gpuTimestampS =
2026 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2027 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2028
2029 // Account for clock drift.
2030 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2031
2032 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2033 // for.
2034 static long long eventId = 1;
2035 static const unsigned char *categoryEnabled =
2036 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2037 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2038 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2039 }
2040
2041 mGpuEvents.clear();
2042}
2043
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002044template <VkFormatFeatureFlags VkFormatProperties::*features>
2045bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2046{
2047 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2048 VkFormatProperties &deviceProperties = mFormatProperties[format];
2049
2050 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2051 {
2052 // If we don't have the actual device features, see if the requested features are mandatory.
2053 // If so, there's no need to query the device.
2054 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2055 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2056 {
2057 return true;
2058 }
2059
2060 // Otherwise query the format features and cache it.
2061 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2062 }
2063
2064 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2065}
2066
Jamie Madillaaca96e2018-06-12 10:19:48 -04002067uint32_t GetUniformBufferDescriptorCount()
2068{
2069 return kUniformBufferDescriptorsPerDescriptorSet;
2070}
2071
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002072} // namespace rx