blob: f7467421af0356e266cdb7901ea99f5d1a3e3185 [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"
Jamie Madilla66779f2017-01-06 10:43:44 -050018#include "common/system_utils.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040019#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050020#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050021#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050022#include "libANGLE/renderer/vulkan/CompilerVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040023#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050025#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050026#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050028#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050029#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040031
Shahbaz Youssefi61656022018-10-24 15:00:50 -040032#include "third_party/trace_event/trace_event.h"
33
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070034// Consts
35namespace
36{
Jamie Madill7c985f52018-11-29 18:16:17 -050037const uint32_t kMockVendorID = 0xba5eba11;
38const uint32_t kMockDeviceID = 0xf005ba11;
39constexpr char kMockDeviceName[] = "Vulkan Mock Device";
40constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050041constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070042} // anonymous namespace
43
Jamie Madill9e54b5a2016-05-25 12:57:39 -040044namespace rx
45{
46
Jamie Madille09bd5d2016-11-29 16:20:35 -050047namespace
48{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040049// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
50// one for the vertex shader.
51constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040052// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
53static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040054// Wait a maximum of 10s. If that times out, we declare it a failure.
55static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050056
Omar El Sheikh26c61b22018-06-29 12:50:59 -060057bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
58{
59#if !defined(ANGLE_PLATFORM_ANDROID)
60 // Mock ICD does not currently run on Android
61 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
62 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
63 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
64#else
65 return false;
66#endif // !defined(ANGLE_PLATFORM_ANDROID)
67}
68
Jamie Madille09bd5d2016-11-29 16:20:35 -050069VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
70 const std::vector<const char *> &enabledExtensionNames)
71{
72 // Compile the extensions names into a set.
73 std::set<std::string> extensionNames;
74 for (const auto &extensionProp : extensionProps)
75 {
76 extensionNames.insert(extensionProp.extensionName);
77 }
78
Jamie Madillacf2f3a2017-11-21 19:22:44 -050079 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050080 {
81 if (extensionNames.count(extensionName) == 0)
82 {
83 return VK_ERROR_EXTENSION_NOT_PRESENT;
84 }
85 }
86
87 return VK_SUCCESS;
88}
89
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050090bool ExtensionFound(const char *extensionName,
91 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060092{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050093 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060094 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050095 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060096 {
97 return true;
98 }
99 }
100 return false;
101}
102
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500103// Array of Validation error/warning messages that will be ignored, should include bugID
104constexpr std::array<const char *, 1> kSkippedMessages = {
105 // http://anglebug.com/2796
106 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
107
108// Suppress validation errors that are known
109// return "true" if given code/prefix/message is known, else return "false"
110bool IsIgnoredDebugMessage(const char *message)
111{
112 for (const char *msg : kSkippedMessages)
113 {
114 if (strstr(message, msg) != nullptr)
115 {
116 return true;
117 }
118 }
119 return false;
120}
121
122const char *GetVkObjectTypeName(VkObjectType type)
123{
124 switch (type)
125 {
126 case VK_OBJECT_TYPE_UNKNOWN:
127 return "Unknown";
128 case VK_OBJECT_TYPE_INSTANCE:
129 return "Instance";
130 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
131 return "Physical Device";
132 case VK_OBJECT_TYPE_DEVICE:
133 return "Device";
134 case VK_OBJECT_TYPE_QUEUE:
135 return "Queue";
136 case VK_OBJECT_TYPE_SEMAPHORE:
137 return "Semaphore";
138 case VK_OBJECT_TYPE_COMMAND_BUFFER:
139 return "Command Buffer";
140 case VK_OBJECT_TYPE_FENCE:
141 return "Fence";
142 case VK_OBJECT_TYPE_DEVICE_MEMORY:
143 return "Device Memory";
144 case VK_OBJECT_TYPE_BUFFER:
145 return "Buffer";
146 case VK_OBJECT_TYPE_IMAGE:
147 return "Image";
148 case VK_OBJECT_TYPE_EVENT:
149 return "Event";
150 case VK_OBJECT_TYPE_QUERY_POOL:
151 return "Query Pool";
152 case VK_OBJECT_TYPE_BUFFER_VIEW:
153 return "Buffer View";
154 case VK_OBJECT_TYPE_IMAGE_VIEW:
155 return "Image View";
156 case VK_OBJECT_TYPE_SHADER_MODULE:
157 return "Shader Module";
158 case VK_OBJECT_TYPE_PIPELINE_CACHE:
159 return "Pipeline Cache";
160 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
161 return "Pipeline Layout";
162 case VK_OBJECT_TYPE_RENDER_PASS:
163 return "Render Pass";
164 case VK_OBJECT_TYPE_PIPELINE:
165 return "Pipeline";
166 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
167 return "Descriptor Set Layout";
168 case VK_OBJECT_TYPE_SAMPLER:
169 return "Sampler";
170 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
171 return "Descriptor Pool";
172 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
173 return "Descriptor Set";
174 case VK_OBJECT_TYPE_FRAMEBUFFER:
175 return "Framebuffer";
176 case VK_OBJECT_TYPE_COMMAND_POOL:
177 return "Command Pool";
178 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
179 return "Sampler YCbCr Conversion";
180 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
181 return "Descriptor Update Template";
182 case VK_OBJECT_TYPE_SURFACE_KHR:
183 return "Surface";
184 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
185 return "Swapchain";
186 case VK_OBJECT_TYPE_DISPLAY_KHR:
187 return "Display";
188 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
189 return "Display Mode";
190 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
191 return "Debug Report Callback";
192 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
193 return "Object Table";
194 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
195 return "Indirect Commands Layout";
196 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
197 return "Debug Utils Messenger";
198 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
199 return "Validation Cache";
200 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
201 return "Acceleration Structure";
202 default:
203 return "<Unrecognized>";
204 }
205}
206
207VKAPI_ATTR VkBool32 VKAPI_CALL
208DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
209 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
210 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
211 void *userData)
212{
213 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
214 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
215 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
216
217 // Check if we even care about this message.
218 if ((messageSeverity & kSeveritiesToLog) == 0)
219 {
220 return VK_FALSE;
221 }
222
223 // See if it's an issue we are aware of and don't want to be spammed about.
224 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
225 {
226 return VK_FALSE;
227 }
228
229 std::ostringstream log;
230 log << "[ " << callbackData->pMessageIdName << " ] " << callbackData->pMessage << std::endl;
231
232 // Aesthetic value based on length of the function name, line number, etc.
233 constexpr size_t kStartIndent = 28;
234
235 // Output the debug marker hierarchy under which this error has occured.
236 size_t indent = kStartIndent;
237 if (callbackData->queueLabelCount > 0)
238 {
239 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
240 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
241 {
242 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
243 << std::endl;
244 }
245 }
246 if (callbackData->cmdBufLabelCount > 0)
247 {
248 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
249 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
250 {
251 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
252 << std::endl;
253 }
254 }
255 // Output the objects involved in this error message.
256 if (callbackData->objectCount > 0)
257 {
258 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
259 {
260 const char *objectName = callbackData->pObjects[i].pObjectName;
261 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
262 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
263 log << std::string(indent, ' ') << "Object: ";
264 if (objectHandle == 0)
265 {
266 log << "VK_NULL_HANDLE";
267 }
268 else
269 {
270 log << "0x" << std::hex << objectHandle << std::dec;
271 }
272 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
273 if (objectName)
274 {
275 log << " [" << objectName << "]";
276 }
277 log << std::endl;
278 }
279 }
280
281 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
282
283 if (isError)
284 {
285 ERR() << log.str();
286 }
287 else
288 {
289 WARN() << log.str();
290 }
291
292 return VK_FALSE;
293}
294
Yuly Novikov199f4292018-01-19 19:04:05 -0500295VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
296 VkDebugReportObjectTypeEXT objectType,
297 uint64_t object,
298 size_t location,
299 int32_t messageCode,
300 const char *layerPrefix,
301 const char *message,
302 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500303{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600304 if (IsIgnoredDebugMessage(message))
305 {
306 return VK_FALSE;
307 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500308 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
309 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500310 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500311#if !defined(NDEBUG)
312 // Abort the call in Debug builds.
313 return VK_TRUE;
314#endif
315 }
316 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
317 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500318 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500319 }
320 else
321 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500322 // Uncomment this if you want Vulkan spam.
323 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500324 }
325
326 return VK_FALSE;
327}
328
Yuly Novikov199f4292018-01-19 19:04:05 -0500329// If we're loading the validation layers, we could be running from any random directory.
330// Change to the executable directory so we can find the layers, then change back to the
331// previous directory to be safe we don't disrupt the application.
332class ScopedVkLoaderEnvironment : angle::NonCopyable
333{
334 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600335 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
336 : mEnableValidationLayers(enableValidationLayers),
337 mEnableMockICD(enableMockICD),
338 mChangedCWD(false),
339 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500340 {
341// Changing CWD and setting environment variables makes no sense on Android,
342// since this code is a part of Java application there.
343// Android Vulkan loader doesn't need this either.
344#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600345 if (enableMockICD)
346 {
347 // Override environment variable to use built Mock ICD
348 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
349 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
350 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
351 if (!mChangedICDPath)
352 {
353 ERR() << "Error setting Path for Mock/Null Driver.";
354 mEnableMockICD = false;
355 }
356 }
Jamie Madill46848422018-08-09 10:46:06 -0400357 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500358 {
359 const auto &cwd = angle::GetCWD();
360 if (!cwd.valid())
361 {
362 ERR() << "Error getting CWD for Vulkan layers init.";
363 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400364 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500365 }
366 else
367 {
368 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500369 std::string exeDir = angle::GetExecutableDirectory();
370 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500371 if (!mChangedCWD)
372 {
373 ERR() << "Error setting CWD for Vulkan layers init.";
374 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400375 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500376 }
377 }
378 }
379
380 // Override environment variable to use the ANGLE layers.
381 if (mEnableValidationLayers)
382 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700383 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500384 {
385 ERR() << "Error setting environment for Vulkan layers init.";
386 mEnableValidationLayers = false;
387 }
388 }
389#endif // !defined(ANGLE_PLATFORM_ANDROID)
390 }
391
392 ~ScopedVkLoaderEnvironment()
393 {
394 if (mChangedCWD)
395 {
396#if !defined(ANGLE_PLATFORM_ANDROID)
397 ASSERT(mPreviousCWD.valid());
398 angle::SetCWD(mPreviousCWD.value().c_str());
399#endif // !defined(ANGLE_PLATFORM_ANDROID)
400 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600401 if (mChangedICDPath)
402 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600403 if (mPreviousICDPath.value().empty())
404 {
405 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
406 }
407 else
408 {
409 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
410 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600411 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500412 }
413
Jamie Madillaaca96e2018-06-12 10:19:48 -0400414 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500415
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600416 bool canEnableMockICD() const { return mEnableMockICD; }
417
Yuly Novikov199f4292018-01-19 19:04:05 -0500418 private:
419 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600420 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500421 bool mChangedCWD;
422 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600423 bool mChangedICDPath;
424 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500425};
426
Jamie Madill21061022018-07-12 23:56:30 -0400427void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
428 bool preferMockICD,
429 VkPhysicalDevice *physicalDeviceOut,
430 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
431{
432 ASSERT(!physicalDevices.empty());
433 if (preferMockICD)
434 {
435 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
436 {
437 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
438 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
439 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
440 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
441 {
442 *physicalDeviceOut = physicalDevice;
443 return;
444 }
445 }
446 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
447 "physicalDevice instead.";
448 }
449
450 // Fall back to first device.
451 *physicalDeviceOut = physicalDevices[0];
452 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
453}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400454
455// Initially dumping the command graphs is disabled.
456constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700457
Jamie Madille09bd5d2016-11-29 16:20:35 -0500458} // anonymous namespace
459
Jamie Madill49ac74b2017-12-21 14:42:33 -0500460// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400461RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500462
Jamie Madillaaca96e2018-06-12 10:19:48 -0400463RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500464
465RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
466 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500467{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500468
469RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
470{
471 std::swap(commandPool, other.commandPool);
472 std::swap(fence, other.fence);
473 std::swap(serial, other.serial);
474 return *this;
475}
476
Jamie Madillbea35a62018-07-05 11:54:10 -0400477void RendererVk::CommandBatch::destroy(VkDevice device)
478{
479 commandPool.destroy(device);
480 fence.destroy(device);
481}
482
Jamie Madill9f2a8612017-11-30 12:43:09 -0500483// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500484RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400485 : mDisplay(nullptr),
486 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700487 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500488 mInstance(VK_NULL_HANDLE),
489 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400490 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500491 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500492 mDebugReportCallback(VK_NULL_HANDLE),
493 mPhysicalDevice(VK_NULL_HANDLE),
494 mQueue(VK_NULL_HANDLE),
495 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
496 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400497 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400498 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400499 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400500 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400501 mCommandGraph(kEnableCommandGraphDiagnostics),
502 mGpuEventsEnabled(false),
503 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
504 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500505{
506 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
507 mFormatProperties.fill(invalid);
508}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400509
Jamie Madillb980c562018-11-27 11:34:27 -0500510RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400511
512void RendererVk::onDestroy(vk::Context *context)
513{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500514 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500515 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500516 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400517 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500518 }
519
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100520 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500521
Jamie Madillc7918ce2018-06-13 13:25:31 -0400522 mPipelineLayoutCache.destroy(mDevice);
523 mDescriptorSetLayoutCache.destroy(mDevice);
524
Jamie Madill9f2a8612017-11-30 12:43:09 -0500525 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500526 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400527 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400528 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400529 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500530
Jamie Madill06ca6342018-07-12 15:56:53 -0400531 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500532
Jamie Madill5deea722017-02-16 10:44:46 -0500533 if (mCommandPool.valid())
534 {
535 mCommandPool.destroy(mDevice);
536 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500537
538 if (mDevice)
539 {
540 vkDestroyDevice(mDevice, nullptr);
541 mDevice = VK_NULL_HANDLE;
542 }
543
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500544 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500545 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500546 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
547 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
548
549 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
550 }
551 else if (mDebugReportCallback)
552 {
553 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
554 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500555 }
556
Jamie Madill4d0bf552016-12-28 15:45:24 -0500557 if (mInstance)
558 {
559 vkDestroyInstance(mInstance, nullptr);
560 mInstance = VK_NULL_HANDLE;
561 }
562
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600563 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500564 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500565}
566
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400567void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400568{
569 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400570
571 mCommandGraph.clear();
572 mLastSubmittedQueueSerial = mCurrentQueueSerial;
573 mCurrentQueueSerial = mQueueSerialFactory.generate();
574 freeAllInFlightResources();
575
576 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400577}
578
579bool RendererVk::isDeviceLost() const
580{
581 return mDeviceLost;
582}
583
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400584angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400585 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400586 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500587{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400588 mDisplay = display;
589 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600590 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
591 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500592 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400593 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500594
Jamie Madill0448ec82016-12-23 13:41:47 -0500595 // Gather global layer properties.
596 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400597 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500598
599 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
600 if (instanceLayerCount > 0)
601 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400602 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
603 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500604 }
605
Jamie Madille09bd5d2016-11-29 16:20:35 -0500606 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400607 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400608 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500609
610 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
611 if (instanceExtensionCount > 0)
612 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400613 ANGLE_VK_TRY(displayVk,
614 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
615 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500616 }
617
Yuly Novikov199f4292018-01-19 19:04:05 -0500618 const char *const *enabledLayerNames = nullptr;
619 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500620 if (mEnableValidationLayers)
621 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500622 bool layersRequested =
623 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
624 mEnableValidationLayers = GetAvailableValidationLayers(
625 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500626 }
627
Jamie Madille09bd5d2016-11-29 16:20:35 -0500628 std::vector<const char *> enabledInstanceExtensions;
629 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500630 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500631
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500632 bool enableDebugUtils =
633 mEnableValidationLayers &&
634 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
635 bool enableDebugReport =
636 mEnableValidationLayers && !enableDebugUtils &&
637 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
638
639 if (enableDebugUtils)
640 {
641 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
642 }
643 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500644 {
645 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
646 }
647
Jamie Madille09bd5d2016-11-29 16:20:35 -0500648 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400649 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400650 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500651
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400652 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500653 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500654 applicationInfo.pApplicationName = "ANGLE";
655 applicationInfo.applicationVersion = 1;
656 applicationInfo.pEngineName = "ANGLE";
657 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700658
659 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
660 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
661 if (!enumerateInstanceVersion)
662 {
663 applicationInfo.apiVersion = VK_API_VERSION_1_0;
664 }
665 else
666 {
667 uint32_t apiVersion = VK_API_VERSION_1_0;
668 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
669 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
670 {
671 // Note: will need to revisit this with Vulkan 1.2+.
672 applicationInfo.apiVersion = VK_API_VERSION_1_1;
673 }
674 else
675 {
676 applicationInfo.apiVersion = VK_API_VERSION_1_0;
677 }
678 }
Jamie Madill327ba852016-11-30 12:38:28 -0500679
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400680 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500681 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
682 instanceInfo.flags = 0;
683 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500684
Jamie Madille09bd5d2016-11-29 16:20:35 -0500685 // Enable requested layers and extensions.
686 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
687 instanceInfo.ppEnabledExtensionNames =
688 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500689 instanceInfo.enabledLayerCount = enabledLayerCount;
690 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500691
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400692 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500693
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500694 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500695 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500696 // Try to use the newer EXT_debug_utils if it exists.
697 InitDebugUtilsEXTFunctions(mInstance);
698
699 // Create the messenger callback.
700 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
701
702 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
703 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
704 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
705 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
706 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
707 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
708 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
709 messengerInfo.pUserData = this;
710
711 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
712 &mDebugUtilsMessenger));
713 }
714 else if (enableDebugReport)
715 {
716 // Fallback to EXT_debug_report.
717 InitDebugReportEXTFunctions(mInstance);
718
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400719 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500720
721 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500722 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500723 debugReportInfo.pfnCallback = &DebugReportCallback;
724 debugReportInfo.pUserData = this;
725
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500726 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
727 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500728 }
729
Jamie Madill4d0bf552016-12-28 15:45:24 -0500730 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400731 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
732 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500733
734 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700735 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400736 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
737 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400738 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700739 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500740
Jamie Madill30b5d842018-08-31 17:19:12 -0400741 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
742
Jamie Madill4d0bf552016-12-28 15:45:24 -0500743 // Ensure we can find a graphics queue family.
744 uint32_t queueCount = 0;
745 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
746
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400747 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500748
749 mQueueFamilyProperties.resize(queueCount);
750 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
751 mQueueFamilyProperties.data());
752
Jamie Madillb980c562018-11-27 11:34:27 -0500753 size_t graphicsQueueFamilyCount = false;
754 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500755 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500756 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
757 {
758 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500759 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500760 {
761 ASSERT(queueInfo.queueCount > 0);
762 graphicsQueueFamilyCount++;
763 if (firstGraphicsQueueFamily == 0)
764 {
765 firstGraphicsQueueFamily = familyIndex;
766 }
767 break;
768 }
769 }
770
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400771 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500772
773 // If only one queue family, go ahead and initialize the device. If there is more than one
774 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
775 if (graphicsQueueFamilyCount == 1)
776 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400777 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500778 }
779
Jamie Madill035fd6b2017-10-03 15:43:22 -0400780 // Store the physical device memory properties so we can find the right memory pools.
781 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500782
Jamie Madill06ca6342018-07-12 15:56:53 -0400783 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500784
Jamie Madill6a89d222017-11-02 11:59:51 -0400785 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500786 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400787
Jamie Madill7c985f52018-11-29 18:16:17 -0500788 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400789}
790
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400791angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500792{
793 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400794 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400795 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500796
797 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
798 if (deviceLayerCount > 0)
799 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400800 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
801 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500802 }
803
804 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400805 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
806 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500807
808 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
809 if (deviceExtensionCount > 0)
810 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400811 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
812 &deviceExtensionCount,
813 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500814 }
815
Yuly Novikov199f4292018-01-19 19:04:05 -0500816 const char *const *enabledLayerNames = nullptr;
817 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500818 if (mEnableValidationLayers)
819 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500820 mEnableValidationLayers = GetAvailableValidationLayers(
821 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500822 }
823
824 std::vector<const char *> enabledDeviceExtensions;
825 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
826
Ian Elliottbcb78902018-12-19 11:46:29 -0700827 initFeatures(deviceExtensionProps);
828 mFeaturesInitialized = true;
829
Luc Ferronbf6dc372018-06-28 15:24:19 -0400830 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700831 if ((getFeatures().flipViewportY) &&
832 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400833 {
834 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
835 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700836 if (getFeatures().supportsIncrementalPresent)
837 {
838 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
839 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400840
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400841 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500842
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400843 // Select additional features to be enabled
844 VkPhysicalDeviceFeatures enabledFeatures = {};
845 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500846 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400847
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400848 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500849
850 float zeroPriority = 0.0f;
851
852 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500853 queueCreateInfo.flags = 0;
854 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
855 queueCreateInfo.queueCount = 1;
856 queueCreateInfo.pQueuePriorities = &zeroPriority;
857
858 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400859 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500860
Jamie Madill50cf2be2018-06-15 09:46:57 -0400861 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400862 createInfo.flags = 0;
863 createInfo.queueCreateInfoCount = 1;
864 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500865 createInfo.enabledLayerCount = enabledLayerCount;
866 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500867 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
868 createInfo.ppEnabledExtensionNames =
869 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400870 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500871
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400872 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873
874 mCurrentQueueFamilyIndex = queueFamilyIndex;
875
876 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
877
878 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400879 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500880 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
881 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
882 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500883
Yuly Novikov27780292018-11-09 11:19:49 -0500884 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400885
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400886 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500887 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500888
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400889 // Initialize the submission semaphore pool.
890 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
891
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400892#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
893 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
894 ASSERT(platform);
895
896 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
897 // platform discovery.
898 const unsigned char *gpuEventsEnabled =
899 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
900 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
901#endif
902
903 if (mGpuEventsEnabled)
904 {
905 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
906 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
907 vk::kDefaultTimestampQueryPoolSize));
908 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
909 }
910
Jamie Madill7c985f52018-11-29 18:16:17 -0500911 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500912}
913
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400914angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400915 VkSurfaceKHR surface,
916 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500917{
918 // We've already initialized a device, and can't re-create it unless it's never been used.
919 // TODO(jmadill): Handle the re-creation case if necessary.
920 if (mDevice != VK_NULL_HANDLE)
921 {
922 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
923
924 // Check if the current device supports present on this surface.
925 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400926 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400927 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500928 surface, &supportsPresent));
929
Jamie Madill6cad7732018-07-11 09:01:17 -0400930 if (supportsPresent == VK_TRUE)
931 {
932 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500933 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400934 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500935 }
936
937 // Find a graphics and present queue.
938 Optional<uint32_t> newPresentQueue;
939 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500940 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500941 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
942 {
943 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500944 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500945 {
946 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400947 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
948 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500949
950 if (supportsPresent == VK_TRUE)
951 {
952 newPresentQueue = queueIndex;
953 break;
954 }
955 }
956 }
957
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400958 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
959 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500960
Jamie Madill6cad7732018-07-11 09:01:17 -0400961 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500962 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500963}
964
965std::string RendererVk::getVendorString() const
966{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300967 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500968}
969
Jamie Madille09bd5d2016-11-29 16:20:35 -0500970std::string RendererVk::getRendererDescription() const
971{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500972 std::stringstream strstr;
973
974 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
975
976 strstr << "Vulkan ";
977 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
978 strstr << VK_VERSION_MINOR(apiVersion) << ".";
979 strstr << VK_VERSION_PATCH(apiVersion);
980
Olli Etuahoc6a06182018-04-13 14:11:46 +0300981 strstr << "(";
982
983 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
984 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
985 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
986 // driver detection.
987 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
988 {
989 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
990 }
991
Geoff Langa7af56b2018-12-14 14:20:28 -0500992 strstr << mPhysicalDeviceProperties.deviceName;
993 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
994
995 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500996
997 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500998}
999
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001000gl::Version RendererVk::getMaxSupportedESVersion() const
1001{
1002 // Declare GLES2 support if necessary features for GLES3 are missing
1003 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
1004
1005 if (!necessaryFeaturesForES3)
1006 {
1007 return gl::Version(2, 0);
1008 }
1009
1010 return gl::Version(3, 0);
1011}
1012
Ian Elliottbcb78902018-12-19 11:46:29 -07001013void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001014{
Jamie Madillb36a4812018-09-25 10:15:11 -04001015// Use OpenGL line rasterization rules by default.
1016// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1017#if defined(ANGLE_PLATFORM_ANDROID)
1018 mFeatures.basicGLLineRasterization = false;
1019#else
Jamie Madill12222072018-07-11 14:59:48 -04001020 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001021#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001022
Ian Elliott52f5da42018-12-21 09:02:09 -07001023 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1024 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001025 {
1026 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1027 // investigation. http://anglebug.com/2728
1028 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1029 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001030
1031#ifdef ANGLE_PLATFORM_WINDOWS
1032 // http://anglebug.com/2838
1033 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001034
1035 // http://anglebug.com/3055
1036 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001037#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001038
1039 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1040 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001041
1042 // Work around incorrect NVIDIA point size range clamping.
1043 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1044 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1045 {
1046 mFeatures.clampPointSize = true;
1047 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001048
1049#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001050 // Work around ineffective compute-graphics barriers on Nexus 5X.
1051 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1052 // http://anglebug.com/3019
1053 mFeatures.flushAfterVertexConversion =
1054 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001055#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001056
1057 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1058 {
1059 mFeatures.supportsIncrementalPresent = true;
1060 }
Jamie Madill12222072018-07-11 14:59:48 -04001061}
1062
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001063void RendererVk::initPipelineCacheVkKey()
1064{
1065 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1066 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1067 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1068 // there is no '\0' in the result.
1069 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1070 {
1071 hashStream << std::hex << c;
1072 }
1073 // Add the vendor and device id too for good measure.
1074 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1075 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1076
1077 const std::string &hashString = hashStream.str();
1078 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1079 hashString.length(), mPipelineCacheVkBlobKey.data());
1080}
1081
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001082angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001083{
1084 initPipelineCacheVkKey();
1085
1086 egl::BlobCache::Value initialData;
1087 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1088 mPipelineCacheVkBlobKey, &initialData);
1089
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001090 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001091
1092 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001093 pipelineCacheCreateInfo.flags = 0;
1094 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1095 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1096
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001097 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001098 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001099}
1100
Jamie Madillacccc6c2016-05-03 17:22:10 -04001101void RendererVk::ensureCapsInitialized() const
1102{
1103 if (!mCapsInitialized)
1104 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001105 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1106 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1107 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001108 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001109 mCapsInitialized = true;
1110 }
1111}
1112
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001113void RendererVk::getSubmitWaitSemaphores(
1114 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001115 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1116 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001117{
1118 if (mSubmitLastSignaledSemaphore.getSemaphore())
1119 {
1120 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001121 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001122
1123 // Return the semaphore to the pool (which will remain valid and unused until the
1124 // queue it's about to be waited on has finished execution).
1125 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1126 }
1127
1128 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1129 {
1130 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001131 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1132
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001133 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1134 }
1135 mSubmitWaitSemaphores.clear();
1136}
1137
Jamie Madillacccc6c2016-05-03 17:22:10 -04001138const gl::Caps &RendererVk::getNativeCaps() const
1139{
1140 ensureCapsInitialized();
1141 return mNativeCaps;
1142}
1143
1144const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1145{
1146 ensureCapsInitialized();
1147 return mNativeTextureCaps;
1148}
1149
1150const gl::Extensions &RendererVk::getNativeExtensions() const
1151{
1152 ensureCapsInitialized();
1153 return mNativeExtensions;
1154}
1155
1156const gl::Limitations &RendererVk::getNativeLimitations() const
1157{
1158 ensureCapsInitialized();
1159 return mNativeLimitations;
1160}
1161
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001162uint32_t RendererVk::getMaxActiveTextures()
1163{
1164 // TODO(lucferron): expose this limitation to GL in Context Caps
1165 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1166 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1167}
1168
Jamie Madill49ac74b2017-12-21 14:42:33 -05001169const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001170{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001171 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001172}
1173
Jamie Madill21061022018-07-12 23:56:30 -04001174angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001175{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001176 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001177 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001178 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1179
Luc Ferron1617e692018-07-11 11:08:19 -04001180 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1181 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001182
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001183 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001184 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1185 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001186
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001187 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001188 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001189 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1190 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001191 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001192 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001193 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001194 submitInfo.signalSemaphoreCount = 0;
1195 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001196
Jamie Madill21061022018-07-12 23:56:30 -04001197 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001198 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001199
Jamie Madill4c26fc22017-02-24 11:04:10 -05001200 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001201 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001202 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001203
1204 if (mGpuEventsEnabled)
1205 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001206 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001207 while (mInFlightGpuEventQueries.size() > 0)
1208 {
1209 ANGLE_TRY(checkCompletedGpuEvents(context));
1210 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001211 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1212 // synchronization if there is no event to be adjusted (happens when finish() gets called
1213 // multiple times towards the end of the application).
1214 if (mGpuEvents.size() > 0)
1215 {
1216 ANGLE_TRY(synchronizeCpuGpuTime(context));
1217 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001218 }
1219
Jamie Madill7c985f52018-11-29 18:16:17 -05001220 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001221}
1222
Jamie Madill0c0dc342017-03-24 14:18:51 -04001223void RendererVk::freeAllInFlightResources()
1224{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001225 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001226 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001227 // On device loss we need to wait for fence to be signaled before destroying it
1228 if (mDeviceLost)
1229 {
1230 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1231 // If wait times out, it is probably not possible to recover from lost device
1232 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1233 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001234 batch.fence.destroy(mDevice);
1235 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001236 }
1237 mInFlightCommands.clear();
1238
1239 for (auto &garbage : mGarbage)
1240 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001241 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001242 }
1243 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001244
1245 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001246}
1247
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001248angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001249{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001250 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001251
Jamie Madill49ac74b2017-12-21 14:42:33 -05001252 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001253 {
Yuly Novikov27780292018-11-09 11:19:49 -05001254 VkResult result = batch.fence.getStatus(mDevice);
1255 if (result == VK_NOT_READY)
1256 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001257 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001258 }
1259 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001260
Jamie Madill49ac74b2017-12-21 14:42:33 -05001261 ASSERT(batch.serial > mLastCompletedQueueSerial);
1262 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001263
Jamie Madill49ac74b2017-12-21 14:42:33 -05001264 batch.fence.destroy(mDevice);
1265 batch.commandPool.destroy(mDevice);
1266 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001267 }
1268
Jamie Madill49ac74b2017-12-21 14:42:33 -05001269 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001270
1271 size_t freeIndex = 0;
1272 for (; freeIndex < mGarbage.size(); ++freeIndex)
1273 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001274 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001275 break;
1276 }
1277
1278 // Remove the entries from the garbage list - they should be ready to go.
1279 if (freeIndex > 0)
1280 {
1281 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001282 }
1283
Jamie Madill7c985f52018-11-29 18:16:17 -05001284 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001285}
1286
Jamie Madill21061022018-07-12 23:56:30 -04001287angle::Result RendererVk::submitFrame(vk::Context *context,
1288 const VkSubmitInfo &submitInfo,
1289 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001290{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001291 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001292 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001293 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1294 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001295
Jamie Madillbea35a62018-07-05 11:54:10 -04001296 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1297 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001298 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001299
Jamie Madill21061022018-07-12 23:56:30 -04001300 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001301
1302 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001303 batch.commandPool = std::move(mCommandPool);
1304 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001305
Jamie Madillbea35a62018-07-05 11:54:10 -04001306 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001307
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001308 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1309 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001310 // so the limit is larger than the expected number of images. The
1311 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001312 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001313
1314 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001315 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001316 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001317 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001318
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001319 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001320
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001321 if (mGpuEventsEnabled)
1322 {
1323 ANGLE_TRY(checkCompletedGpuEvents(context));
1324 }
1325
Jamie Madill49ac74b2017-12-21 14:42:33 -05001326 // Simply null out the command buffer here - it was allocated using the command pool.
1327 commandBuffer.releaseHandle();
1328
1329 // Reallocate the command pool for next frame.
1330 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001331 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001332 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001333 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001334 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001335
Yuly Novikov27780292018-11-09 11:19:49 -05001336 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001337 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001338}
1339
Jamie Madillaaca96e2018-06-12 10:19:48 -04001340bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001341{
1342 return serial > mLastCompletedQueueSerial;
1343}
1344
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001345angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1346{
1347 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1348 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001349 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001350 }
1351
1352 // Find the first batch with serial equal to or bigger than given serial (note that
1353 // the batch serials are unique, otherwise upper-bound would have been necessary).
1354 size_t batchIndex = mInFlightCommands.size() - 1;
1355 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1356 {
1357 if (mInFlightCommands[i].serial >= serial)
1358 {
1359 batchIndex = i;
1360 break;
1361 }
1362 }
1363 const CommandBatch &batch = mInFlightCommands[batchIndex];
1364
1365 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001366 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001367
1368 // Clean up finished batches.
1369 return checkCompletedCommands(context);
1370}
1371
Jamie Madill21061022018-07-12 23:56:30 -04001372angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1373 const vk::RenderPassDesc &desc,
1374 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001375{
Jamie Madill21061022018-07-12 23:56:30 -04001376 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001377 renderPassOut);
1378}
1379
Jamie Madill21061022018-07-12 23:56:30 -04001380angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1381 const vk::RenderPassDesc &desc,
1382 const vk::AttachmentOpsArray &ops,
1383 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001384{
Jamie Madill21061022018-07-12 23:56:30 -04001385 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001386 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001387}
1388
Jamie Madilla5e06072018-05-18 14:36:05 -04001389vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001390{
Jamie Madilla5e06072018-05-18 14:36:05 -04001391 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001392}
1393
Jamie Madill21061022018-07-12 23:56:30 -04001394angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001395{
Jamie Madill21061022018-07-12 23:56:30 -04001396 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001397 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001398}
1399
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001400angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001401{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001402 if (mCommandGraph.empty())
1403 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001404 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001405 }
1406
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001407 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1408
Jamie Madillbea35a62018-07-05 11:54:10 -04001409 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1410 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001411
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001412 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001413 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1414 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001415
1416 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1417 // will be waited on.
1418 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001419
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001420 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001421 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001422 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1423 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001424 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001425 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001426 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001427 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001428 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001429
Jamie Madill21061022018-07-12 23:56:30 -04001430 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001431
Jamie Madill7c985f52018-11-29 18:16:17 -05001432 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001433}
1434
Jamie Madill78feddc2018-04-27 11:45:05 -04001435Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001436{
Jamie Madill78feddc2018-04-27 11:45:05 -04001437 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001438}
1439
Jamie Madill21061022018-07-12 23:56:30 -04001440angle::Result RendererVk::getDescriptorSetLayout(
1441 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001442 const vk::DescriptorSetLayoutDesc &desc,
1443 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1444{
Jamie Madill21061022018-07-12 23:56:30 -04001445 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001446}
1447
Jamie Madill21061022018-07-12 23:56:30 -04001448angle::Result RendererVk::getPipelineLayout(
1449 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001450 const vk::PipelineLayoutDesc &desc,
1451 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1452 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1453{
Jamie Madill21061022018-07-12 23:56:30 -04001454 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001455 pipelineLayoutOut);
1456}
1457
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001458angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1459{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001460 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001461
1462 if (--mPipelineCacheVkUpdateTimeout > 0)
1463 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001464 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001465 }
1466
1467 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1468
1469 // Get the size of the cache.
1470 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001471 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001472 if (result != VK_INCOMPLETE)
1473 {
1474 ANGLE_VK_TRY(displayVk, result);
1475 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001476
1477 angle::MemoryBuffer *pipelineCacheData = nullptr;
1478 ANGLE_VK_CHECK_ALLOC(displayVk,
1479 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1480
1481 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001482 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001483 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1484 // was determined just above), so receiving it hints at an implementation bug we would want
1485 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001486 ASSERT(result != VK_INCOMPLETE);
1487 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001488
1489 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1490 // the buffer to avoid leaking garbage memory.
1491 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1492 if (pipelineCacheSize < originalPipelineCacheSize)
1493 {
1494 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1495 originalPipelineCacheSize - pipelineCacheSize);
1496 }
1497
1498 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1499
Jamie Madill7c985f52018-11-29 18:16:17 -05001500 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001501}
1502
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001503angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1504 const vk::Semaphore **outSemaphore)
1505{
1506 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1507
1508 vk::SemaphoreHelper semaphore;
1509 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1510
1511 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1512 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1513
Jamie Madill7c985f52018-11-29 18:16:17 -05001514 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001515}
1516
1517const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1518{
1519 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1520
1521 // Return the semaphore to the pool (which will remain valid and unused until the
1522 // queue it's about to be waited on has finished execution). The caller is about
1523 // to wait on it.
1524 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1525
1526 return semaphore;
1527}
1528
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001529angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1530{
1531 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1532 // that seems impossible, so instead, we are going to make a small submission with just a
1533 // timestamp query. First, the disjoint timer query extension says:
1534 //
1535 // > This will return the GL time after all previous commands have reached the GL server but
1536 // have not yet necessarily executed.
1537 //
1538 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1539 // The wording allows us to make a submission to get the timestamp without performing a flush.
1540 //
1541 // Second:
1542 //
1543 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1544 // object target, applications can measure the latency between when commands reach the GL server
1545 // and when they are realized in the framebuffer.
1546 //
1547 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1548 // GPU bubble. This function directly generates a command buffer and submits it instead of
1549 // using the other member functions. This is to avoid changing any state, such as the queue
1550 // serial.
1551
1552 // Create a query used to receive the GPU timestamp
1553 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1554 vk::QueryHelper timestampQuery;
1555 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1556 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1557
1558 // Record the command buffer
1559 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1560 vk::CommandBuffer &commandBuffer = commandBatch.get();
1561
1562 VkCommandBufferAllocateInfo commandBufferInfo = {};
1563 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1564 commandBufferInfo.commandPool = mCommandPool.getHandle();
1565 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1566 commandBufferInfo.commandBufferCount = 1;
1567
Yuly Novikov27780292018-11-09 11:19:49 -05001568 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001569
1570 VkCommandBufferBeginInfo beginInfo = {};
1571 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1572 beginInfo.flags = 0;
1573 beginInfo.pInheritanceInfo = nullptr;
1574
Yuly Novikov27780292018-11-09 11:19:49 -05001575 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001576
1577 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1578 timestampQuery.getQuery(), 1);
1579 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1580 timestampQuery.getQueryPool()->getHandle(),
1581 timestampQuery.getQuery());
1582
Yuly Novikov27780292018-11-09 11:19:49 -05001583 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001584
1585 // Create fence for the submission
1586 VkFenceCreateInfo fenceInfo = {};
1587 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1588 fenceInfo.flags = 0;
1589
1590 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001591 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001592
1593 // Submit the command buffer
1594 VkSubmitInfo submitInfo = {};
1595 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1596 submitInfo.waitSemaphoreCount = 0;
1597 submitInfo.pWaitSemaphores = nullptr;
1598 submitInfo.pWaitDstStageMask = nullptr;
1599 submitInfo.commandBufferCount = 1;
1600 submitInfo.pCommandBuffers = commandBuffer.ptr();
1601 submitInfo.signalSemaphoreCount = 0;
1602 submitInfo.pSignalSemaphores = nullptr;
1603
1604 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1605
1606 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1607 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001608 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001609
1610 // Get the query results
1611 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1612
Yuly Novikov27780292018-11-09 11:19:49 -05001613 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1614 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1615 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001616
1617 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1618
Jamie Madill7c985f52018-11-29 18:16:17 -05001619 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001620}
1621
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001622// These functions look at the mandatory format for support, and fallback to querying the device (if
1623// necessary) to test the availability of the bits.
1624bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1625 const VkFormatFeatureFlags featureBits)
1626{
1627 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1628}
1629
1630bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1631 const VkFormatFeatureFlags featureBits)
1632{
1633 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1634}
1635
1636bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1637{
1638 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1639}
1640
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001641angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1642{
1643 ASSERT(mGpuEventsEnabled);
1644
1645 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1646 ASSERT(platform);
1647
1648 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1649 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1650 //
1651 // CPU GPU
1652 //
1653 // Record command buffer
1654 // with timestamp query
1655 //
1656 // Submit command buffer
1657 //
1658 // Post-submission work Begin execution
1659 //
1660 // ???? Write timstamp Tgpu
1661 //
1662 // ???? End execution
1663 //
1664 // ???? Return query results
1665 //
1666 // ????
1667 //
1668 // Get query results
1669 //
1670 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1671 // finished post-submission work while the GPU is executing in parallel. With no further work,
1672 // querying CPU timestamps before submission and after getting query results give the bounds to
1673 // Tgpu, which could be quite large.
1674 //
1675 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1676 // reduce this range. This function implements the following procedure:
1677 //
1678 // CPU GPU
1679 //
1680 // Record command buffer
1681 // with timestamp query
1682 //
1683 // Submit command buffer
1684 //
1685 // Post-submission work Begin execution
1686 //
1687 // ???? Set Event GPUReady
1688 //
1689 // Wait on Event GPUReady Wait on Event CPUReady
1690 //
1691 // Get CPU Time Ts Wait on Event CPUReady
1692 //
1693 // Set Event CPUReady Wait on Event CPUReady
1694 //
1695 // Get CPU Time Tcpu Get GPU Time Tgpu
1696 //
1697 // Wait on Event GPUDone Set Event GPUDone
1698 //
1699 // Get CPU Time Te End Execution
1700 //
1701 // Idle Return query results
1702 //
1703 // Get query results
1704 //
1705 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1706 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1707 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1708 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1709 // calibration.
1710 //
1711 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1712
1713 // Make sure nothing is running
1714 ASSERT(mCommandGraph.empty());
1715
1716 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1717
1718 // Create a query used to receive the GPU timestamp
1719 vk::QueryHelper timestampQuery;
1720 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1721
1722 // Create the three events
1723 VkEventCreateInfo eventCreateInfo = {};
1724 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1725 eventCreateInfo.flags = 0;
1726
1727 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001728 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1729 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1730 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001731
1732 constexpr uint32_t kRetries = 10;
1733
1734 // Time suffixes used are S for seconds and Cycles for cycles
1735 double tightestRangeS = 1e6f;
1736 double TcpuS = 0;
1737 uint64_t TgpuCycles = 0;
1738 for (uint32_t i = 0; i < kRetries; ++i)
1739 {
1740 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001741 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1742 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1743 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001744
1745 // Record the command buffer
1746 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1747 vk::CommandBuffer &commandBuffer = commandBatch.get();
1748
1749 VkCommandBufferAllocateInfo commandBufferInfo = {};
1750 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1751 commandBufferInfo.commandPool = mCommandPool.getHandle();
1752 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1753 commandBufferInfo.commandBufferCount = 1;
1754
Yuly Novikov27780292018-11-09 11:19:49 -05001755 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001756
1757 VkCommandBufferBeginInfo beginInfo = {};
1758 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1759 beginInfo.flags = 0;
1760 beginInfo.pInheritanceInfo = nullptr;
1761
Yuly Novikov27780292018-11-09 11:19:49 -05001762 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001763
1764 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1765 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1766 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1767 nullptr);
1768
1769 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1770 timestampQuery.getQuery(), 1);
1771 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1772 timestampQuery.getQueryPool()->getHandle(),
1773 timestampQuery.getQuery());
1774
1775 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1776
Yuly Novikov27780292018-11-09 11:19:49 -05001777 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001778
1779 // Submit the command buffer
1780 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1781 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1782 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1783
1784 VkSubmitInfo submitInfo = {};
1785 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1786 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1787 submitInfo.pWaitSemaphores = waitSemaphores.data();
1788 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1789 submitInfo.commandBufferCount = 1;
1790 submitInfo.pCommandBuffers = commandBuffer.ptr();
1791 submitInfo.signalSemaphoreCount = 0;
1792 submitInfo.pSignalSemaphores = nullptr;
1793
1794 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1795
1796 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001797 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001798 do
1799 {
Yuly Novikov27780292018-11-09 11:19:49 -05001800 result = gpuReady.get().getStatus(mDevice);
1801 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1802 {
1803 ANGLE_VK_TRY(context, result);
1804 }
1805 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001806
1807 double TsS = platform->monotonicallyIncreasingTime(platform);
1808
1809 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001810 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001811 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1812
1813 // Wait for GPU to be done. Another short busy wait.
1814 do
1815 {
Yuly Novikov27780292018-11-09 11:19:49 -05001816 result = gpuDone.get().getStatus(mDevice);
1817 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1818 {
1819 ANGLE_VK_TRY(context, result);
1820 }
1821 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001822
1823 double TeS = platform->monotonicallyIncreasingTime(platform);
1824
1825 // Get the query results
1826 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1827
1828 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1829
1830 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001831 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1832 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1833 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001834
1835 // Use the first timestamp queried as origin.
1836 if (mGpuEventTimestampOrigin == 0)
1837 {
1838 mGpuEventTimestampOrigin = gpuTimestampCycles;
1839 }
1840
1841 // Take these CPU and GPU timestamps if there is better confidence.
1842 double confidenceRangeS = TeS - TsS;
1843 if (confidenceRangeS < tightestRangeS)
1844 {
1845 tightestRangeS = confidenceRangeS;
1846 TcpuS = cpuTimestampS;
1847 TgpuCycles = gpuTimestampCycles;
1848 }
1849 }
1850
1851 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1852
1853 // timestampPeriod gives nanoseconds/cycle.
1854 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1855 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1856 1'000'000'000.0;
1857
1858 flushGpuEvents(TgpuS, TcpuS);
1859
1860 mGpuClockSync.gpuTimestampS = TgpuS;
1861 mGpuClockSync.cpuTimestampS = TcpuS;
1862
Jamie Madill7c985f52018-11-29 18:16:17 -05001863 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001864}
1865
1866angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1867 vk::CommandBuffer *commandBuffer,
1868 char phase,
1869 const char *name)
1870{
1871 ASSERT(mGpuEventsEnabled);
1872
1873 GpuEventQuery event;
1874
1875 event.name = name;
1876 event.phase = phase;
1877 event.serial = mCurrentQueueSerial;
1878
1879 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1880
1881 commandBuffer->resetQueryPool(
1882 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1883 commandBuffer->writeTimestamp(
1884 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1885 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1886
1887 mInFlightGpuEventQueries.push_back(std::move(event));
1888
Jamie Madill7c985f52018-11-29 18:16:17 -05001889 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001890}
1891
1892angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1893{
1894 ASSERT(mGpuEventsEnabled);
1895
1896 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1897 ASSERT(platform);
1898
1899 int finishedCount = 0;
1900
1901 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1902 {
1903 // Only check the timestamp query if the submission has finished.
1904 if (eventQuery.serial > mLastCompletedQueueSerial)
1905 {
1906 break;
1907 }
1908
1909 // See if the results are available.
1910 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001911 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1912 ->getResults(mDevice, eventQuery.queryIndex, 1,
1913 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1914 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1915 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001916 {
1917 break;
1918 }
Yuly Novikov27780292018-11-09 11:19:49 -05001919 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001920
1921 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1922
1923 GpuEvent event;
1924 event.gpuTimestampCycles = gpuTimestampCycles;
1925 event.name = eventQuery.name;
1926 event.phase = eventQuery.phase;
1927
1928 mGpuEvents.emplace_back(event);
1929
1930 ++finishedCount;
1931 }
1932
1933 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1934 mInFlightGpuEventQueries.begin() + finishedCount);
1935
Jamie Madill7c985f52018-11-29 18:16:17 -05001936 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001937}
1938
1939void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1940{
1941 if (mGpuEvents.size() == 0)
1942 {
1943 return;
1944 }
1945
1946 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1947 ASSERT(platform);
1948
1949 // Find the slope of the clock drift for adjustment
1950 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1951 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1952 double gpuSyncDriftSlope = 0;
1953
1954 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1955 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1956
1957 // No gpu trace events should have been generated before the clock sync, so if there is no
1958 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1959 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1960 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1961
1962 gpuSyncDriftSlope =
1963 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1964
1965 for (const GpuEvent &event : mGpuEvents)
1966 {
1967 double gpuTimestampS =
1968 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1969 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1970
1971 // Account for clock drift.
1972 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1973
1974 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1975 // for.
1976 static long long eventId = 1;
1977 static const unsigned char *categoryEnabled =
1978 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1979 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1980 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1981 }
1982
1983 mGpuEvents.clear();
1984}
1985
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001986template <VkFormatFeatureFlags VkFormatProperties::*features>
1987bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1988{
1989 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
1990 VkFormatProperties &deviceProperties = mFormatProperties[format];
1991
1992 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
1993 {
1994 // If we don't have the actual device features, see if the requested features are mandatory.
1995 // If so, there's no need to query the device.
1996 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
1997 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
1998 {
1999 return true;
2000 }
2001
2002 // Otherwise query the format features and cache it.
2003 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2004 }
2005
2006 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2007}
2008
Jamie Madillaaca96e2018-06-12 10:19:48 -04002009uint32_t GetUniformBufferDescriptorCount()
2010{
2011 return kUniformBufferDescriptorsPerDescriptorSet;
2012}
2013
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002014} // namespace rx