blob: 3f131c34a9d96458834b7c8955c42e45fc8f42da [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();
369 const char *exeDir = angle::GetExecutableDirectory();
370 mChangedCWD = angle::SetCWD(exeDir);
371 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;
846
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400847 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500848
849 float zeroPriority = 0.0f;
850
851 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500852 queueCreateInfo.flags = 0;
853 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
854 queueCreateInfo.queueCount = 1;
855 queueCreateInfo.pQueuePriorities = &zeroPriority;
856
857 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400858 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500859
Jamie Madill50cf2be2018-06-15 09:46:57 -0400860 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400861 createInfo.flags = 0;
862 createInfo.queueCreateInfoCount = 1;
863 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500864 createInfo.enabledLayerCount = enabledLayerCount;
865 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500866 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
867 createInfo.ppEnabledExtensionNames =
868 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400869 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500870
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400871 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500872
873 mCurrentQueueFamilyIndex = queueFamilyIndex;
874
875 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
876
877 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400878 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500879 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
880 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
881 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500882
Yuly Novikov27780292018-11-09 11:19:49 -0500883 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400884
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400885 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500886 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500887
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400888 // Initialize the submission semaphore pool.
889 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
890
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400891#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
892 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
893 ASSERT(platform);
894
895 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
896 // platform discovery.
897 const unsigned char *gpuEventsEnabled =
898 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
899 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
900#endif
901
902 if (mGpuEventsEnabled)
903 {
904 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
905 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
906 vk::kDefaultTimestampQueryPoolSize));
907 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
908 }
909
Jamie Madill7c985f52018-11-29 18:16:17 -0500910 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500911}
912
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400913angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400914 VkSurfaceKHR surface,
915 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500916{
917 // We've already initialized a device, and can't re-create it unless it's never been used.
918 // TODO(jmadill): Handle the re-creation case if necessary.
919 if (mDevice != VK_NULL_HANDLE)
920 {
921 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
922
923 // Check if the current device supports present on this surface.
924 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400925 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400926 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500927 surface, &supportsPresent));
928
Jamie Madill6cad7732018-07-11 09:01:17 -0400929 if (supportsPresent == VK_TRUE)
930 {
931 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500932 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400933 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500934 }
935
936 // Find a graphics and present queue.
937 Optional<uint32_t> newPresentQueue;
938 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500939 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500940 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
941 {
942 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500943 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500944 {
945 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400946 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
947 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500948
949 if (supportsPresent == VK_TRUE)
950 {
951 newPresentQueue = queueIndex;
952 break;
953 }
954 }
955 }
956
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400957 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
958 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500959
Jamie Madill6cad7732018-07-11 09:01:17 -0400960 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500961 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500962}
963
964std::string RendererVk::getVendorString() const
965{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300966 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500967}
968
Jamie Madille09bd5d2016-11-29 16:20:35 -0500969std::string RendererVk::getRendererDescription() const
970{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500971 std::stringstream strstr;
972
973 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
974
975 strstr << "Vulkan ";
976 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
977 strstr << VK_VERSION_MINOR(apiVersion) << ".";
978 strstr << VK_VERSION_PATCH(apiVersion);
979
Olli Etuahoc6a06182018-04-13 14:11:46 +0300980 strstr << "(";
981
982 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
983 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
984 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
985 // driver detection.
986 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
987 {
988 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
989 }
990
Geoff Langa7af56b2018-12-14 14:20:28 -0500991 strstr << mPhysicalDeviceProperties.deviceName;
992 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
993
994 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500995
996 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500997}
998
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500999gl::Version RendererVk::getMaxSupportedESVersion() const
1000{
1001 // Declare GLES2 support if necessary features for GLES3 are missing
1002 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
1003
1004 if (!necessaryFeaturesForES3)
1005 {
1006 return gl::Version(2, 0);
1007 }
1008
1009 return gl::Version(3, 0);
1010}
1011
Ian Elliottbcb78902018-12-19 11:46:29 -07001012void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001013{
Jamie Madillb36a4812018-09-25 10:15:11 -04001014// Use OpenGL line rasterization rules by default.
1015// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1016#if defined(ANGLE_PLATFORM_ANDROID)
1017 mFeatures.basicGLLineRasterization = false;
1018#else
Jamie Madill12222072018-07-11 14:59:48 -04001019 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001020#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001021
Ian Elliott52f5da42018-12-21 09:02:09 -07001022 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1023 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001024 {
1025 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1026 // investigation. http://anglebug.com/2728
1027 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1028 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001029
1030#ifdef ANGLE_PLATFORM_WINDOWS
1031 // http://anglebug.com/2838
1032 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001033
1034 // http://anglebug.com/3055
1035 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001036#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001037
1038 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1039 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001040
1041 // Work around incorrect NVIDIA point size range clamping.
1042 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1043 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1044 {
1045 mFeatures.clampPointSize = true;
1046 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001047
1048#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001049 // Work around ineffective compute-graphics barriers on Nexus 5X.
1050 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1051 // http://anglebug.com/3019
1052 mFeatures.flushAfterVertexConversion =
1053 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001054#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001055
1056 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1057 {
1058 mFeatures.supportsIncrementalPresent = true;
1059 }
Jamie Madill12222072018-07-11 14:59:48 -04001060}
1061
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001062void RendererVk::initPipelineCacheVkKey()
1063{
1064 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1065 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1066 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1067 // there is no '\0' in the result.
1068 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1069 {
1070 hashStream << std::hex << c;
1071 }
1072 // Add the vendor and device id too for good measure.
1073 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1074 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1075
1076 const std::string &hashString = hashStream.str();
1077 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1078 hashString.length(), mPipelineCacheVkBlobKey.data());
1079}
1080
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001081angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001082{
1083 initPipelineCacheVkKey();
1084
1085 egl::BlobCache::Value initialData;
1086 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1087 mPipelineCacheVkBlobKey, &initialData);
1088
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001089 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001090
1091 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001092 pipelineCacheCreateInfo.flags = 0;
1093 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1094 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1095
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001096 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001097 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001098}
1099
Jamie Madillacccc6c2016-05-03 17:22:10 -04001100void RendererVk::ensureCapsInitialized() const
1101{
1102 if (!mCapsInitialized)
1103 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001104 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1105 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1106 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001107 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001108 mCapsInitialized = true;
1109 }
1110}
1111
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001112void RendererVk::getSubmitWaitSemaphores(
1113 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001114 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1115 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001116{
1117 if (mSubmitLastSignaledSemaphore.getSemaphore())
1118 {
1119 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001120 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001121
1122 // Return the semaphore to the pool (which will remain valid and unused until the
1123 // queue it's about to be waited on has finished execution).
1124 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1125 }
1126
1127 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1128 {
1129 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001130 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1131
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001132 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1133 }
1134 mSubmitWaitSemaphores.clear();
1135}
1136
Jamie Madillacccc6c2016-05-03 17:22:10 -04001137const gl::Caps &RendererVk::getNativeCaps() const
1138{
1139 ensureCapsInitialized();
1140 return mNativeCaps;
1141}
1142
1143const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1144{
1145 ensureCapsInitialized();
1146 return mNativeTextureCaps;
1147}
1148
1149const gl::Extensions &RendererVk::getNativeExtensions() const
1150{
1151 ensureCapsInitialized();
1152 return mNativeExtensions;
1153}
1154
1155const gl::Limitations &RendererVk::getNativeLimitations() const
1156{
1157 ensureCapsInitialized();
1158 return mNativeLimitations;
1159}
1160
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001161uint32_t RendererVk::getMaxActiveTextures()
1162{
1163 // TODO(lucferron): expose this limitation to GL in Context Caps
1164 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1165 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1166}
1167
Jamie Madill49ac74b2017-12-21 14:42:33 -05001168const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001169{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001170 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001171}
1172
Jamie Madill21061022018-07-12 23:56:30 -04001173angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001174{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001175 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001176 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001177 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1178
Luc Ferron1617e692018-07-11 11:08:19 -04001179 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1180 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001181
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001182 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001183 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1184 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001185
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001186 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001187 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001188 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1189 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001190 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001191 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001192 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001193 submitInfo.signalSemaphoreCount = 0;
1194 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001195
Jamie Madill21061022018-07-12 23:56:30 -04001196 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001197 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001198
Jamie Madill4c26fc22017-02-24 11:04:10 -05001199 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001200 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001201 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001202
1203 if (mGpuEventsEnabled)
1204 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001205 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001206 while (mInFlightGpuEventQueries.size() > 0)
1207 {
1208 ANGLE_TRY(checkCompletedGpuEvents(context));
1209 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001210 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1211 // synchronization if there is no event to be adjusted (happens when finish() gets called
1212 // multiple times towards the end of the application).
1213 if (mGpuEvents.size() > 0)
1214 {
1215 ANGLE_TRY(synchronizeCpuGpuTime(context));
1216 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001217 }
1218
Jamie Madill7c985f52018-11-29 18:16:17 -05001219 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001220}
1221
Jamie Madill0c0dc342017-03-24 14:18:51 -04001222void RendererVk::freeAllInFlightResources()
1223{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001224 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001225 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001226 // On device loss we need to wait for fence to be signaled before destroying it
1227 if (mDeviceLost)
1228 {
1229 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1230 // If wait times out, it is probably not possible to recover from lost device
1231 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1232 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001233 batch.fence.destroy(mDevice);
1234 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001235 }
1236 mInFlightCommands.clear();
1237
1238 for (auto &garbage : mGarbage)
1239 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001240 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001241 }
1242 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001243
1244 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001245}
1246
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001247angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001248{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001249 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001250
Jamie Madill49ac74b2017-12-21 14:42:33 -05001251 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001252 {
Yuly Novikov27780292018-11-09 11:19:49 -05001253 VkResult result = batch.fence.getStatus(mDevice);
1254 if (result == VK_NOT_READY)
1255 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001256 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001257 }
1258 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001259
Jamie Madill49ac74b2017-12-21 14:42:33 -05001260 ASSERT(batch.serial > mLastCompletedQueueSerial);
1261 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001262
Jamie Madill49ac74b2017-12-21 14:42:33 -05001263 batch.fence.destroy(mDevice);
1264 batch.commandPool.destroy(mDevice);
1265 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001266 }
1267
Jamie Madill49ac74b2017-12-21 14:42:33 -05001268 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001269
1270 size_t freeIndex = 0;
1271 for (; freeIndex < mGarbage.size(); ++freeIndex)
1272 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001273 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001274 break;
1275 }
1276
1277 // Remove the entries from the garbage list - they should be ready to go.
1278 if (freeIndex > 0)
1279 {
1280 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001281 }
1282
Jamie Madill7c985f52018-11-29 18:16:17 -05001283 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001284}
1285
Jamie Madill21061022018-07-12 23:56:30 -04001286angle::Result RendererVk::submitFrame(vk::Context *context,
1287 const VkSubmitInfo &submitInfo,
1288 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001289{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001290 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001291 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001292 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1293 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001294
Jamie Madillbea35a62018-07-05 11:54:10 -04001295 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1296 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001297 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001298
Jamie Madill21061022018-07-12 23:56:30 -04001299 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001300
1301 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001302 batch.commandPool = std::move(mCommandPool);
1303 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001304
Jamie Madillbea35a62018-07-05 11:54:10 -04001305 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001306
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001307 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1308 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001309 // so the limit is larger than the expected number of images. The
1310 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001311 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001312
1313 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001314 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001315 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001316 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001317
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001318 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001319
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001320 if (mGpuEventsEnabled)
1321 {
1322 ANGLE_TRY(checkCompletedGpuEvents(context));
1323 }
1324
Jamie Madill49ac74b2017-12-21 14:42:33 -05001325 // Simply null out the command buffer here - it was allocated using the command pool.
1326 commandBuffer.releaseHandle();
1327
1328 // Reallocate the command pool for next frame.
1329 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001330 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001331 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001332 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001333 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001334
Yuly Novikov27780292018-11-09 11:19:49 -05001335 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001336 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001337}
1338
Jamie Madillaaca96e2018-06-12 10:19:48 -04001339bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001340{
1341 return serial > mLastCompletedQueueSerial;
1342}
1343
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001344angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1345{
1346 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1347 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001348 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001349 }
1350
1351 // Find the first batch with serial equal to or bigger than given serial (note that
1352 // the batch serials are unique, otherwise upper-bound would have been necessary).
1353 size_t batchIndex = mInFlightCommands.size() - 1;
1354 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1355 {
1356 if (mInFlightCommands[i].serial >= serial)
1357 {
1358 batchIndex = i;
1359 break;
1360 }
1361 }
1362 const CommandBatch &batch = mInFlightCommands[batchIndex];
1363
1364 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001365 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001366
1367 // Clean up finished batches.
1368 return checkCompletedCommands(context);
1369}
1370
Jamie Madill21061022018-07-12 23:56:30 -04001371angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1372 const vk::RenderPassDesc &desc,
1373 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001374{
Jamie Madill21061022018-07-12 23:56:30 -04001375 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001376 renderPassOut);
1377}
1378
Jamie Madill21061022018-07-12 23:56:30 -04001379angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1380 const vk::RenderPassDesc &desc,
1381 const vk::AttachmentOpsArray &ops,
1382 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001383{
Jamie Madill21061022018-07-12 23:56:30 -04001384 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001385 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001386}
1387
Jamie Madilla5e06072018-05-18 14:36:05 -04001388vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001389{
Jamie Madilla5e06072018-05-18 14:36:05 -04001390 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001391}
1392
Jamie Madill21061022018-07-12 23:56:30 -04001393angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001394{
Jamie Madill21061022018-07-12 23:56:30 -04001395 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001396 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001397}
1398
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001399angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001400{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001401 if (mCommandGraph.empty())
1402 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001403 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001404 }
1405
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001406 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1407
Jamie Madillbea35a62018-07-05 11:54:10 -04001408 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1409 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001410
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001411 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001412 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1413 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001414
1415 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1416 // will be waited on.
1417 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001418
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001419 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001420 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001421 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1422 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001423 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001424 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001425 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001426 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001427 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001428
Jamie Madill21061022018-07-12 23:56:30 -04001429 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001430
Jamie Madill7c985f52018-11-29 18:16:17 -05001431 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001432}
1433
Jamie Madill78feddc2018-04-27 11:45:05 -04001434Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001435{
Jamie Madill78feddc2018-04-27 11:45:05 -04001436 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001437}
1438
Jamie Madill21061022018-07-12 23:56:30 -04001439angle::Result RendererVk::getDescriptorSetLayout(
1440 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001441 const vk::DescriptorSetLayoutDesc &desc,
1442 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1443{
Jamie Madill21061022018-07-12 23:56:30 -04001444 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001445}
1446
Jamie Madill21061022018-07-12 23:56:30 -04001447angle::Result RendererVk::getPipelineLayout(
1448 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001449 const vk::PipelineLayoutDesc &desc,
1450 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1451 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1452{
Jamie Madill21061022018-07-12 23:56:30 -04001453 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001454 pipelineLayoutOut);
1455}
1456
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001457angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1458{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001459 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001460
1461 if (--mPipelineCacheVkUpdateTimeout > 0)
1462 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001463 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001464 }
1465
1466 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1467
1468 // Get the size of the cache.
1469 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001470 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001471 if (result != VK_INCOMPLETE)
1472 {
1473 ANGLE_VK_TRY(displayVk, result);
1474 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001475
1476 angle::MemoryBuffer *pipelineCacheData = nullptr;
1477 ANGLE_VK_CHECK_ALLOC(displayVk,
1478 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1479
1480 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001481 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001482 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1483 // was determined just above), so receiving it hints at an implementation bug we would want
1484 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001485 ASSERT(result != VK_INCOMPLETE);
1486 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001487
1488 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1489 // the buffer to avoid leaking garbage memory.
1490 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1491 if (pipelineCacheSize < originalPipelineCacheSize)
1492 {
1493 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1494 originalPipelineCacheSize - pipelineCacheSize);
1495 }
1496
1497 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1498
Jamie Madill7c985f52018-11-29 18:16:17 -05001499 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001500}
1501
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001502angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1503 const vk::Semaphore **outSemaphore)
1504{
1505 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1506
1507 vk::SemaphoreHelper semaphore;
1508 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1509
1510 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1511 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1512
Jamie Madill7c985f52018-11-29 18:16:17 -05001513 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001514}
1515
1516const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1517{
1518 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1519
1520 // Return the semaphore to the pool (which will remain valid and unused until the
1521 // queue it's about to be waited on has finished execution). The caller is about
1522 // to wait on it.
1523 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1524
1525 return semaphore;
1526}
1527
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001528angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1529{
1530 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1531 // that seems impossible, so instead, we are going to make a small submission with just a
1532 // timestamp query. First, the disjoint timer query extension says:
1533 //
1534 // > This will return the GL time after all previous commands have reached the GL server but
1535 // have not yet necessarily executed.
1536 //
1537 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1538 // The wording allows us to make a submission to get the timestamp without performing a flush.
1539 //
1540 // Second:
1541 //
1542 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1543 // object target, applications can measure the latency between when commands reach the GL server
1544 // and when they are realized in the framebuffer.
1545 //
1546 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1547 // GPU bubble. This function directly generates a command buffer and submits it instead of
1548 // using the other member functions. This is to avoid changing any state, such as the queue
1549 // serial.
1550
1551 // Create a query used to receive the GPU timestamp
1552 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1553 vk::QueryHelper timestampQuery;
1554 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1555 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1556
1557 // Record the command buffer
1558 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1559 vk::CommandBuffer &commandBuffer = commandBatch.get();
1560
1561 VkCommandBufferAllocateInfo commandBufferInfo = {};
1562 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1563 commandBufferInfo.commandPool = mCommandPool.getHandle();
1564 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1565 commandBufferInfo.commandBufferCount = 1;
1566
Yuly Novikov27780292018-11-09 11:19:49 -05001567 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001568
1569 VkCommandBufferBeginInfo beginInfo = {};
1570 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1571 beginInfo.flags = 0;
1572 beginInfo.pInheritanceInfo = nullptr;
1573
Yuly Novikov27780292018-11-09 11:19:49 -05001574 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001575
1576 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1577 timestampQuery.getQuery(), 1);
1578 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1579 timestampQuery.getQueryPool()->getHandle(),
1580 timestampQuery.getQuery());
1581
Yuly Novikov27780292018-11-09 11:19:49 -05001582 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001583
1584 // Create fence for the submission
1585 VkFenceCreateInfo fenceInfo = {};
1586 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1587 fenceInfo.flags = 0;
1588
1589 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001590 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001591
1592 // Submit the command buffer
1593 VkSubmitInfo submitInfo = {};
1594 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1595 submitInfo.waitSemaphoreCount = 0;
1596 submitInfo.pWaitSemaphores = nullptr;
1597 submitInfo.pWaitDstStageMask = nullptr;
1598 submitInfo.commandBufferCount = 1;
1599 submitInfo.pCommandBuffers = commandBuffer.ptr();
1600 submitInfo.signalSemaphoreCount = 0;
1601 submitInfo.pSignalSemaphores = nullptr;
1602
1603 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1604
1605 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1606 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001607 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001608
1609 // Get the query results
1610 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1611
Yuly Novikov27780292018-11-09 11:19:49 -05001612 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1613 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1614 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001615
1616 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1617
Jamie Madill7c985f52018-11-29 18:16:17 -05001618 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001619}
1620
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001621// These functions look at the mandatory format for support, and fallback to querying the device (if
1622// necessary) to test the availability of the bits.
1623bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1624 const VkFormatFeatureFlags featureBits)
1625{
1626 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1627}
1628
1629bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1630 const VkFormatFeatureFlags featureBits)
1631{
1632 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1633}
1634
1635bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1636{
1637 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1638}
1639
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001640angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1641{
1642 ASSERT(mGpuEventsEnabled);
1643
1644 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1645 ASSERT(platform);
1646
1647 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1648 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1649 //
1650 // CPU GPU
1651 //
1652 // Record command buffer
1653 // with timestamp query
1654 //
1655 // Submit command buffer
1656 //
1657 // Post-submission work Begin execution
1658 //
1659 // ???? Write timstamp Tgpu
1660 //
1661 // ???? End execution
1662 //
1663 // ???? Return query results
1664 //
1665 // ????
1666 //
1667 // Get query results
1668 //
1669 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1670 // finished post-submission work while the GPU is executing in parallel. With no further work,
1671 // querying CPU timestamps before submission and after getting query results give the bounds to
1672 // Tgpu, which could be quite large.
1673 //
1674 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1675 // reduce this range. This function implements the following procedure:
1676 //
1677 // CPU GPU
1678 //
1679 // Record command buffer
1680 // with timestamp query
1681 //
1682 // Submit command buffer
1683 //
1684 // Post-submission work Begin execution
1685 //
1686 // ???? Set Event GPUReady
1687 //
1688 // Wait on Event GPUReady Wait on Event CPUReady
1689 //
1690 // Get CPU Time Ts Wait on Event CPUReady
1691 //
1692 // Set Event CPUReady Wait on Event CPUReady
1693 //
1694 // Get CPU Time Tcpu Get GPU Time Tgpu
1695 //
1696 // Wait on Event GPUDone Set Event GPUDone
1697 //
1698 // Get CPU Time Te End Execution
1699 //
1700 // Idle Return query results
1701 //
1702 // Get query results
1703 //
1704 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1705 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1706 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1707 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1708 // calibration.
1709 //
1710 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1711
1712 // Make sure nothing is running
1713 ASSERT(mCommandGraph.empty());
1714
1715 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1716
1717 // Create a query used to receive the GPU timestamp
1718 vk::QueryHelper timestampQuery;
1719 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1720
1721 // Create the three events
1722 VkEventCreateInfo eventCreateInfo = {};
1723 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1724 eventCreateInfo.flags = 0;
1725
1726 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001727 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1728 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1729 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001730
1731 constexpr uint32_t kRetries = 10;
1732
1733 // Time suffixes used are S for seconds and Cycles for cycles
1734 double tightestRangeS = 1e6f;
1735 double TcpuS = 0;
1736 uint64_t TgpuCycles = 0;
1737 for (uint32_t i = 0; i < kRetries; ++i)
1738 {
1739 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001740 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1741 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1742 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001743
1744 // Record the command buffer
1745 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1746 vk::CommandBuffer &commandBuffer = commandBatch.get();
1747
1748 VkCommandBufferAllocateInfo commandBufferInfo = {};
1749 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1750 commandBufferInfo.commandPool = mCommandPool.getHandle();
1751 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1752 commandBufferInfo.commandBufferCount = 1;
1753
Yuly Novikov27780292018-11-09 11:19:49 -05001754 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001755
1756 VkCommandBufferBeginInfo beginInfo = {};
1757 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1758 beginInfo.flags = 0;
1759 beginInfo.pInheritanceInfo = nullptr;
1760
Yuly Novikov27780292018-11-09 11:19:49 -05001761 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001762
1763 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1764 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1765 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1766 nullptr);
1767
1768 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1769 timestampQuery.getQuery(), 1);
1770 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1771 timestampQuery.getQueryPool()->getHandle(),
1772 timestampQuery.getQuery());
1773
1774 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1775
Yuly Novikov27780292018-11-09 11:19:49 -05001776 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001777
1778 // Submit the command buffer
1779 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1780 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1781 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1782
1783 VkSubmitInfo submitInfo = {};
1784 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1785 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1786 submitInfo.pWaitSemaphores = waitSemaphores.data();
1787 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1788 submitInfo.commandBufferCount = 1;
1789 submitInfo.pCommandBuffers = commandBuffer.ptr();
1790 submitInfo.signalSemaphoreCount = 0;
1791 submitInfo.pSignalSemaphores = nullptr;
1792
1793 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1794
1795 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001796 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001797 do
1798 {
Yuly Novikov27780292018-11-09 11:19:49 -05001799 result = gpuReady.get().getStatus(mDevice);
1800 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1801 {
1802 ANGLE_VK_TRY(context, result);
1803 }
1804 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001805
1806 double TsS = platform->monotonicallyIncreasingTime(platform);
1807
1808 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001809 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001810 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1811
1812 // Wait for GPU to be done. Another short busy wait.
1813 do
1814 {
Yuly Novikov27780292018-11-09 11:19:49 -05001815 result = gpuDone.get().getStatus(mDevice);
1816 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1817 {
1818 ANGLE_VK_TRY(context, result);
1819 }
1820 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001821
1822 double TeS = platform->monotonicallyIncreasingTime(platform);
1823
1824 // Get the query results
1825 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1826
1827 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1828
1829 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001830 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1831 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1832 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001833
1834 // Use the first timestamp queried as origin.
1835 if (mGpuEventTimestampOrigin == 0)
1836 {
1837 mGpuEventTimestampOrigin = gpuTimestampCycles;
1838 }
1839
1840 // Take these CPU and GPU timestamps if there is better confidence.
1841 double confidenceRangeS = TeS - TsS;
1842 if (confidenceRangeS < tightestRangeS)
1843 {
1844 tightestRangeS = confidenceRangeS;
1845 TcpuS = cpuTimestampS;
1846 TgpuCycles = gpuTimestampCycles;
1847 }
1848 }
1849
1850 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1851
1852 // timestampPeriod gives nanoseconds/cycle.
1853 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1854 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1855 1'000'000'000.0;
1856
1857 flushGpuEvents(TgpuS, TcpuS);
1858
1859 mGpuClockSync.gpuTimestampS = TgpuS;
1860 mGpuClockSync.cpuTimestampS = TcpuS;
1861
Jamie Madill7c985f52018-11-29 18:16:17 -05001862 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001863}
1864
1865angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1866 vk::CommandBuffer *commandBuffer,
1867 char phase,
1868 const char *name)
1869{
1870 ASSERT(mGpuEventsEnabled);
1871
1872 GpuEventQuery event;
1873
1874 event.name = name;
1875 event.phase = phase;
1876 event.serial = mCurrentQueueSerial;
1877
1878 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1879
1880 commandBuffer->resetQueryPool(
1881 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1882 commandBuffer->writeTimestamp(
1883 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1884 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1885
1886 mInFlightGpuEventQueries.push_back(std::move(event));
1887
Jamie Madill7c985f52018-11-29 18:16:17 -05001888 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001889}
1890
1891angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1892{
1893 ASSERT(mGpuEventsEnabled);
1894
1895 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1896 ASSERT(platform);
1897
1898 int finishedCount = 0;
1899
1900 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1901 {
1902 // Only check the timestamp query if the submission has finished.
1903 if (eventQuery.serial > mLastCompletedQueueSerial)
1904 {
1905 break;
1906 }
1907
1908 // See if the results are available.
1909 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001910 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1911 ->getResults(mDevice, eventQuery.queryIndex, 1,
1912 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1913 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1914 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001915 {
1916 break;
1917 }
Yuly Novikov27780292018-11-09 11:19:49 -05001918 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001919
1920 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1921
1922 GpuEvent event;
1923 event.gpuTimestampCycles = gpuTimestampCycles;
1924 event.name = eventQuery.name;
1925 event.phase = eventQuery.phase;
1926
1927 mGpuEvents.emplace_back(event);
1928
1929 ++finishedCount;
1930 }
1931
1932 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1933 mInFlightGpuEventQueries.begin() + finishedCount);
1934
Jamie Madill7c985f52018-11-29 18:16:17 -05001935 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001936}
1937
1938void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1939{
1940 if (mGpuEvents.size() == 0)
1941 {
1942 return;
1943 }
1944
1945 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1946 ASSERT(platform);
1947
1948 // Find the slope of the clock drift for adjustment
1949 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1950 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1951 double gpuSyncDriftSlope = 0;
1952
1953 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1954 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1955
1956 // No gpu trace events should have been generated before the clock sync, so if there is no
1957 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1958 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1959 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1960
1961 gpuSyncDriftSlope =
1962 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1963
1964 for (const GpuEvent &event : mGpuEvents)
1965 {
1966 double gpuTimestampS =
1967 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1968 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1969
1970 // Account for clock drift.
1971 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1972
1973 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1974 // for.
1975 static long long eventId = 1;
1976 static const unsigned char *categoryEnabled =
1977 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1978 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1979 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1980 }
1981
1982 mGpuEvents.clear();
1983}
1984
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001985template <VkFormatFeatureFlags VkFormatProperties::*features>
1986bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1987{
1988 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
1989 VkFormatProperties &deviceProperties = mFormatProperties[format];
1990
1991 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
1992 {
1993 // If we don't have the actual device features, see if the requested features are mandatory.
1994 // If so, there's no need to query the device.
1995 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
1996 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
1997 {
1998 return true;
1999 }
2000
2001 // Otherwise query the format features and cache it.
2002 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2003 }
2004
2005 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2006}
2007
Jamie Madillaaca96e2018-06-12 10:19:48 -04002008uint32_t GetUniformBufferDescriptorCount()
2009{
2010 return kUniformBufferDescriptorsPerDescriptorSet;
2011}
2012
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002013} // namespace rx