blob: ede6f91157a743bc3a8b8941c82b6c90fa392f8a [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040034
Shahbaz Youssefi61656022018-10-24 15:00:50 -040035#include "third_party/trace_event/trace_event.h"
36
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070037// Consts
38namespace
39{
Jamie Madill7c985f52018-11-29 18:16:17 -050040const uint32_t kMockVendorID = 0xba5eba11;
41const uint32_t kMockDeviceID = 0xf005ba11;
42constexpr char kMockDeviceName[] = "Vulkan Mock Device";
43constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050044constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070045} // anonymous namespace
46
Jamie Madill9e54b5a2016-05-25 12:57:39 -040047namespace rx
48{
49
Jamie Madille09bd5d2016-11-29 16:20:35 -050050namespace
51{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040052// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
53// one for the vertex shader.
54constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040055// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
56static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040057// Wait a maximum of 10s. If that times out, we declare it a failure.
58static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050059
Omar El Sheikh26c61b22018-06-29 12:50:59 -060060bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
61{
62#if !defined(ANGLE_PLATFORM_ANDROID)
63 // Mock ICD does not currently run on Android
64 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
66 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
67#else
68 return false;
69#endif // !defined(ANGLE_PLATFORM_ANDROID)
70}
71
Jamie Madille09bd5d2016-11-29 16:20:35 -050072VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
73 const std::vector<const char *> &enabledExtensionNames)
74{
75 // Compile the extensions names into a set.
76 std::set<std::string> extensionNames;
77 for (const auto &extensionProp : extensionProps)
78 {
79 extensionNames.insert(extensionProp.extensionName);
80 }
81
Jamie Madillacf2f3a2017-11-21 19:22:44 -050082 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050083 {
84 if (extensionNames.count(extensionName) == 0)
85 {
86 return VK_ERROR_EXTENSION_NOT_PRESENT;
87 }
88 }
89
90 return VK_SUCCESS;
91}
92
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050093bool ExtensionFound(const char *extensionName,
94 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060095{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050096 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060097 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050098 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060099 {
100 return true;
101 }
102 }
103 return false;
104}
105
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500106// Array of Validation error/warning messages that will be ignored, should include bugID
107constexpr std::array<const char *, 1> kSkippedMessages = {
108 // http://anglebug.com/2796
109 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
110
111// Suppress validation errors that are known
112// return "true" if given code/prefix/message is known, else return "false"
113bool IsIgnoredDebugMessage(const char *message)
114{
115 for (const char *msg : kSkippedMessages)
116 {
117 if (strstr(message, msg) != nullptr)
118 {
119 return true;
120 }
121 }
122 return false;
123}
124
125const char *GetVkObjectTypeName(VkObjectType type)
126{
127 switch (type)
128 {
129 case VK_OBJECT_TYPE_UNKNOWN:
130 return "Unknown";
131 case VK_OBJECT_TYPE_INSTANCE:
132 return "Instance";
133 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
134 return "Physical Device";
135 case VK_OBJECT_TYPE_DEVICE:
136 return "Device";
137 case VK_OBJECT_TYPE_QUEUE:
138 return "Queue";
139 case VK_OBJECT_TYPE_SEMAPHORE:
140 return "Semaphore";
141 case VK_OBJECT_TYPE_COMMAND_BUFFER:
142 return "Command Buffer";
143 case VK_OBJECT_TYPE_FENCE:
144 return "Fence";
145 case VK_OBJECT_TYPE_DEVICE_MEMORY:
146 return "Device Memory";
147 case VK_OBJECT_TYPE_BUFFER:
148 return "Buffer";
149 case VK_OBJECT_TYPE_IMAGE:
150 return "Image";
151 case VK_OBJECT_TYPE_EVENT:
152 return "Event";
153 case VK_OBJECT_TYPE_QUERY_POOL:
154 return "Query Pool";
155 case VK_OBJECT_TYPE_BUFFER_VIEW:
156 return "Buffer View";
157 case VK_OBJECT_TYPE_IMAGE_VIEW:
158 return "Image View";
159 case VK_OBJECT_TYPE_SHADER_MODULE:
160 return "Shader Module";
161 case VK_OBJECT_TYPE_PIPELINE_CACHE:
162 return "Pipeline Cache";
163 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
164 return "Pipeline Layout";
165 case VK_OBJECT_TYPE_RENDER_PASS:
166 return "Render Pass";
167 case VK_OBJECT_TYPE_PIPELINE:
168 return "Pipeline";
169 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
170 return "Descriptor Set Layout";
171 case VK_OBJECT_TYPE_SAMPLER:
172 return "Sampler";
173 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
174 return "Descriptor Pool";
175 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
176 return "Descriptor Set";
177 case VK_OBJECT_TYPE_FRAMEBUFFER:
178 return "Framebuffer";
179 case VK_OBJECT_TYPE_COMMAND_POOL:
180 return "Command Pool";
181 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
182 return "Sampler YCbCr Conversion";
183 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
184 return "Descriptor Update Template";
185 case VK_OBJECT_TYPE_SURFACE_KHR:
186 return "Surface";
187 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
188 return "Swapchain";
189 case VK_OBJECT_TYPE_DISPLAY_KHR:
190 return "Display";
191 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
192 return "Display Mode";
193 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
194 return "Debug Report Callback";
195 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
196 return "Object Table";
197 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
198 return "Indirect Commands Layout";
199 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
200 return "Debug Utils Messenger";
201 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
202 return "Validation Cache";
203 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
204 return "Acceleration Structure";
205 default:
206 return "<Unrecognized>";
207 }
208}
209
210VKAPI_ATTR VkBool32 VKAPI_CALL
211DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
212 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
213 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
214 void *userData)
215{
216 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
217 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
218 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
219
220 // Check if we even care about this message.
221 if ((messageSeverity & kSeveritiesToLog) == 0)
222 {
223 return VK_FALSE;
224 }
225
226 // See if it's an issue we are aware of and don't want to be spammed about.
227 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
228 {
229 return VK_FALSE;
230 }
231
232 std::ostringstream log;
233 log << "[ " << callbackData->pMessageIdName << " ] " << callbackData->pMessage << std::endl;
234
235 // Aesthetic value based on length of the function name, line number, etc.
236 constexpr size_t kStartIndent = 28;
237
238 // Output the debug marker hierarchy under which this error has occured.
239 size_t indent = kStartIndent;
240 if (callbackData->queueLabelCount > 0)
241 {
242 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
243 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
244 {
245 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
246 << std::endl;
247 }
248 }
249 if (callbackData->cmdBufLabelCount > 0)
250 {
251 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
252 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
253 {
254 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
255 << std::endl;
256 }
257 }
258 // Output the objects involved in this error message.
259 if (callbackData->objectCount > 0)
260 {
261 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
262 {
263 const char *objectName = callbackData->pObjects[i].pObjectName;
264 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
265 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
266 log << std::string(indent, ' ') << "Object: ";
267 if (objectHandle == 0)
268 {
269 log << "VK_NULL_HANDLE";
270 }
271 else
272 {
273 log << "0x" << std::hex << objectHandle << std::dec;
274 }
275 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
276 if (objectName)
277 {
278 log << " [" << objectName << "]";
279 }
280 log << std::endl;
281 }
282 }
283
284 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
285
286 if (isError)
287 {
288 ERR() << log.str();
289 }
290 else
291 {
292 WARN() << log.str();
293 }
294
295 return VK_FALSE;
296}
297
Yuly Novikov199f4292018-01-19 19:04:05 -0500298VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
299 VkDebugReportObjectTypeEXT objectType,
300 uint64_t object,
301 size_t location,
302 int32_t messageCode,
303 const char *layerPrefix,
304 const char *message,
305 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500306{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600307 if (IsIgnoredDebugMessage(message))
308 {
309 return VK_FALSE;
310 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500311 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
312 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500313 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500314#if !defined(NDEBUG)
315 // Abort the call in Debug builds.
316 return VK_TRUE;
317#endif
318 }
319 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
320 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500321 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500322 }
323 else
324 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500325 // Uncomment this if you want Vulkan spam.
326 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500327 }
328
329 return VK_FALSE;
330}
331
Yuly Novikov199f4292018-01-19 19:04:05 -0500332// If we're loading the validation layers, we could be running from any random directory.
333// Change to the executable directory so we can find the layers, then change back to the
334// previous directory to be safe we don't disrupt the application.
335class ScopedVkLoaderEnvironment : angle::NonCopyable
336{
337 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600338 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
339 : mEnableValidationLayers(enableValidationLayers),
340 mEnableMockICD(enableMockICD),
341 mChangedCWD(false),
342 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500343 {
344// Changing CWD and setting environment variables makes no sense on Android,
345// since this code is a part of Java application there.
346// Android Vulkan loader doesn't need this either.
347#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600348 if (enableMockICD)
349 {
350 // Override environment variable to use built Mock ICD
351 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
352 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
353 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
354 if (!mChangedICDPath)
355 {
356 ERR() << "Error setting Path for Mock/Null Driver.";
357 mEnableMockICD = false;
358 }
359 }
Jamie Madill46848422018-08-09 10:46:06 -0400360 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500361 {
362 const auto &cwd = angle::GetCWD();
363 if (!cwd.valid())
364 {
365 ERR() << "Error getting CWD for Vulkan layers init.";
366 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400367 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500368 }
369 else
370 {
371 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500372 std::string exeDir = angle::GetExecutableDirectory();
373 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500374 if (!mChangedCWD)
375 {
376 ERR() << "Error setting CWD for Vulkan layers init.";
377 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400378 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500379 }
380 }
381 }
382
383 // Override environment variable to use the ANGLE layers.
384 if (mEnableValidationLayers)
385 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700386 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500387 {
388 ERR() << "Error setting environment for Vulkan layers init.";
389 mEnableValidationLayers = false;
390 }
391 }
392#endif // !defined(ANGLE_PLATFORM_ANDROID)
393 }
394
395 ~ScopedVkLoaderEnvironment()
396 {
397 if (mChangedCWD)
398 {
399#if !defined(ANGLE_PLATFORM_ANDROID)
400 ASSERT(mPreviousCWD.valid());
401 angle::SetCWD(mPreviousCWD.value().c_str());
402#endif // !defined(ANGLE_PLATFORM_ANDROID)
403 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600404 if (mChangedICDPath)
405 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600406 if (mPreviousICDPath.value().empty())
407 {
408 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
409 }
410 else
411 {
412 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
413 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600414 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500415 }
416
Jamie Madillaaca96e2018-06-12 10:19:48 -0400417 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500418
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600419 bool canEnableMockICD() const { return mEnableMockICD; }
420
Yuly Novikov199f4292018-01-19 19:04:05 -0500421 private:
422 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600423 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500424 bool mChangedCWD;
425 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool mChangedICDPath;
427 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500428};
429
Jamie Madill21061022018-07-12 23:56:30 -0400430void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
431 bool preferMockICD,
432 VkPhysicalDevice *physicalDeviceOut,
433 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
434{
435 ASSERT(!physicalDevices.empty());
436 if (preferMockICD)
437 {
438 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
439 {
440 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
441 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
442 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
443 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
444 {
445 *physicalDeviceOut = physicalDevice;
446 return;
447 }
448 }
449 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
450 "physicalDevice instead.";
451 }
452
453 // Fall back to first device.
454 *physicalDeviceOut = physicalDevices[0];
455 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
456}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400457
458// Initially dumping the command graphs is disabled.
459constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700460
Jamie Madille09bd5d2016-11-29 16:20:35 -0500461} // anonymous namespace
462
Jamie Madill49ac74b2017-12-21 14:42:33 -0500463// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400464RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500465
Jamie Madillaaca96e2018-06-12 10:19:48 -0400466RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500467
468RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
469 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500470{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500471
472RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
473{
474 std::swap(commandPool, other.commandPool);
475 std::swap(fence, other.fence);
476 std::swap(serial, other.serial);
477 return *this;
478}
479
Jamie Madillbea35a62018-07-05 11:54:10 -0400480void RendererVk::CommandBatch::destroy(VkDevice device)
481{
482 commandPool.destroy(device);
483 fence.destroy(device);
484}
485
Jamie Madill9f2a8612017-11-30 12:43:09 -0500486// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500487RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400488 : mDisplay(nullptr),
489 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700490 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500491 mInstance(VK_NULL_HANDLE),
492 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400493 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500494 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500495 mDebugReportCallback(VK_NULL_HANDLE),
496 mPhysicalDevice(VK_NULL_HANDLE),
497 mQueue(VK_NULL_HANDLE),
498 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
499 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400500 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400501 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400502 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400503 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400504 mCommandGraph(kEnableCommandGraphDiagnostics),
505 mGpuEventsEnabled(false),
506 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
507 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500508{
509 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
510 mFormatProperties.fill(invalid);
511}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400512
Jamie Madillb980c562018-11-27 11:34:27 -0500513RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400514
515void RendererVk::onDestroy(vk::Context *context)
516{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500517 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500518 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500519 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400520 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500521 }
522
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100523 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500524
Jamie Madillc7918ce2018-06-13 13:25:31 -0400525 mPipelineLayoutCache.destroy(mDevice);
526 mDescriptorSetLayoutCache.destroy(mDevice);
527
Jamie Madill9f2a8612017-11-30 12:43:09 -0500528 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500529 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400530 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400531 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400532 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500533
Jamie Madill06ca6342018-07-12 15:56:53 -0400534 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500535
Jamie Madill5deea722017-02-16 10:44:46 -0500536 if (mCommandPool.valid())
537 {
538 mCommandPool.destroy(mDevice);
539 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500540
541 if (mDevice)
542 {
543 vkDestroyDevice(mDevice, nullptr);
544 mDevice = VK_NULL_HANDLE;
545 }
546
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500547 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500548 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500549 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
550 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
551
552 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
553 }
554 else if (mDebugReportCallback)
555 {
556 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
557 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500558 }
559
Jamie Madill4d0bf552016-12-28 15:45:24 -0500560 if (mInstance)
561 {
562 vkDestroyInstance(mInstance, nullptr);
563 mInstance = VK_NULL_HANDLE;
564 }
565
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600566 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500568}
569
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400570void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400571{
572 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400573
574 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500575 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400576 freeAllInFlightResources();
577
578 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400579}
580
581bool RendererVk::isDeviceLost() const
582{
583 return mDeviceLost;
584}
585
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400586angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400587 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400588 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500589{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400590 mDisplay = display;
591 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600592 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
593 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500594 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400595 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500596
Jamie Madill0448ec82016-12-23 13:41:47 -0500597 // Gather global layer properties.
598 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400599 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500600
601 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
602 if (instanceLayerCount > 0)
603 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400604 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
605 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500606 }
607
Jamie Madille09bd5d2016-11-29 16:20:35 -0500608 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400609 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400610 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500611
612 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
613 if (instanceExtensionCount > 0)
614 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400615 ANGLE_VK_TRY(displayVk,
616 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
617 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500618 }
619
Yuly Novikov199f4292018-01-19 19:04:05 -0500620 const char *const *enabledLayerNames = nullptr;
621 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500622 if (mEnableValidationLayers)
623 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500624 bool layersRequested =
625 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
626 mEnableValidationLayers = GetAvailableValidationLayers(
627 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500628 }
629
Jamie Madille09bd5d2016-11-29 16:20:35 -0500630 std::vector<const char *> enabledInstanceExtensions;
631 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500632 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500633
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500634 bool enableDebugUtils =
635 mEnableValidationLayers &&
636 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
637 bool enableDebugReport =
638 mEnableValidationLayers && !enableDebugUtils &&
639 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
640
641 if (enableDebugUtils)
642 {
643 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
644 }
645 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500646 {
647 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
648 }
649
Jamie Madille09bd5d2016-11-29 16:20:35 -0500650 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400651 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400652 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500653
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400654 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500655 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500656 applicationInfo.pApplicationName = "ANGLE";
657 applicationInfo.applicationVersion = 1;
658 applicationInfo.pEngineName = "ANGLE";
659 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700660
661 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
662 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
663 if (!enumerateInstanceVersion)
664 {
665 applicationInfo.apiVersion = VK_API_VERSION_1_0;
666 }
667 else
668 {
669 uint32_t apiVersion = VK_API_VERSION_1_0;
670 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
671 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
672 {
673 // Note: will need to revisit this with Vulkan 1.2+.
674 applicationInfo.apiVersion = VK_API_VERSION_1_1;
675 }
676 else
677 {
678 applicationInfo.apiVersion = VK_API_VERSION_1_0;
679 }
680 }
Jamie Madill327ba852016-11-30 12:38:28 -0500681
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400682 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500683 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
684 instanceInfo.flags = 0;
685 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500686
Jamie Madille09bd5d2016-11-29 16:20:35 -0500687 // Enable requested layers and extensions.
688 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
689 instanceInfo.ppEnabledExtensionNames =
690 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500691 instanceInfo.enabledLayerCount = enabledLayerCount;
692 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500693
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400694 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500695
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500696 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500697 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500698 // Try to use the newer EXT_debug_utils if it exists.
699 InitDebugUtilsEXTFunctions(mInstance);
700
701 // Create the messenger callback.
702 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
703
704 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
705 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
706 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
707 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
708 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
709 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
710 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
711 messengerInfo.pUserData = this;
712
713 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
714 &mDebugUtilsMessenger));
715 }
716 else if (enableDebugReport)
717 {
718 // Fallback to EXT_debug_report.
719 InitDebugReportEXTFunctions(mInstance);
720
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400721 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500722
723 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500724 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500725 debugReportInfo.pfnCallback = &DebugReportCallback;
726 debugReportInfo.pUserData = this;
727
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500728 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
729 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500730 }
731
Jamie Madill4d0bf552016-12-28 15:45:24 -0500732 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400733 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
734 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500735
736 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700737 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400738 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
739 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400740 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700741 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500742
Jamie Madill30b5d842018-08-31 17:19:12 -0400743 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
744
Jamie Madill4d0bf552016-12-28 15:45:24 -0500745 // Ensure we can find a graphics queue family.
746 uint32_t queueCount = 0;
747 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
748
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400749 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500750
751 mQueueFamilyProperties.resize(queueCount);
752 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
753 mQueueFamilyProperties.data());
754
Jamie Madillb980c562018-11-27 11:34:27 -0500755 size_t graphicsQueueFamilyCount = false;
756 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500757 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500758 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
759 {
760 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500761 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500762 {
763 ASSERT(queueInfo.queueCount > 0);
764 graphicsQueueFamilyCount++;
765 if (firstGraphicsQueueFamily == 0)
766 {
767 firstGraphicsQueueFamily = familyIndex;
768 }
769 break;
770 }
771 }
772
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400773 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500774
775 // If only one queue family, go ahead and initialize the device. If there is more than one
776 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
777 if (graphicsQueueFamilyCount == 1)
778 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400779 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500780 }
781
Jamie Madill035fd6b2017-10-03 15:43:22 -0400782 // Store the physical device memory properties so we can find the right memory pools.
783 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500784
Jamie Madill06ca6342018-07-12 15:56:53 -0400785 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500786
Jamie Madill6a89d222017-11-02 11:59:51 -0400787 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500788 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400789
Jamie Madill7c985f52018-11-29 18:16:17 -0500790 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400791}
792
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400793angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500794{
795 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400796 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400797 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500798
799 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
800 if (deviceLayerCount > 0)
801 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400802 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
803 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500804 }
805
806 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400807 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
808 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500809
810 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
811 if (deviceExtensionCount > 0)
812 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400813 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
814 &deviceExtensionCount,
815 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500816 }
817
Yuly Novikov199f4292018-01-19 19:04:05 -0500818 const char *const *enabledLayerNames = nullptr;
819 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500820 if (mEnableValidationLayers)
821 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500822 mEnableValidationLayers = GetAvailableValidationLayers(
823 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500824 }
825
826 std::vector<const char *> enabledDeviceExtensions;
827 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
828
Ian Elliottbcb78902018-12-19 11:46:29 -0700829 initFeatures(deviceExtensionProps);
830 mFeaturesInitialized = true;
831
Luc Ferronbf6dc372018-06-28 15:24:19 -0400832 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700833 if ((getFeatures().flipViewportY) &&
834 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400835 {
836 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
837 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700838 if (getFeatures().supportsIncrementalPresent)
839 {
840 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
841 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400842
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400843 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500844
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400845 // Select additional features to be enabled
846 VkPhysicalDeviceFeatures enabledFeatures = {};
847 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500848 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400849
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400850 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500851
852 float zeroPriority = 0.0f;
853
854 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500855 queueCreateInfo.flags = 0;
856 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
857 queueCreateInfo.queueCount = 1;
858 queueCreateInfo.pQueuePriorities = &zeroPriority;
859
860 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400861 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862
Jamie Madill50cf2be2018-06-15 09:46:57 -0400863 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400864 createInfo.flags = 0;
865 createInfo.queueCreateInfoCount = 1;
866 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500867 createInfo.enabledLayerCount = enabledLayerCount;
868 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500869 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
870 createInfo.ppEnabledExtensionNames =
871 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400872 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400874 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500875
876 mCurrentQueueFamilyIndex = queueFamilyIndex;
877
878 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
879
880 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400881 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500882 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
883 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
884 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500885
Yuly Novikov27780292018-11-09 11:19:49 -0500886 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400887
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400888 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500889 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500890
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400891 // Initialize the submission semaphore pool.
892 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
893
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400894#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
895 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
896 ASSERT(platform);
897
898 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
899 // platform discovery.
900 const unsigned char *gpuEventsEnabled =
901 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
902 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
903#endif
904
905 if (mGpuEventsEnabled)
906 {
907 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
908 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
909 vk::kDefaultTimestampQueryPoolSize));
910 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
911 }
912
Jamie Madill7c985f52018-11-29 18:16:17 -0500913 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500914}
915
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400916angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400917 VkSurfaceKHR surface,
918 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500919{
920 // We've already initialized a device, and can't re-create it unless it's never been used.
921 // TODO(jmadill): Handle the re-creation case if necessary.
922 if (mDevice != VK_NULL_HANDLE)
923 {
924 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
925
926 // Check if the current device supports present on this surface.
927 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400928 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400929 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500930 surface, &supportsPresent));
931
Jamie Madill6cad7732018-07-11 09:01:17 -0400932 if (supportsPresent == VK_TRUE)
933 {
934 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500935 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400936 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500937 }
938
939 // Find a graphics and present queue.
940 Optional<uint32_t> newPresentQueue;
941 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500942 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500943 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
944 {
945 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500946 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500947 {
948 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400949 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
950 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500951
952 if (supportsPresent == VK_TRUE)
953 {
954 newPresentQueue = queueIndex;
955 break;
956 }
957 }
958 }
959
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400960 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
961 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500962
Jamie Madill6cad7732018-07-11 09:01:17 -0400963 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500964 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500965}
966
967std::string RendererVk::getVendorString() const
968{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300969 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500970}
971
Jamie Madille09bd5d2016-11-29 16:20:35 -0500972std::string RendererVk::getRendererDescription() const
973{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500974 std::stringstream strstr;
975
976 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
977
978 strstr << "Vulkan ";
979 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
980 strstr << VK_VERSION_MINOR(apiVersion) << ".";
981 strstr << VK_VERSION_PATCH(apiVersion);
982
Olli Etuahoc6a06182018-04-13 14:11:46 +0300983 strstr << "(";
984
985 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
986 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
987 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
988 // driver detection.
989 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
990 {
991 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
992 }
993
Geoff Langa7af56b2018-12-14 14:20:28 -0500994 strstr << mPhysicalDeviceProperties.deviceName;
995 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
996
997 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500998
999 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001000}
1001
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001002gl::Version RendererVk::getMaxSupportedESVersion() const
1003{
1004 // Declare GLES2 support if necessary features for GLES3 are missing
1005 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
1006
1007 if (!necessaryFeaturesForES3)
1008 {
1009 return gl::Version(2, 0);
1010 }
1011
1012 return gl::Version(3, 0);
1013}
1014
Ian Elliottbcb78902018-12-19 11:46:29 -07001015void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001016{
Jamie Madillb36a4812018-09-25 10:15:11 -04001017// Use OpenGL line rasterization rules by default.
1018// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1019#if defined(ANGLE_PLATFORM_ANDROID)
1020 mFeatures.basicGLLineRasterization = false;
1021#else
Jamie Madill12222072018-07-11 14:59:48 -04001022 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001023#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001024
Ian Elliott52f5da42018-12-21 09:02:09 -07001025 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1026 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001027 {
1028 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1029 // investigation. http://anglebug.com/2728
1030 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1031 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001032
1033#ifdef ANGLE_PLATFORM_WINDOWS
1034 // http://anglebug.com/2838
1035 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001036
1037 // http://anglebug.com/3055
1038 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001039#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001040
1041 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1042 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001043
1044 // Work around incorrect NVIDIA point size range clamping.
1045 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1046 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1047 {
1048 mFeatures.clampPointSize = true;
1049 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001050
1051#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001052 // Work around ineffective compute-graphics barriers on Nexus 5X.
1053 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1054 // http://anglebug.com/3019
1055 mFeatures.flushAfterVertexConversion =
1056 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001057#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001058
1059 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1060 {
1061 mFeatures.supportsIncrementalPresent = true;
1062 }
Jamie Madill12222072018-07-11 14:59:48 -04001063}
1064
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001065void RendererVk::initPipelineCacheVkKey()
1066{
1067 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1068 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1069 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1070 // there is no '\0' in the result.
1071 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1072 {
1073 hashStream << std::hex << c;
1074 }
1075 // Add the vendor and device id too for good measure.
1076 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1077 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1078
1079 const std::string &hashString = hashStream.str();
1080 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1081 hashString.length(), mPipelineCacheVkBlobKey.data());
1082}
1083
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001084angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001085{
1086 initPipelineCacheVkKey();
1087
1088 egl::BlobCache::Value initialData;
1089 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1090 mPipelineCacheVkBlobKey, &initialData);
1091
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001092 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001093
1094 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001095 pipelineCacheCreateInfo.flags = 0;
1096 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1097 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1098
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001099 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001100 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001101}
1102
Jamie Madillacccc6c2016-05-03 17:22:10 -04001103void RendererVk::ensureCapsInitialized() const
1104{
1105 if (!mCapsInitialized)
1106 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001107 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1108 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1109 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001110 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001111 mCapsInitialized = true;
1112 }
1113}
1114
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001115void RendererVk::getSubmitWaitSemaphores(
1116 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001117 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1118 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001119{
1120 if (mSubmitLastSignaledSemaphore.getSemaphore())
1121 {
1122 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001123 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001124
1125 // Return the semaphore to the pool (which will remain valid and unused until the
1126 // queue it's about to be waited on has finished execution).
1127 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1128 }
1129
1130 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1131 {
1132 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001133 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1134
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001135 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1136 }
1137 mSubmitWaitSemaphores.clear();
1138}
1139
Jamie Madillacccc6c2016-05-03 17:22:10 -04001140const gl::Caps &RendererVk::getNativeCaps() const
1141{
1142 ensureCapsInitialized();
1143 return mNativeCaps;
1144}
1145
1146const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1147{
1148 ensureCapsInitialized();
1149 return mNativeTextureCaps;
1150}
1151
1152const gl::Extensions &RendererVk::getNativeExtensions() const
1153{
1154 ensureCapsInitialized();
1155 return mNativeExtensions;
1156}
1157
1158const gl::Limitations &RendererVk::getNativeLimitations() const
1159{
1160 ensureCapsInitialized();
1161 return mNativeLimitations;
1162}
1163
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001164uint32_t RendererVk::getMaxActiveTextures()
1165{
1166 // TODO(lucferron): expose this limitation to GL in Context Caps
1167 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1168 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1169}
1170
Jamie Madill49ac74b2017-12-21 14:42:33 -05001171const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001172{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001173 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001174}
1175
Jamie Madill21061022018-07-12 23:56:30 -04001176angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001177{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001178 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001179 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001180 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1181
Luc Ferron1617e692018-07-11 11:08:19 -04001182 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1183 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001184
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001185 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001186 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1187 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001188
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001189 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001190 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001191 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1192 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001193 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001194 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001195 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001196 submitInfo.signalSemaphoreCount = 0;
1197 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001198
Jamie Madill21061022018-07-12 23:56:30 -04001199 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001200 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001201
Jamie Madill4c26fc22017-02-24 11:04:10 -05001202 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001203 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001204 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001205
1206 if (mGpuEventsEnabled)
1207 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001208 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001209 while (mInFlightGpuEventQueries.size() > 0)
1210 {
1211 ANGLE_TRY(checkCompletedGpuEvents(context));
1212 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001213 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1214 // synchronization if there is no event to be adjusted (happens when finish() gets called
1215 // multiple times towards the end of the application).
1216 if (mGpuEvents.size() > 0)
1217 {
1218 ANGLE_TRY(synchronizeCpuGpuTime(context));
1219 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001220 }
1221
Jamie Madill7c985f52018-11-29 18:16:17 -05001222 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001223}
1224
Jamie Madill0c0dc342017-03-24 14:18:51 -04001225void RendererVk::freeAllInFlightResources()
1226{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001227 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001228 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001229 // On device loss we need to wait for fence to be signaled before destroying it
1230 if (mDeviceLost)
1231 {
1232 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1233 // If wait times out, it is probably not possible to recover from lost device
1234 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1235 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001236 batch.fence.destroy(mDevice);
1237 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001238 }
1239 mInFlightCommands.clear();
1240
1241 for (auto &garbage : mGarbage)
1242 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001243 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001244 }
1245 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001246
1247 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001248}
1249
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001250angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001251{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001252 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001253
Jamie Madill49ac74b2017-12-21 14:42:33 -05001254 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001255 {
Yuly Novikov27780292018-11-09 11:19:49 -05001256 VkResult result = batch.fence.getStatus(mDevice);
1257 if (result == VK_NOT_READY)
1258 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001259 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001260 }
1261 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001262
Jamie Madill49ac74b2017-12-21 14:42:33 -05001263 ASSERT(batch.serial > mLastCompletedQueueSerial);
1264 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001265
Jamie Madill49ac74b2017-12-21 14:42:33 -05001266 batch.fence.destroy(mDevice);
1267 batch.commandPool.destroy(mDevice);
1268 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001269 }
1270
Jamie Madill49ac74b2017-12-21 14:42:33 -05001271 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001272
1273 size_t freeIndex = 0;
1274 for (; freeIndex < mGarbage.size(); ++freeIndex)
1275 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001276 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001277 break;
1278 }
1279
1280 // Remove the entries from the garbage list - they should be ready to go.
1281 if (freeIndex > 0)
1282 {
1283 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001284 }
1285
Jamie Madill7c985f52018-11-29 18:16:17 -05001286 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001287}
1288
Jamie Madill21061022018-07-12 23:56:30 -04001289angle::Result RendererVk::submitFrame(vk::Context *context,
1290 const VkSubmitInfo &submitInfo,
1291 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001292{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001293 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001294 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001295 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1296 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001297
Jamie Madillbea35a62018-07-05 11:54:10 -04001298 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1299 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001300 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001301
Jamie Madill21061022018-07-12 23:56:30 -04001302 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001303
1304 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001305 batch.commandPool = std::move(mCommandPool);
1306 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001307
Jamie Madillbea35a62018-07-05 11:54:10 -04001308 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001309
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001310 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1311 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001312 // so the limit is larger than the expected number of images. The
1313 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001314 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001315
Jamie Madill85ca1892019-01-16 13:27:15 -05001316 nextSerial();
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 Madill85ca1892019-01-16 13:27:15 -05001339void RendererVk::nextSerial()
1340{
1341 // Increment the queue serial. If this fails, we should restart ANGLE.
1342 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1343 mCurrentQueueSerial = mQueueSerialFactory.generate();
1344
1345 // Notify the Contexts that they should be starting new command buffers.
1346 // We use one command pool per serial/submit associated with this VkQueue. We can also
1347 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1348 // check for a new serial when starting a new command buffer. We just check that the current
1349 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1350 // using this VkQueue that they their current command buffer is no longer valid.
1351 for (gl::Context *context : mDisplay->getContextSet())
1352 {
1353 ContextVk *contextVk = vk::GetImpl(context);
1354 contextVk->onCommandBufferFinished();
1355 }
1356}
1357
Jamie Madillaaca96e2018-06-12 10:19:48 -04001358bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001359{
1360 return serial > mLastCompletedQueueSerial;
1361}
1362
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001363angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1364{
1365 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1366 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001367 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001368 }
1369
1370 // Find the first batch with serial equal to or bigger than given serial (note that
1371 // the batch serials are unique, otherwise upper-bound would have been necessary).
1372 size_t batchIndex = mInFlightCommands.size() - 1;
1373 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1374 {
1375 if (mInFlightCommands[i].serial >= serial)
1376 {
1377 batchIndex = i;
1378 break;
1379 }
1380 }
1381 const CommandBatch &batch = mInFlightCommands[batchIndex];
1382
1383 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001384 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001385
1386 // Clean up finished batches.
1387 return checkCompletedCommands(context);
1388}
1389
Jamie Madill21061022018-07-12 23:56:30 -04001390angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1391 const vk::RenderPassDesc &desc,
1392 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001393{
Jamie Madill21061022018-07-12 23:56:30 -04001394 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001395 renderPassOut);
1396}
1397
Jamie Madill21061022018-07-12 23:56:30 -04001398angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1399 const vk::RenderPassDesc &desc,
1400 const vk::AttachmentOpsArray &ops,
1401 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001402{
Jamie Madill21061022018-07-12 23:56:30 -04001403 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001404 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001405}
1406
Jamie Madilla5e06072018-05-18 14:36:05 -04001407vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001408{
Jamie Madilla5e06072018-05-18 14:36:05 -04001409 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001410}
1411
Jamie Madill21061022018-07-12 23:56:30 -04001412angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001413{
Jamie Madill21061022018-07-12 23:56:30 -04001414 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001415 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001416}
1417
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001418angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001419{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001420 if (mCommandGraph.empty())
1421 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001422 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001423 }
1424
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001425 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1426
Jamie Madillbea35a62018-07-05 11:54:10 -04001427 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1428 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001429
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001430 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001431 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1432 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001433
1434 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1435 // will be waited on.
1436 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001437
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001438 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001439 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001440 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1441 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001442 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001443 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001444 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001445 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001446 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001447
Jamie Madill21061022018-07-12 23:56:30 -04001448 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001449
Jamie Madill7c985f52018-11-29 18:16:17 -05001450 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001451}
1452
Jamie Madill78feddc2018-04-27 11:45:05 -04001453Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001454{
Jamie Madill78feddc2018-04-27 11:45:05 -04001455 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001456}
1457
Jamie Madill21061022018-07-12 23:56:30 -04001458angle::Result RendererVk::getDescriptorSetLayout(
1459 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001460 const vk::DescriptorSetLayoutDesc &desc,
1461 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1462{
Jamie Madill21061022018-07-12 23:56:30 -04001463 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001464}
1465
Jamie Madill21061022018-07-12 23:56:30 -04001466angle::Result RendererVk::getPipelineLayout(
1467 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001468 const vk::PipelineLayoutDesc &desc,
1469 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1470 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1471{
Jamie Madill21061022018-07-12 23:56:30 -04001472 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001473 pipelineLayoutOut);
1474}
1475
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001476angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1477{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001478 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001479
1480 if (--mPipelineCacheVkUpdateTimeout > 0)
1481 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001482 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001483 }
1484
1485 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1486
1487 // Get the size of the cache.
1488 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001489 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001490 if (result != VK_INCOMPLETE)
1491 {
1492 ANGLE_VK_TRY(displayVk, result);
1493 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001494
1495 angle::MemoryBuffer *pipelineCacheData = nullptr;
1496 ANGLE_VK_CHECK_ALLOC(displayVk,
1497 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1498
1499 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001500 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001501 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1502 // was determined just above), so receiving it hints at an implementation bug we would want
1503 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001504 ASSERT(result != VK_INCOMPLETE);
1505 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001506
1507 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1508 // the buffer to avoid leaking garbage memory.
1509 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1510 if (pipelineCacheSize < originalPipelineCacheSize)
1511 {
1512 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1513 originalPipelineCacheSize - pipelineCacheSize);
1514 }
1515
1516 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1517
Jamie Madill7c985f52018-11-29 18:16:17 -05001518 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001519}
1520
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001521angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1522 const vk::Semaphore **outSemaphore)
1523{
1524 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1525
1526 vk::SemaphoreHelper semaphore;
1527 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1528
1529 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1530 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1531
Jamie Madill7c985f52018-11-29 18:16:17 -05001532 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001533}
1534
1535const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1536{
1537 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1538
1539 // Return the semaphore to the pool (which will remain valid and unused until the
1540 // queue it's about to be waited on has finished execution). The caller is about
1541 // to wait on it.
1542 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1543
1544 return semaphore;
1545}
1546
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001547angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1548{
1549 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1550 // that seems impossible, so instead, we are going to make a small submission with just a
1551 // timestamp query. First, the disjoint timer query extension says:
1552 //
1553 // > This will return the GL time after all previous commands have reached the GL server but
1554 // have not yet necessarily executed.
1555 //
1556 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1557 // The wording allows us to make a submission to get the timestamp without performing a flush.
1558 //
1559 // Second:
1560 //
1561 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1562 // object target, applications can measure the latency between when commands reach the GL server
1563 // and when they are realized in the framebuffer.
1564 //
1565 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1566 // GPU bubble. This function directly generates a command buffer and submits it instead of
1567 // using the other member functions. This is to avoid changing any state, such as the queue
1568 // serial.
1569
1570 // Create a query used to receive the GPU timestamp
1571 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1572 vk::QueryHelper timestampQuery;
1573 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1574 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1575
1576 // Record the command buffer
1577 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1578 vk::CommandBuffer &commandBuffer = commandBatch.get();
1579
1580 VkCommandBufferAllocateInfo commandBufferInfo = {};
1581 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1582 commandBufferInfo.commandPool = mCommandPool.getHandle();
1583 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1584 commandBufferInfo.commandBufferCount = 1;
1585
Yuly Novikov27780292018-11-09 11:19:49 -05001586 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001587
1588 VkCommandBufferBeginInfo beginInfo = {};
1589 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1590 beginInfo.flags = 0;
1591 beginInfo.pInheritanceInfo = nullptr;
1592
Yuly Novikov27780292018-11-09 11:19:49 -05001593 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001594
1595 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1596 timestampQuery.getQuery(), 1);
1597 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1598 timestampQuery.getQueryPool()->getHandle(),
1599 timestampQuery.getQuery());
1600
Yuly Novikov27780292018-11-09 11:19:49 -05001601 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001602
1603 // Create fence for the submission
1604 VkFenceCreateInfo fenceInfo = {};
1605 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1606 fenceInfo.flags = 0;
1607
1608 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001609 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001610
1611 // Submit the command buffer
1612 VkSubmitInfo submitInfo = {};
1613 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1614 submitInfo.waitSemaphoreCount = 0;
1615 submitInfo.pWaitSemaphores = nullptr;
1616 submitInfo.pWaitDstStageMask = nullptr;
1617 submitInfo.commandBufferCount = 1;
1618 submitInfo.pCommandBuffers = commandBuffer.ptr();
1619 submitInfo.signalSemaphoreCount = 0;
1620 submitInfo.pSignalSemaphores = nullptr;
1621
1622 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1623
1624 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1625 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001626 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001627
1628 // Get the query results
1629 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1630
Yuly Novikov27780292018-11-09 11:19:49 -05001631 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1632 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1633 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001634
1635 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1636
Jamie Madill7c985f52018-11-29 18:16:17 -05001637 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001638}
1639
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001640// These functions look at the mandatory format for support, and fallback to querying the device (if
1641// necessary) to test the availability of the bits.
1642bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1643 const VkFormatFeatureFlags featureBits)
1644{
1645 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1646}
1647
1648bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1649 const VkFormatFeatureFlags featureBits)
1650{
1651 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1652}
1653
1654bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1655{
1656 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1657}
1658
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001659angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1660{
1661 ASSERT(mGpuEventsEnabled);
1662
1663 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1664 ASSERT(platform);
1665
1666 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1667 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1668 //
1669 // CPU GPU
1670 //
1671 // Record command buffer
1672 // with timestamp query
1673 //
1674 // Submit command buffer
1675 //
1676 // Post-submission work Begin execution
1677 //
1678 // ???? Write timstamp Tgpu
1679 //
1680 // ???? End execution
1681 //
1682 // ???? Return query results
1683 //
1684 // ????
1685 //
1686 // Get query results
1687 //
1688 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1689 // finished post-submission work while the GPU is executing in parallel. With no further work,
1690 // querying CPU timestamps before submission and after getting query results give the bounds to
1691 // Tgpu, which could be quite large.
1692 //
1693 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1694 // reduce this range. This function implements the following procedure:
1695 //
1696 // CPU GPU
1697 //
1698 // Record command buffer
1699 // with timestamp query
1700 //
1701 // Submit command buffer
1702 //
1703 // Post-submission work Begin execution
1704 //
1705 // ???? Set Event GPUReady
1706 //
1707 // Wait on Event GPUReady Wait on Event CPUReady
1708 //
1709 // Get CPU Time Ts Wait on Event CPUReady
1710 //
1711 // Set Event CPUReady Wait on Event CPUReady
1712 //
1713 // Get CPU Time Tcpu Get GPU Time Tgpu
1714 //
1715 // Wait on Event GPUDone Set Event GPUDone
1716 //
1717 // Get CPU Time Te End Execution
1718 //
1719 // Idle Return query results
1720 //
1721 // Get query results
1722 //
1723 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1724 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1725 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1726 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1727 // calibration.
1728 //
1729 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1730
1731 // Make sure nothing is running
1732 ASSERT(mCommandGraph.empty());
1733
1734 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1735
1736 // Create a query used to receive the GPU timestamp
1737 vk::QueryHelper timestampQuery;
1738 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1739
1740 // Create the three events
1741 VkEventCreateInfo eventCreateInfo = {};
1742 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1743 eventCreateInfo.flags = 0;
1744
1745 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001746 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1747 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1748 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001749
1750 constexpr uint32_t kRetries = 10;
1751
1752 // Time suffixes used are S for seconds and Cycles for cycles
1753 double tightestRangeS = 1e6f;
1754 double TcpuS = 0;
1755 uint64_t TgpuCycles = 0;
1756 for (uint32_t i = 0; i < kRetries; ++i)
1757 {
1758 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001759 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1760 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1761 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001762
1763 // Record the command buffer
1764 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1765 vk::CommandBuffer &commandBuffer = commandBatch.get();
1766
1767 VkCommandBufferAllocateInfo commandBufferInfo = {};
1768 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1769 commandBufferInfo.commandPool = mCommandPool.getHandle();
1770 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1771 commandBufferInfo.commandBufferCount = 1;
1772
Yuly Novikov27780292018-11-09 11:19:49 -05001773 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001774
1775 VkCommandBufferBeginInfo beginInfo = {};
1776 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1777 beginInfo.flags = 0;
1778 beginInfo.pInheritanceInfo = nullptr;
1779
Yuly Novikov27780292018-11-09 11:19:49 -05001780 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001781
1782 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1783 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1784 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1785 nullptr);
1786
1787 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1788 timestampQuery.getQuery(), 1);
1789 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1790 timestampQuery.getQueryPool()->getHandle(),
1791 timestampQuery.getQuery());
1792
1793 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1794
Yuly Novikov27780292018-11-09 11:19:49 -05001795 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001796
1797 // Submit the command buffer
1798 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1799 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1800 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1801
1802 VkSubmitInfo submitInfo = {};
1803 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1804 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1805 submitInfo.pWaitSemaphores = waitSemaphores.data();
1806 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1807 submitInfo.commandBufferCount = 1;
1808 submitInfo.pCommandBuffers = commandBuffer.ptr();
1809 submitInfo.signalSemaphoreCount = 0;
1810 submitInfo.pSignalSemaphores = nullptr;
1811
1812 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1813
1814 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001815 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001816 do
1817 {
Yuly Novikov27780292018-11-09 11:19:49 -05001818 result = gpuReady.get().getStatus(mDevice);
1819 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1820 {
1821 ANGLE_VK_TRY(context, result);
1822 }
1823 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001824
1825 double TsS = platform->monotonicallyIncreasingTime(platform);
1826
1827 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001828 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001829 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1830
1831 // Wait for GPU to be done. Another short busy wait.
1832 do
1833 {
Yuly Novikov27780292018-11-09 11:19:49 -05001834 result = gpuDone.get().getStatus(mDevice);
1835 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1836 {
1837 ANGLE_VK_TRY(context, result);
1838 }
1839 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001840
1841 double TeS = platform->monotonicallyIncreasingTime(platform);
1842
1843 // Get the query results
1844 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1845
1846 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1847
1848 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001849 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1850 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1851 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001852
1853 // Use the first timestamp queried as origin.
1854 if (mGpuEventTimestampOrigin == 0)
1855 {
1856 mGpuEventTimestampOrigin = gpuTimestampCycles;
1857 }
1858
1859 // Take these CPU and GPU timestamps if there is better confidence.
1860 double confidenceRangeS = TeS - TsS;
1861 if (confidenceRangeS < tightestRangeS)
1862 {
1863 tightestRangeS = confidenceRangeS;
1864 TcpuS = cpuTimestampS;
1865 TgpuCycles = gpuTimestampCycles;
1866 }
1867 }
1868
1869 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1870
1871 // timestampPeriod gives nanoseconds/cycle.
1872 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1873 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1874 1'000'000'000.0;
1875
1876 flushGpuEvents(TgpuS, TcpuS);
1877
1878 mGpuClockSync.gpuTimestampS = TgpuS;
1879 mGpuClockSync.cpuTimestampS = TcpuS;
1880
Jamie Madill7c985f52018-11-29 18:16:17 -05001881 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001882}
1883
1884angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1885 vk::CommandBuffer *commandBuffer,
1886 char phase,
1887 const char *name)
1888{
1889 ASSERT(mGpuEventsEnabled);
1890
1891 GpuEventQuery event;
1892
1893 event.name = name;
1894 event.phase = phase;
1895 event.serial = mCurrentQueueSerial;
1896
1897 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1898
1899 commandBuffer->resetQueryPool(
1900 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1901 commandBuffer->writeTimestamp(
1902 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1903 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1904
1905 mInFlightGpuEventQueries.push_back(std::move(event));
1906
Jamie Madill7c985f52018-11-29 18:16:17 -05001907 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001908}
1909
1910angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1911{
1912 ASSERT(mGpuEventsEnabled);
1913
1914 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1915 ASSERT(platform);
1916
1917 int finishedCount = 0;
1918
1919 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1920 {
1921 // Only check the timestamp query if the submission has finished.
1922 if (eventQuery.serial > mLastCompletedQueueSerial)
1923 {
1924 break;
1925 }
1926
1927 // See if the results are available.
1928 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001929 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1930 ->getResults(mDevice, eventQuery.queryIndex, 1,
1931 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1932 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1933 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001934 {
1935 break;
1936 }
Yuly Novikov27780292018-11-09 11:19:49 -05001937 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001938
1939 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1940
1941 GpuEvent event;
1942 event.gpuTimestampCycles = gpuTimestampCycles;
1943 event.name = eventQuery.name;
1944 event.phase = eventQuery.phase;
1945
1946 mGpuEvents.emplace_back(event);
1947
1948 ++finishedCount;
1949 }
1950
1951 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1952 mInFlightGpuEventQueries.begin() + finishedCount);
1953
Jamie Madill7c985f52018-11-29 18:16:17 -05001954 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001955}
1956
1957void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1958{
1959 if (mGpuEvents.size() == 0)
1960 {
1961 return;
1962 }
1963
1964 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1965 ASSERT(platform);
1966
1967 // Find the slope of the clock drift for adjustment
1968 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1969 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1970 double gpuSyncDriftSlope = 0;
1971
1972 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1973 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1974
1975 // No gpu trace events should have been generated before the clock sync, so if there is no
1976 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1977 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1978 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1979
1980 gpuSyncDriftSlope =
1981 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1982
1983 for (const GpuEvent &event : mGpuEvents)
1984 {
1985 double gpuTimestampS =
1986 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1987 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1988
1989 // Account for clock drift.
1990 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1991
1992 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1993 // for.
1994 static long long eventId = 1;
1995 static const unsigned char *categoryEnabled =
1996 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1997 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1998 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1999 }
2000
2001 mGpuEvents.clear();
2002}
2003
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002004template <VkFormatFeatureFlags VkFormatProperties::*features>
2005bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2006{
2007 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2008 VkFormatProperties &deviceProperties = mFormatProperties[format];
2009
2010 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2011 {
2012 // If we don't have the actual device features, see if the requested features are mandatory.
2013 // If so, there's no need to query the device.
2014 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2015 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2016 {
2017 return true;
2018 }
2019
2020 // Otherwise query the format features and cache it.
2021 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2022 }
2023
2024 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2025}
2026
Jamie Madillaaca96e2018-06-12 10:19:48 -04002027uint32_t GetUniformBufferDescriptorCount()
2028{
2029 return kUniformBufferDescriptorsPerDescriptorSet;
2030}
2031
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002032} // namespace rx