blob: 43689c04c13ea4e0a3aa46bb63c4465565dbd311 [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"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040020#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050021#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050022#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050023#include "libANGLE/renderer/vulkan/CompilerVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040024#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050025#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050026#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050027#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050028#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050029#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050030#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050031#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040032
Shahbaz Youssefi61656022018-10-24 15:00:50 -040033#include "third_party/trace_event/trace_event.h"
34
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070035// Consts
36namespace
37{
Jamie Madill7c985f52018-11-29 18:16:17 -050038const uint32_t kMockVendorID = 0xba5eba11;
39const uint32_t kMockDeviceID = 0xf005ba11;
40constexpr char kMockDeviceName[] = "Vulkan Mock Device";
41constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050042constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070043} // anonymous namespace
44
Jamie Madill9e54b5a2016-05-25 12:57:39 -040045namespace rx
46{
47
Jamie Madille09bd5d2016-11-29 16:20:35 -050048namespace
49{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040050// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
51// one for the vertex shader.
52constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040053// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
54static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040055// Wait a maximum of 10s. If that times out, we declare it a failure.
56static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050057
Omar El Sheikh26c61b22018-06-29 12:50:59 -060058bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
59{
60#if !defined(ANGLE_PLATFORM_ANDROID)
61 // Mock ICD does not currently run on Android
62 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
63 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
64 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
65#else
66 return false;
67#endif // !defined(ANGLE_PLATFORM_ANDROID)
68}
69
Jamie Madille09bd5d2016-11-29 16:20:35 -050070VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
71 const std::vector<const char *> &enabledExtensionNames)
72{
73 // Compile the extensions names into a set.
74 std::set<std::string> extensionNames;
75 for (const auto &extensionProp : extensionProps)
76 {
77 extensionNames.insert(extensionProp.extensionName);
78 }
79
Jamie Madillacf2f3a2017-11-21 19:22:44 -050080 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050081 {
82 if (extensionNames.count(extensionName) == 0)
83 {
84 return VK_ERROR_EXTENSION_NOT_PRESENT;
85 }
86 }
87
88 return VK_SUCCESS;
89}
90
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050091bool ExtensionFound(const char *extensionName,
92 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060093{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050094 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060095 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050096 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060097 {
98 return true;
99 }
100 }
101 return false;
102}
103
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500104// Array of Validation error/warning messages that will be ignored, should include bugID
105constexpr std::array<const char *, 1> kSkippedMessages = {
106 // http://anglebug.com/2796
107 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
108
109// Suppress validation errors that are known
110// return "true" if given code/prefix/message is known, else return "false"
111bool IsIgnoredDebugMessage(const char *message)
112{
113 for (const char *msg : kSkippedMessages)
114 {
115 if (strstr(message, msg) != nullptr)
116 {
117 return true;
118 }
119 }
120 return false;
121}
122
123const char *GetVkObjectTypeName(VkObjectType type)
124{
125 switch (type)
126 {
127 case VK_OBJECT_TYPE_UNKNOWN:
128 return "Unknown";
129 case VK_OBJECT_TYPE_INSTANCE:
130 return "Instance";
131 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
132 return "Physical Device";
133 case VK_OBJECT_TYPE_DEVICE:
134 return "Device";
135 case VK_OBJECT_TYPE_QUEUE:
136 return "Queue";
137 case VK_OBJECT_TYPE_SEMAPHORE:
138 return "Semaphore";
139 case VK_OBJECT_TYPE_COMMAND_BUFFER:
140 return "Command Buffer";
141 case VK_OBJECT_TYPE_FENCE:
142 return "Fence";
143 case VK_OBJECT_TYPE_DEVICE_MEMORY:
144 return "Device Memory";
145 case VK_OBJECT_TYPE_BUFFER:
146 return "Buffer";
147 case VK_OBJECT_TYPE_IMAGE:
148 return "Image";
149 case VK_OBJECT_TYPE_EVENT:
150 return "Event";
151 case VK_OBJECT_TYPE_QUERY_POOL:
152 return "Query Pool";
153 case VK_OBJECT_TYPE_BUFFER_VIEW:
154 return "Buffer View";
155 case VK_OBJECT_TYPE_IMAGE_VIEW:
156 return "Image View";
157 case VK_OBJECT_TYPE_SHADER_MODULE:
158 return "Shader Module";
159 case VK_OBJECT_TYPE_PIPELINE_CACHE:
160 return "Pipeline Cache";
161 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
162 return "Pipeline Layout";
163 case VK_OBJECT_TYPE_RENDER_PASS:
164 return "Render Pass";
165 case VK_OBJECT_TYPE_PIPELINE:
166 return "Pipeline";
167 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
168 return "Descriptor Set Layout";
169 case VK_OBJECT_TYPE_SAMPLER:
170 return "Sampler";
171 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
172 return "Descriptor Pool";
173 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
174 return "Descriptor Set";
175 case VK_OBJECT_TYPE_FRAMEBUFFER:
176 return "Framebuffer";
177 case VK_OBJECT_TYPE_COMMAND_POOL:
178 return "Command Pool";
179 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
180 return "Sampler YCbCr Conversion";
181 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
182 return "Descriptor Update Template";
183 case VK_OBJECT_TYPE_SURFACE_KHR:
184 return "Surface";
185 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
186 return "Swapchain";
187 case VK_OBJECT_TYPE_DISPLAY_KHR:
188 return "Display";
189 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
190 return "Display Mode";
191 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
192 return "Debug Report Callback";
193 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
194 return "Object Table";
195 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
196 return "Indirect Commands Layout";
197 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
198 return "Debug Utils Messenger";
199 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
200 return "Validation Cache";
201 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
202 return "Acceleration Structure";
203 default:
204 return "<Unrecognized>";
205 }
206}
207
208VKAPI_ATTR VkBool32 VKAPI_CALL
209DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
210 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
211 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
212 void *userData)
213{
214 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
215 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
216 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
217
218 // Check if we even care about this message.
219 if ((messageSeverity & kSeveritiesToLog) == 0)
220 {
221 return VK_FALSE;
222 }
223
224 // See if it's an issue we are aware of and don't want to be spammed about.
225 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
226 {
227 return VK_FALSE;
228 }
229
230 std::ostringstream log;
231 log << "[ " << callbackData->pMessageIdName << " ] " << callbackData->pMessage << std::endl;
232
233 // Aesthetic value based on length of the function name, line number, etc.
234 constexpr size_t kStartIndent = 28;
235
236 // Output the debug marker hierarchy under which this error has occured.
237 size_t indent = kStartIndent;
238 if (callbackData->queueLabelCount > 0)
239 {
240 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
241 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
242 {
243 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
244 << std::endl;
245 }
246 }
247 if (callbackData->cmdBufLabelCount > 0)
248 {
249 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
250 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
251 {
252 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
253 << std::endl;
254 }
255 }
256 // Output the objects involved in this error message.
257 if (callbackData->objectCount > 0)
258 {
259 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
260 {
261 const char *objectName = callbackData->pObjects[i].pObjectName;
262 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
263 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
264 log << std::string(indent, ' ') << "Object: ";
265 if (objectHandle == 0)
266 {
267 log << "VK_NULL_HANDLE";
268 }
269 else
270 {
271 log << "0x" << std::hex << objectHandle << std::dec;
272 }
273 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
274 if (objectName)
275 {
276 log << " [" << objectName << "]";
277 }
278 log << std::endl;
279 }
280 }
281
282 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
283
284 if (isError)
285 {
286 ERR() << log.str();
287 }
288 else
289 {
290 WARN() << log.str();
291 }
292
293 return VK_FALSE;
294}
295
Yuly Novikov199f4292018-01-19 19:04:05 -0500296VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
297 VkDebugReportObjectTypeEXT objectType,
298 uint64_t object,
299 size_t location,
300 int32_t messageCode,
301 const char *layerPrefix,
302 const char *message,
303 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500304{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600305 if (IsIgnoredDebugMessage(message))
306 {
307 return VK_FALSE;
308 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500309 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
310 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500311 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500312#if !defined(NDEBUG)
313 // Abort the call in Debug builds.
314 return VK_TRUE;
315#endif
316 }
317 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
318 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500319 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500320 }
321 else
322 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500323 // Uncomment this if you want Vulkan spam.
324 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500325 }
326
327 return VK_FALSE;
328}
329
Yuly Novikov199f4292018-01-19 19:04:05 -0500330// If we're loading the validation layers, we could be running from any random directory.
331// Change to the executable directory so we can find the layers, then change back to the
332// previous directory to be safe we don't disrupt the application.
333class ScopedVkLoaderEnvironment : angle::NonCopyable
334{
335 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600336 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
337 : mEnableValidationLayers(enableValidationLayers),
338 mEnableMockICD(enableMockICD),
339 mChangedCWD(false),
340 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500341 {
342// Changing CWD and setting environment variables makes no sense on Android,
343// since this code is a part of Java application there.
344// Android Vulkan loader doesn't need this either.
345#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600346 if (enableMockICD)
347 {
348 // Override environment variable to use built Mock ICD
349 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
350 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
351 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
352 if (!mChangedICDPath)
353 {
354 ERR() << "Error setting Path for Mock/Null Driver.";
355 mEnableMockICD = false;
356 }
357 }
Jamie Madill46848422018-08-09 10:46:06 -0400358 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500359 {
360 const auto &cwd = angle::GetCWD();
361 if (!cwd.valid())
362 {
363 ERR() << "Error getting CWD for Vulkan layers init.";
364 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400365 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500366 }
367 else
368 {
369 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500370 std::string exeDir = angle::GetExecutableDirectory();
371 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500372 if (!mChangedCWD)
373 {
374 ERR() << "Error setting CWD for Vulkan layers init.";
375 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400376 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500377 }
378 }
379 }
380
381 // Override environment variable to use the ANGLE layers.
382 if (mEnableValidationLayers)
383 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700384 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500385 {
386 ERR() << "Error setting environment for Vulkan layers init.";
387 mEnableValidationLayers = false;
388 }
389 }
390#endif // !defined(ANGLE_PLATFORM_ANDROID)
391 }
392
393 ~ScopedVkLoaderEnvironment()
394 {
395 if (mChangedCWD)
396 {
397#if !defined(ANGLE_PLATFORM_ANDROID)
398 ASSERT(mPreviousCWD.valid());
399 angle::SetCWD(mPreviousCWD.value().c_str());
400#endif // !defined(ANGLE_PLATFORM_ANDROID)
401 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600402 if (mChangedICDPath)
403 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600404 if (mPreviousICDPath.value().empty())
405 {
406 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
407 }
408 else
409 {
410 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
411 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600412 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500413 }
414
Jamie Madillaaca96e2018-06-12 10:19:48 -0400415 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500416
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600417 bool canEnableMockICD() const { return mEnableMockICD; }
418
Yuly Novikov199f4292018-01-19 19:04:05 -0500419 private:
420 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600421 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500422 bool mChangedCWD;
423 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600424 bool mChangedICDPath;
425 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500426};
427
Jamie Madill21061022018-07-12 23:56:30 -0400428void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
429 bool preferMockICD,
430 VkPhysicalDevice *physicalDeviceOut,
431 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
432{
433 ASSERT(!physicalDevices.empty());
434 if (preferMockICD)
435 {
436 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
437 {
438 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
439 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
440 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
441 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
442 {
443 *physicalDeviceOut = physicalDevice;
444 return;
445 }
446 }
447 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
448 "physicalDevice instead.";
449 }
450
451 // Fall back to first device.
452 *physicalDeviceOut = physicalDevices[0];
453 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
454}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400455
456// Initially dumping the command graphs is disabled.
457constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700458
Jamie Madille09bd5d2016-11-29 16:20:35 -0500459} // anonymous namespace
460
Jamie Madill49ac74b2017-12-21 14:42:33 -0500461// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400462RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500463
Jamie Madillaaca96e2018-06-12 10:19:48 -0400464RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500465
466RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
467 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500468{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500469
470RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
471{
472 std::swap(commandPool, other.commandPool);
473 std::swap(fence, other.fence);
474 std::swap(serial, other.serial);
475 return *this;
476}
477
Jamie Madillbea35a62018-07-05 11:54:10 -0400478void RendererVk::CommandBatch::destroy(VkDevice device)
479{
480 commandPool.destroy(device);
481 fence.destroy(device);
482}
483
Jamie Madill9f2a8612017-11-30 12:43:09 -0500484// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500485RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400486 : mDisplay(nullptr),
487 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700488 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500489 mInstance(VK_NULL_HANDLE),
490 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400491 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500492 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500493 mDebugReportCallback(VK_NULL_HANDLE),
494 mPhysicalDevice(VK_NULL_HANDLE),
495 mQueue(VK_NULL_HANDLE),
496 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
497 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400498 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400499 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400500 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400501 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400502 mCommandGraph(kEnableCommandGraphDiagnostics),
503 mGpuEventsEnabled(false),
504 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
505 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500506{
507 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
508 mFormatProperties.fill(invalid);
509}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400510
Jamie Madillb980c562018-11-27 11:34:27 -0500511RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400512
513void RendererVk::onDestroy(vk::Context *context)
514{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500515 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500516 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500517 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400518 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500519 }
520
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100521 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500522
Jamie Madillc7918ce2018-06-13 13:25:31 -0400523 mPipelineLayoutCache.destroy(mDevice);
524 mDescriptorSetLayoutCache.destroy(mDevice);
525
Jamie Madill9f2a8612017-11-30 12:43:09 -0500526 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500527 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400528 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400529 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400530 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500531
Jamie Madill06ca6342018-07-12 15:56:53 -0400532 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500533
Jamie Madill5deea722017-02-16 10:44:46 -0500534 if (mCommandPool.valid())
535 {
536 mCommandPool.destroy(mDevice);
537 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500538
539 if (mDevice)
540 {
541 vkDestroyDevice(mDevice, nullptr);
542 mDevice = VK_NULL_HANDLE;
543 }
544
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500545 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500546 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500547 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
548 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
549
550 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
551 }
552 else if (mDebugReportCallback)
553 {
554 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
555 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500556 }
557
Jamie Madill4d0bf552016-12-28 15:45:24 -0500558 if (mInstance)
559 {
560 vkDestroyInstance(mInstance, nullptr);
561 mInstance = VK_NULL_HANDLE;
562 }
563
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600564 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500565 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500566}
567
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400568void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400569{
570 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400571
572 mCommandGraph.clear();
573 mLastSubmittedQueueSerial = mCurrentQueueSerial;
574 mCurrentQueueSerial = mQueueSerialFactory.generate();
575 freeAllInFlightResources();
576
577 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400578}
579
580bool RendererVk::isDeviceLost() const
581{
582 return mDeviceLost;
583}
584
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400585angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400586 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400587 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500588{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400589 mDisplay = display;
590 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600591 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
592 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500593 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400594 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500595
Jamie Madill0448ec82016-12-23 13:41:47 -0500596 // Gather global layer properties.
597 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400598 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500599
600 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
601 if (instanceLayerCount > 0)
602 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400603 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
604 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500605 }
606
Jamie Madille09bd5d2016-11-29 16:20:35 -0500607 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400608 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400609 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500610
611 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
612 if (instanceExtensionCount > 0)
613 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400614 ANGLE_VK_TRY(displayVk,
615 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
616 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500617 }
618
Yuly Novikov199f4292018-01-19 19:04:05 -0500619 const char *const *enabledLayerNames = nullptr;
620 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500621 if (mEnableValidationLayers)
622 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500623 bool layersRequested =
624 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
625 mEnableValidationLayers = GetAvailableValidationLayers(
626 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500627 }
628
Jamie Madille09bd5d2016-11-29 16:20:35 -0500629 std::vector<const char *> enabledInstanceExtensions;
630 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500631 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500632
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500633 bool enableDebugUtils =
634 mEnableValidationLayers &&
635 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
636 bool enableDebugReport =
637 mEnableValidationLayers && !enableDebugUtils &&
638 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
639
640 if (enableDebugUtils)
641 {
642 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
643 }
644 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500645 {
646 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
647 }
648
Jamie Madille09bd5d2016-11-29 16:20:35 -0500649 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400650 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400651 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500652
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400653 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500654 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500655 applicationInfo.pApplicationName = "ANGLE";
656 applicationInfo.applicationVersion = 1;
657 applicationInfo.pEngineName = "ANGLE";
658 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700659
660 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
661 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
662 if (!enumerateInstanceVersion)
663 {
664 applicationInfo.apiVersion = VK_API_VERSION_1_0;
665 }
666 else
667 {
668 uint32_t apiVersion = VK_API_VERSION_1_0;
669 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
670 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
671 {
672 // Note: will need to revisit this with Vulkan 1.2+.
673 applicationInfo.apiVersion = VK_API_VERSION_1_1;
674 }
675 else
676 {
677 applicationInfo.apiVersion = VK_API_VERSION_1_0;
678 }
679 }
Jamie Madill327ba852016-11-30 12:38:28 -0500680
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400681 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500682 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
683 instanceInfo.flags = 0;
684 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500685
Jamie Madille09bd5d2016-11-29 16:20:35 -0500686 // Enable requested layers and extensions.
687 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
688 instanceInfo.ppEnabledExtensionNames =
689 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500690 instanceInfo.enabledLayerCount = enabledLayerCount;
691 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500692
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400693 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500694
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500695 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500696 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500697 // Try to use the newer EXT_debug_utils if it exists.
698 InitDebugUtilsEXTFunctions(mInstance);
699
700 // Create the messenger callback.
701 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
702
703 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
704 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
705 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
706 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
707 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
708 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
709 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
710 messengerInfo.pUserData = this;
711
712 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
713 &mDebugUtilsMessenger));
714 }
715 else if (enableDebugReport)
716 {
717 // Fallback to EXT_debug_report.
718 InitDebugReportEXTFunctions(mInstance);
719
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400720 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500721
722 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500723 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500724 debugReportInfo.pfnCallback = &DebugReportCallback;
725 debugReportInfo.pUserData = this;
726
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500727 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
728 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500729 }
730
Jamie Madill4d0bf552016-12-28 15:45:24 -0500731 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400732 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
733 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500734
735 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700736 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400737 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
738 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400739 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700740 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500741
Jamie Madill30b5d842018-08-31 17:19:12 -0400742 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
743
Jamie Madill4d0bf552016-12-28 15:45:24 -0500744 // Ensure we can find a graphics queue family.
745 uint32_t queueCount = 0;
746 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
747
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400748 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500749
750 mQueueFamilyProperties.resize(queueCount);
751 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
752 mQueueFamilyProperties.data());
753
Jamie Madillb980c562018-11-27 11:34:27 -0500754 size_t graphicsQueueFamilyCount = false;
755 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500756 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500757 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
758 {
759 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500760 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500761 {
762 ASSERT(queueInfo.queueCount > 0);
763 graphicsQueueFamilyCount++;
764 if (firstGraphicsQueueFamily == 0)
765 {
766 firstGraphicsQueueFamily = familyIndex;
767 }
768 break;
769 }
770 }
771
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400772 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500773
774 // If only one queue family, go ahead and initialize the device. If there is more than one
775 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
776 if (graphicsQueueFamilyCount == 1)
777 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400778 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500779 }
780
Jamie Madill035fd6b2017-10-03 15:43:22 -0400781 // Store the physical device memory properties so we can find the right memory pools.
782 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500783
Jamie Madill06ca6342018-07-12 15:56:53 -0400784 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500785
Jamie Madill6a89d222017-11-02 11:59:51 -0400786 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500787 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400788
Jamie Madill7c985f52018-11-29 18:16:17 -0500789 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400790}
791
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400792angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500793{
794 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400795 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400796 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500797
798 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
799 if (deviceLayerCount > 0)
800 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400801 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
802 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500803 }
804
805 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400806 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
807 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500808
809 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
810 if (deviceExtensionCount > 0)
811 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400812 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
813 &deviceExtensionCount,
814 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500815 }
816
Yuly Novikov199f4292018-01-19 19:04:05 -0500817 const char *const *enabledLayerNames = nullptr;
818 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500819 if (mEnableValidationLayers)
820 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500821 mEnableValidationLayers = GetAvailableValidationLayers(
822 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500823 }
824
825 std::vector<const char *> enabledDeviceExtensions;
826 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
827
Ian Elliottbcb78902018-12-19 11:46:29 -0700828 initFeatures(deviceExtensionProps);
829 mFeaturesInitialized = true;
830
Luc Ferronbf6dc372018-06-28 15:24:19 -0400831 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700832 if ((getFeatures().flipViewportY) &&
833 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400834 {
835 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
836 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700837 if (getFeatures().supportsIncrementalPresent)
838 {
839 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
840 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400841
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400842 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500843
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400844 // Select additional features to be enabled
845 VkPhysicalDeviceFeatures enabledFeatures = {};
846 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500847 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400848
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400849 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500850
851 float zeroPriority = 0.0f;
852
853 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500854 queueCreateInfo.flags = 0;
855 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
856 queueCreateInfo.queueCount = 1;
857 queueCreateInfo.pQueuePriorities = &zeroPriority;
858
859 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400860 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500861
Jamie Madill50cf2be2018-06-15 09:46:57 -0400862 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400863 createInfo.flags = 0;
864 createInfo.queueCreateInfoCount = 1;
865 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500866 createInfo.enabledLayerCount = enabledLayerCount;
867 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500868 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
869 createInfo.ppEnabledExtensionNames =
870 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400871 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500872
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400873 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500874
875 mCurrentQueueFamilyIndex = queueFamilyIndex;
876
877 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
878
879 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400880 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500881 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
882 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
883 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500884
Yuly Novikov27780292018-11-09 11:19:49 -0500885 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400886
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400887 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500888 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500889
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400890 // Initialize the submission semaphore pool.
891 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
892
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400893#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
894 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
895 ASSERT(platform);
896
897 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
898 // platform discovery.
899 const unsigned char *gpuEventsEnabled =
900 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
901 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
902#endif
903
904 if (mGpuEventsEnabled)
905 {
906 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
907 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
908 vk::kDefaultTimestampQueryPoolSize));
909 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
910 }
911
Jamie Madill7c985f52018-11-29 18:16:17 -0500912 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500913}
914
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400915angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400916 VkSurfaceKHR surface,
917 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500918{
919 // We've already initialized a device, and can't re-create it unless it's never been used.
920 // TODO(jmadill): Handle the re-creation case if necessary.
921 if (mDevice != VK_NULL_HANDLE)
922 {
923 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
924
925 // Check if the current device supports present on this surface.
926 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400927 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400928 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500929 surface, &supportsPresent));
930
Jamie Madill6cad7732018-07-11 09:01:17 -0400931 if (supportsPresent == VK_TRUE)
932 {
933 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500934 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400935 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500936 }
937
938 // Find a graphics and present queue.
939 Optional<uint32_t> newPresentQueue;
940 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500941 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500942 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
943 {
944 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500945 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500946 {
947 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400948 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
949 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500950
951 if (supportsPresent == VK_TRUE)
952 {
953 newPresentQueue = queueIndex;
954 break;
955 }
956 }
957 }
958
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400959 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
960 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500961
Jamie Madill6cad7732018-07-11 09:01:17 -0400962 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500963 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500964}
965
966std::string RendererVk::getVendorString() const
967{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300968 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500969}
970
Jamie Madille09bd5d2016-11-29 16:20:35 -0500971std::string RendererVk::getRendererDescription() const
972{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500973 std::stringstream strstr;
974
975 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
976
977 strstr << "Vulkan ";
978 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
979 strstr << VK_VERSION_MINOR(apiVersion) << ".";
980 strstr << VK_VERSION_PATCH(apiVersion);
981
Olli Etuahoc6a06182018-04-13 14:11:46 +0300982 strstr << "(";
983
984 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
985 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
986 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
987 // driver detection.
988 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
989 {
990 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
991 }
992
Geoff Langa7af56b2018-12-14 14:20:28 -0500993 strstr << mPhysicalDeviceProperties.deviceName;
994 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
995
996 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500997
998 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500999}
1000
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001001gl::Version RendererVk::getMaxSupportedESVersion() const
1002{
1003 // Declare GLES2 support if necessary features for GLES3 are missing
1004 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
1005
1006 if (!necessaryFeaturesForES3)
1007 {
1008 return gl::Version(2, 0);
1009 }
1010
1011 return gl::Version(3, 0);
1012}
1013
Ian Elliottbcb78902018-12-19 11:46:29 -07001014void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001015{
Jamie Madillb36a4812018-09-25 10:15:11 -04001016// Use OpenGL line rasterization rules by default.
1017// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1018#if defined(ANGLE_PLATFORM_ANDROID)
1019 mFeatures.basicGLLineRasterization = false;
1020#else
Jamie Madill12222072018-07-11 14:59:48 -04001021 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001022#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001023
Ian Elliott52f5da42018-12-21 09:02:09 -07001024 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1025 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001026 {
1027 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1028 // investigation. http://anglebug.com/2728
1029 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1030 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001031
1032#ifdef ANGLE_PLATFORM_WINDOWS
1033 // http://anglebug.com/2838
1034 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001035
1036 // http://anglebug.com/3055
1037 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001038#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001039
1040 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1041 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001042
1043 // Work around incorrect NVIDIA point size range clamping.
1044 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1045 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1046 {
1047 mFeatures.clampPointSize = true;
1048 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001049
1050#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001051 // Work around ineffective compute-graphics barriers on Nexus 5X.
1052 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1053 // http://anglebug.com/3019
1054 mFeatures.flushAfterVertexConversion =
1055 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001056#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001057
1058 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1059 {
1060 mFeatures.supportsIncrementalPresent = true;
1061 }
Jamie Madill12222072018-07-11 14:59:48 -04001062}
1063
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001064void RendererVk::initPipelineCacheVkKey()
1065{
1066 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1067 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1068 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1069 // there is no '\0' in the result.
1070 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1071 {
1072 hashStream << std::hex << c;
1073 }
1074 // Add the vendor and device id too for good measure.
1075 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1076 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1077
1078 const std::string &hashString = hashStream.str();
1079 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1080 hashString.length(), mPipelineCacheVkBlobKey.data());
1081}
1082
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001083angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001084{
1085 initPipelineCacheVkKey();
1086
1087 egl::BlobCache::Value initialData;
1088 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1089 mPipelineCacheVkBlobKey, &initialData);
1090
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001091 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001092
1093 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001094 pipelineCacheCreateInfo.flags = 0;
1095 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1096 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1097
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001098 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001099 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001100}
1101
Jamie Madillacccc6c2016-05-03 17:22:10 -04001102void RendererVk::ensureCapsInitialized() const
1103{
1104 if (!mCapsInitialized)
1105 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001106 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1107 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1108 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001109 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001110 mCapsInitialized = true;
1111 }
1112}
1113
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001114void RendererVk::getSubmitWaitSemaphores(
1115 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001116 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1117 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001118{
1119 if (mSubmitLastSignaledSemaphore.getSemaphore())
1120 {
1121 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001122 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001123
1124 // Return the semaphore to the pool (which will remain valid and unused until the
1125 // queue it's about to be waited on has finished execution).
1126 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1127 }
1128
1129 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1130 {
1131 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001132 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1133
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001134 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1135 }
1136 mSubmitWaitSemaphores.clear();
1137}
1138
Jamie Madillacccc6c2016-05-03 17:22:10 -04001139const gl::Caps &RendererVk::getNativeCaps() const
1140{
1141 ensureCapsInitialized();
1142 return mNativeCaps;
1143}
1144
1145const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1146{
1147 ensureCapsInitialized();
1148 return mNativeTextureCaps;
1149}
1150
1151const gl::Extensions &RendererVk::getNativeExtensions() const
1152{
1153 ensureCapsInitialized();
1154 return mNativeExtensions;
1155}
1156
1157const gl::Limitations &RendererVk::getNativeLimitations() const
1158{
1159 ensureCapsInitialized();
1160 return mNativeLimitations;
1161}
1162
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001163uint32_t RendererVk::getMaxActiveTextures()
1164{
1165 // TODO(lucferron): expose this limitation to GL in Context Caps
1166 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1167 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1168}
1169
Jamie Madill49ac74b2017-12-21 14:42:33 -05001170const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001171{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001172 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001173}
1174
Jamie Madill21061022018-07-12 23:56:30 -04001175angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001176{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001177 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001178 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001179 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1180
Luc Ferron1617e692018-07-11 11:08:19 -04001181 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1182 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001183
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001184 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001185 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1186 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001187
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001188 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001189 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001190 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1191 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001192 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001193 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001194 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001195 submitInfo.signalSemaphoreCount = 0;
1196 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001197
Jamie Madill21061022018-07-12 23:56:30 -04001198 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001199 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001200
Jamie Madill4c26fc22017-02-24 11:04:10 -05001201 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001202 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001203 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001204
1205 if (mGpuEventsEnabled)
1206 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001207 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001208 while (mInFlightGpuEventQueries.size() > 0)
1209 {
1210 ANGLE_TRY(checkCompletedGpuEvents(context));
1211 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001212 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1213 // synchronization if there is no event to be adjusted (happens when finish() gets called
1214 // multiple times towards the end of the application).
1215 if (mGpuEvents.size() > 0)
1216 {
1217 ANGLE_TRY(synchronizeCpuGpuTime(context));
1218 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001219 }
1220
Jamie Madill7c985f52018-11-29 18:16:17 -05001221 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001222}
1223
Jamie Madill0c0dc342017-03-24 14:18:51 -04001224void RendererVk::freeAllInFlightResources()
1225{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001226 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001227 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001228 // On device loss we need to wait for fence to be signaled before destroying it
1229 if (mDeviceLost)
1230 {
1231 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1232 // If wait times out, it is probably not possible to recover from lost device
1233 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1234 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001235 batch.fence.destroy(mDevice);
1236 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001237 }
1238 mInFlightCommands.clear();
1239
1240 for (auto &garbage : mGarbage)
1241 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001242 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001243 }
1244 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001245
1246 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001247}
1248
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001249angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001250{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001251 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001252
Jamie Madill49ac74b2017-12-21 14:42:33 -05001253 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001254 {
Yuly Novikov27780292018-11-09 11:19:49 -05001255 VkResult result = batch.fence.getStatus(mDevice);
1256 if (result == VK_NOT_READY)
1257 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001258 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001259 }
1260 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001261
Jamie Madill49ac74b2017-12-21 14:42:33 -05001262 ASSERT(batch.serial > mLastCompletedQueueSerial);
1263 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001264
Jamie Madill49ac74b2017-12-21 14:42:33 -05001265 batch.fence.destroy(mDevice);
1266 batch.commandPool.destroy(mDevice);
1267 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001268 }
1269
Jamie Madill49ac74b2017-12-21 14:42:33 -05001270 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001271
1272 size_t freeIndex = 0;
1273 for (; freeIndex < mGarbage.size(); ++freeIndex)
1274 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001275 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001276 break;
1277 }
1278
1279 // Remove the entries from the garbage list - they should be ready to go.
1280 if (freeIndex > 0)
1281 {
1282 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001283 }
1284
Jamie Madill7c985f52018-11-29 18:16:17 -05001285 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001286}
1287
Jamie Madill21061022018-07-12 23:56:30 -04001288angle::Result RendererVk::submitFrame(vk::Context *context,
1289 const VkSubmitInfo &submitInfo,
1290 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001291{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001292 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001293 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001294 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1295 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001296
Jamie Madillbea35a62018-07-05 11:54:10 -04001297 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1298 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001299 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001300
Jamie Madill21061022018-07-12 23:56:30 -04001301 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001302
1303 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001304 batch.commandPool = std::move(mCommandPool);
1305 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001306
Jamie Madillbea35a62018-07-05 11:54:10 -04001307 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001308
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001309 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1310 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001311 // so the limit is larger than the expected number of images. The
1312 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001313 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001314
1315 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001316 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001317 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001318 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001319
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001320 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001321
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001322 if (mGpuEventsEnabled)
1323 {
1324 ANGLE_TRY(checkCompletedGpuEvents(context));
1325 }
1326
Jamie Madill49ac74b2017-12-21 14:42:33 -05001327 // Simply null out the command buffer here - it was allocated using the command pool.
1328 commandBuffer.releaseHandle();
1329
1330 // Reallocate the command pool for next frame.
1331 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001332 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001333 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001334 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001335 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001336
Yuly Novikov27780292018-11-09 11:19:49 -05001337 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001338 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001339}
1340
Jamie Madillaaca96e2018-06-12 10:19:48 -04001341bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001342{
1343 return serial > mLastCompletedQueueSerial;
1344}
1345
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001346angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1347{
1348 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1349 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001350 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001351 }
1352
1353 // Find the first batch with serial equal to or bigger than given serial (note that
1354 // the batch serials are unique, otherwise upper-bound would have been necessary).
1355 size_t batchIndex = mInFlightCommands.size() - 1;
1356 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1357 {
1358 if (mInFlightCommands[i].serial >= serial)
1359 {
1360 batchIndex = i;
1361 break;
1362 }
1363 }
1364 const CommandBatch &batch = mInFlightCommands[batchIndex];
1365
1366 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001367 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001368
1369 // Clean up finished batches.
1370 return checkCompletedCommands(context);
1371}
1372
Jamie Madill21061022018-07-12 23:56:30 -04001373angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1374 const vk::RenderPassDesc &desc,
1375 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001376{
Jamie Madill21061022018-07-12 23:56:30 -04001377 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001378 renderPassOut);
1379}
1380
Jamie Madill21061022018-07-12 23:56:30 -04001381angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1382 const vk::RenderPassDesc &desc,
1383 const vk::AttachmentOpsArray &ops,
1384 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001385{
Jamie Madill21061022018-07-12 23:56:30 -04001386 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001387 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001388}
1389
Jamie Madilla5e06072018-05-18 14:36:05 -04001390vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001391{
Jamie Madilla5e06072018-05-18 14:36:05 -04001392 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001393}
1394
Jamie Madill21061022018-07-12 23:56:30 -04001395angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001396{
Jamie Madill21061022018-07-12 23:56:30 -04001397 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001398 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001399}
1400
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001401angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001402{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001403 if (mCommandGraph.empty())
1404 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001405 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001406 }
1407
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001408 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1409
Jamie Madillbea35a62018-07-05 11:54:10 -04001410 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1411 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001412
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001413 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001414 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1415 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001416
1417 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1418 // will be waited on.
1419 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001420
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001421 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001422 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001423 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1424 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001425 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001426 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001427 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001428 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001429 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001430
Jamie Madill21061022018-07-12 23:56:30 -04001431 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001432
Jamie Madill7c985f52018-11-29 18:16:17 -05001433 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001434}
1435
Jamie Madill78feddc2018-04-27 11:45:05 -04001436Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001437{
Jamie Madill78feddc2018-04-27 11:45:05 -04001438 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001439}
1440
Jamie Madill21061022018-07-12 23:56:30 -04001441angle::Result RendererVk::getDescriptorSetLayout(
1442 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001443 const vk::DescriptorSetLayoutDesc &desc,
1444 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1445{
Jamie Madill21061022018-07-12 23:56:30 -04001446 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001447}
1448
Jamie Madill21061022018-07-12 23:56:30 -04001449angle::Result RendererVk::getPipelineLayout(
1450 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001451 const vk::PipelineLayoutDesc &desc,
1452 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1453 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1454{
Jamie Madill21061022018-07-12 23:56:30 -04001455 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001456 pipelineLayoutOut);
1457}
1458
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001459angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1460{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001461 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001462
1463 if (--mPipelineCacheVkUpdateTimeout > 0)
1464 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001465 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001466 }
1467
1468 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1469
1470 // Get the size of the cache.
1471 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001472 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001473 if (result != VK_INCOMPLETE)
1474 {
1475 ANGLE_VK_TRY(displayVk, result);
1476 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001477
1478 angle::MemoryBuffer *pipelineCacheData = nullptr;
1479 ANGLE_VK_CHECK_ALLOC(displayVk,
1480 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1481
1482 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001483 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001484 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1485 // was determined just above), so receiving it hints at an implementation bug we would want
1486 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001487 ASSERT(result != VK_INCOMPLETE);
1488 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001489
1490 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1491 // the buffer to avoid leaking garbage memory.
1492 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1493 if (pipelineCacheSize < originalPipelineCacheSize)
1494 {
1495 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1496 originalPipelineCacheSize - pipelineCacheSize);
1497 }
1498
1499 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1500
Jamie Madill7c985f52018-11-29 18:16:17 -05001501 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001502}
1503
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001504angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1505 const vk::Semaphore **outSemaphore)
1506{
1507 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1508
1509 vk::SemaphoreHelper semaphore;
1510 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1511
1512 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1513 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1514
Jamie Madill7c985f52018-11-29 18:16:17 -05001515 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001516}
1517
1518const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1519{
1520 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1521
1522 // Return the semaphore to the pool (which will remain valid and unused until the
1523 // queue it's about to be waited on has finished execution). The caller is about
1524 // to wait on it.
1525 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1526
1527 return semaphore;
1528}
1529
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001530angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1531{
1532 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1533 // that seems impossible, so instead, we are going to make a small submission with just a
1534 // timestamp query. First, the disjoint timer query extension says:
1535 //
1536 // > This will return the GL time after all previous commands have reached the GL server but
1537 // have not yet necessarily executed.
1538 //
1539 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1540 // The wording allows us to make a submission to get the timestamp without performing a flush.
1541 //
1542 // Second:
1543 //
1544 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1545 // object target, applications can measure the latency between when commands reach the GL server
1546 // and when they are realized in the framebuffer.
1547 //
1548 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1549 // GPU bubble. This function directly generates a command buffer and submits it instead of
1550 // using the other member functions. This is to avoid changing any state, such as the queue
1551 // serial.
1552
1553 // Create a query used to receive the GPU timestamp
1554 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1555 vk::QueryHelper timestampQuery;
1556 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1557 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1558
1559 // Record the command buffer
1560 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1561 vk::CommandBuffer &commandBuffer = commandBatch.get();
1562
1563 VkCommandBufferAllocateInfo commandBufferInfo = {};
1564 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1565 commandBufferInfo.commandPool = mCommandPool.getHandle();
1566 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1567 commandBufferInfo.commandBufferCount = 1;
1568
Yuly Novikov27780292018-11-09 11:19:49 -05001569 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001570
1571 VkCommandBufferBeginInfo beginInfo = {};
1572 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1573 beginInfo.flags = 0;
1574 beginInfo.pInheritanceInfo = nullptr;
1575
Yuly Novikov27780292018-11-09 11:19:49 -05001576 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001577
1578 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1579 timestampQuery.getQuery(), 1);
1580 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1581 timestampQuery.getQueryPool()->getHandle(),
1582 timestampQuery.getQuery());
1583
Yuly Novikov27780292018-11-09 11:19:49 -05001584 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001585
1586 // Create fence for the submission
1587 VkFenceCreateInfo fenceInfo = {};
1588 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1589 fenceInfo.flags = 0;
1590
1591 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001592 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001593
1594 // Submit the command buffer
1595 VkSubmitInfo submitInfo = {};
1596 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1597 submitInfo.waitSemaphoreCount = 0;
1598 submitInfo.pWaitSemaphores = nullptr;
1599 submitInfo.pWaitDstStageMask = nullptr;
1600 submitInfo.commandBufferCount = 1;
1601 submitInfo.pCommandBuffers = commandBuffer.ptr();
1602 submitInfo.signalSemaphoreCount = 0;
1603 submitInfo.pSignalSemaphores = nullptr;
1604
1605 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1606
1607 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1608 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001609 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001610
1611 // Get the query results
1612 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1613
Yuly Novikov27780292018-11-09 11:19:49 -05001614 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1615 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1616 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001617
1618 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1619
Jamie Madill7c985f52018-11-29 18:16:17 -05001620 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001621}
1622
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001623// These functions look at the mandatory format for support, and fallback to querying the device (if
1624// necessary) to test the availability of the bits.
1625bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1626 const VkFormatFeatureFlags featureBits)
1627{
1628 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1629}
1630
1631bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1632 const VkFormatFeatureFlags featureBits)
1633{
1634 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1635}
1636
1637bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1638{
1639 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1640}
1641
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001642angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1643{
1644 ASSERT(mGpuEventsEnabled);
1645
1646 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1647 ASSERT(platform);
1648
1649 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1650 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1651 //
1652 // CPU GPU
1653 //
1654 // Record command buffer
1655 // with timestamp query
1656 //
1657 // Submit command buffer
1658 //
1659 // Post-submission work Begin execution
1660 //
1661 // ???? Write timstamp Tgpu
1662 //
1663 // ???? End execution
1664 //
1665 // ???? Return query results
1666 //
1667 // ????
1668 //
1669 // Get query results
1670 //
1671 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1672 // finished post-submission work while the GPU is executing in parallel. With no further work,
1673 // querying CPU timestamps before submission and after getting query results give the bounds to
1674 // Tgpu, which could be quite large.
1675 //
1676 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1677 // reduce this range. This function implements the following procedure:
1678 //
1679 // CPU GPU
1680 //
1681 // Record command buffer
1682 // with timestamp query
1683 //
1684 // Submit command buffer
1685 //
1686 // Post-submission work Begin execution
1687 //
1688 // ???? Set Event GPUReady
1689 //
1690 // Wait on Event GPUReady Wait on Event CPUReady
1691 //
1692 // Get CPU Time Ts Wait on Event CPUReady
1693 //
1694 // Set Event CPUReady Wait on Event CPUReady
1695 //
1696 // Get CPU Time Tcpu Get GPU Time Tgpu
1697 //
1698 // Wait on Event GPUDone Set Event GPUDone
1699 //
1700 // Get CPU Time Te End Execution
1701 //
1702 // Idle Return query results
1703 //
1704 // Get query results
1705 //
1706 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1707 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1708 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1709 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1710 // calibration.
1711 //
1712 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1713
1714 // Make sure nothing is running
1715 ASSERT(mCommandGraph.empty());
1716
1717 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1718
1719 // Create a query used to receive the GPU timestamp
1720 vk::QueryHelper timestampQuery;
1721 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1722
1723 // Create the three events
1724 VkEventCreateInfo eventCreateInfo = {};
1725 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1726 eventCreateInfo.flags = 0;
1727
1728 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001729 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1730 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1731 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001732
1733 constexpr uint32_t kRetries = 10;
1734
1735 // Time suffixes used are S for seconds and Cycles for cycles
1736 double tightestRangeS = 1e6f;
1737 double TcpuS = 0;
1738 uint64_t TgpuCycles = 0;
1739 for (uint32_t i = 0; i < kRetries; ++i)
1740 {
1741 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001742 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1743 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1744 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001745
1746 // Record the command buffer
1747 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1748 vk::CommandBuffer &commandBuffer = commandBatch.get();
1749
1750 VkCommandBufferAllocateInfo commandBufferInfo = {};
1751 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1752 commandBufferInfo.commandPool = mCommandPool.getHandle();
1753 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1754 commandBufferInfo.commandBufferCount = 1;
1755
Yuly Novikov27780292018-11-09 11:19:49 -05001756 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001757
1758 VkCommandBufferBeginInfo beginInfo = {};
1759 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1760 beginInfo.flags = 0;
1761 beginInfo.pInheritanceInfo = nullptr;
1762
Yuly Novikov27780292018-11-09 11:19:49 -05001763 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001764
1765 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1766 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1767 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1768 nullptr);
1769
1770 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1771 timestampQuery.getQuery(), 1);
1772 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1773 timestampQuery.getQueryPool()->getHandle(),
1774 timestampQuery.getQuery());
1775
1776 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1777
Yuly Novikov27780292018-11-09 11:19:49 -05001778 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001779
1780 // Submit the command buffer
1781 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1782 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1783 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1784
1785 VkSubmitInfo submitInfo = {};
1786 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1787 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1788 submitInfo.pWaitSemaphores = waitSemaphores.data();
1789 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1790 submitInfo.commandBufferCount = 1;
1791 submitInfo.pCommandBuffers = commandBuffer.ptr();
1792 submitInfo.signalSemaphoreCount = 0;
1793 submitInfo.pSignalSemaphores = nullptr;
1794
1795 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1796
1797 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001798 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001799 do
1800 {
Yuly Novikov27780292018-11-09 11:19:49 -05001801 result = gpuReady.get().getStatus(mDevice);
1802 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1803 {
1804 ANGLE_VK_TRY(context, result);
1805 }
1806 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001807
1808 double TsS = platform->monotonicallyIncreasingTime(platform);
1809
1810 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001811 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001812 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1813
1814 // Wait for GPU to be done. Another short busy wait.
1815 do
1816 {
Yuly Novikov27780292018-11-09 11:19:49 -05001817 result = gpuDone.get().getStatus(mDevice);
1818 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1819 {
1820 ANGLE_VK_TRY(context, result);
1821 }
1822 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001823
1824 double TeS = platform->monotonicallyIncreasingTime(platform);
1825
1826 // Get the query results
1827 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1828
1829 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1830
1831 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001832 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1833 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1834 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001835
1836 // Use the first timestamp queried as origin.
1837 if (mGpuEventTimestampOrigin == 0)
1838 {
1839 mGpuEventTimestampOrigin = gpuTimestampCycles;
1840 }
1841
1842 // Take these CPU and GPU timestamps if there is better confidence.
1843 double confidenceRangeS = TeS - TsS;
1844 if (confidenceRangeS < tightestRangeS)
1845 {
1846 tightestRangeS = confidenceRangeS;
1847 TcpuS = cpuTimestampS;
1848 TgpuCycles = gpuTimestampCycles;
1849 }
1850 }
1851
1852 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1853
1854 // timestampPeriod gives nanoseconds/cycle.
1855 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1856 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1857 1'000'000'000.0;
1858
1859 flushGpuEvents(TgpuS, TcpuS);
1860
1861 mGpuClockSync.gpuTimestampS = TgpuS;
1862 mGpuClockSync.cpuTimestampS = TcpuS;
1863
Jamie Madill7c985f52018-11-29 18:16:17 -05001864 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001865}
1866
1867angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1868 vk::CommandBuffer *commandBuffer,
1869 char phase,
1870 const char *name)
1871{
1872 ASSERT(mGpuEventsEnabled);
1873
1874 GpuEventQuery event;
1875
1876 event.name = name;
1877 event.phase = phase;
1878 event.serial = mCurrentQueueSerial;
1879
1880 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1881
1882 commandBuffer->resetQueryPool(
1883 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1884 commandBuffer->writeTimestamp(
1885 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1886 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1887
1888 mInFlightGpuEventQueries.push_back(std::move(event));
1889
Jamie Madill7c985f52018-11-29 18:16:17 -05001890 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001891}
1892
1893angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1894{
1895 ASSERT(mGpuEventsEnabled);
1896
1897 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1898 ASSERT(platform);
1899
1900 int finishedCount = 0;
1901
1902 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1903 {
1904 // Only check the timestamp query if the submission has finished.
1905 if (eventQuery.serial > mLastCompletedQueueSerial)
1906 {
1907 break;
1908 }
1909
1910 // See if the results are available.
1911 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001912 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1913 ->getResults(mDevice, eventQuery.queryIndex, 1,
1914 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1915 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1916 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001917 {
1918 break;
1919 }
Yuly Novikov27780292018-11-09 11:19:49 -05001920 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001921
1922 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1923
1924 GpuEvent event;
1925 event.gpuTimestampCycles = gpuTimestampCycles;
1926 event.name = eventQuery.name;
1927 event.phase = eventQuery.phase;
1928
1929 mGpuEvents.emplace_back(event);
1930
1931 ++finishedCount;
1932 }
1933
1934 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1935 mInFlightGpuEventQueries.begin() + finishedCount);
1936
Jamie Madill7c985f52018-11-29 18:16:17 -05001937 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001938}
1939
1940void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1941{
1942 if (mGpuEvents.size() == 0)
1943 {
1944 return;
1945 }
1946
1947 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1948 ASSERT(platform);
1949
1950 // Find the slope of the clock drift for adjustment
1951 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1952 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1953 double gpuSyncDriftSlope = 0;
1954
1955 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1956 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1957
1958 // No gpu trace events should have been generated before the clock sync, so if there is no
1959 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1960 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1961 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1962
1963 gpuSyncDriftSlope =
1964 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1965
1966 for (const GpuEvent &event : mGpuEvents)
1967 {
1968 double gpuTimestampS =
1969 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1970 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1971
1972 // Account for clock drift.
1973 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1974
1975 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1976 // for.
1977 static long long eventId = 1;
1978 static const unsigned char *categoryEnabled =
1979 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1980 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1981 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1982 }
1983
1984 mGpuEvents.clear();
1985}
1986
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001987template <VkFormatFeatureFlags VkFormatProperties::*features>
1988bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1989{
1990 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
1991 VkFormatProperties &deviceProperties = mFormatProperties[format];
1992
1993 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
1994 {
1995 // If we don't have the actual device features, see if the requested features are mandatory.
1996 // If so, there's no need to query the device.
1997 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
1998 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
1999 {
2000 return true;
2001 }
2002
2003 // Otherwise query the format features and cache it.
2004 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2005 }
2006
2007 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2008}
2009
Jamie Madillaaca96e2018-06-12 10:19:48 -04002010uint32_t GetUniformBufferDescriptorCount()
2011{
2012 return kUniformBufferDescriptorsPerDescriptorSet;
2013}
2014
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002015} // namespace rx