blob: 908af8a63c51b3f1f758db4f4b0cbd4aad935c39 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050018#include "common/system_utils.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040019#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050020#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050021#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050022#include "libANGLE/renderer/vulkan/CompilerVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040023#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050025#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050026#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050028#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050029#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040031
Shahbaz Youssefi61656022018-10-24 15:00:50 -040032#include "third_party/trace_event/trace_event.h"
33
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070034// Consts
35namespace
36{
Jamie Madillb980c562018-11-27 11:34:27 -050037const uint32_t kMockVendorID = 0xba5eba11;
38const uint32_t kMockDeviceID = 0xf005ba11;
39constexpr char kMockDeviceName[] = "Vulkan Mock Device";
Shahbaz Youssefi61656022018-10-24 15:00:50 -040040constexpr size_t kInFlightCommandsLimit = 100u;
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070041} // anonymous namespace
42
Jamie Madill9e54b5a2016-05-25 12:57:39 -040043namespace rx
44{
45
Jamie Madille09bd5d2016-11-29 16:20:35 -050046namespace
47{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040048// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
49// one for the vertex shader.
50constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040051// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
52static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040053// Wait a maximum of 10s. If that times out, we declare it a failure.
54static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050055
Omar El Sheikh26c61b22018-06-29 12:50:59 -060056bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
57{
58#if !defined(ANGLE_PLATFORM_ANDROID)
59 // Mock ICD does not currently run on Android
60 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
61 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
62 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
63#else
64 return false;
65#endif // !defined(ANGLE_PLATFORM_ANDROID)
66}
67
Jamie Madille09bd5d2016-11-29 16:20:35 -050068VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
69 const std::vector<const char *> &enabledExtensionNames)
70{
71 // Compile the extensions names into a set.
72 std::set<std::string> extensionNames;
73 for (const auto &extensionProp : extensionProps)
74 {
75 extensionNames.insert(extensionProp.extensionName);
76 }
77
Jamie Madillacf2f3a2017-11-21 19:22:44 -050078 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050079 {
80 if (extensionNames.count(extensionName) == 0)
81 {
82 return VK_ERROR_EXTENSION_NOT_PRESENT;
83 }
84 }
85
86 return VK_SUCCESS;
87}
88
Tobin Ehlis3a181e32018-08-29 15:17:05 -060089// Array of Validation error/warning messages that will be ignored, should include bugID
90constexpr std::array<const char *, 1> kSkippedMessages = {
91 // http://anglebug.com/2796
92 " [ UNASSIGNED-CoreValidation-Shader-PointSizeMissing ] Object: VK_NULL_HANDLE (Type = 19) "
93 "| Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader "
94 "corresponding to VK_SHADER_STAGE_VERTEX_BIT."};
95
96// Suppress validation errors that are known
97// return "true" if given code/prefix/message is known, else return "false"
98bool IsIgnoredDebugMessage(const char *message)
99{
100 for (const auto &msg : kSkippedMessages)
101 {
102 if (strcmp(msg, message) == 0)
103 {
104 return true;
105 }
106 }
107 return false;
108}
109
Yuly Novikov199f4292018-01-19 19:04:05 -0500110VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
111 VkDebugReportObjectTypeEXT objectType,
112 uint64_t object,
113 size_t location,
114 int32_t messageCode,
115 const char *layerPrefix,
116 const char *message,
117 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500118{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600119 if (IsIgnoredDebugMessage(message))
120 {
121 return VK_FALSE;
122 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500123 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
124 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500125 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500126#if !defined(NDEBUG)
127 // Abort the call in Debug builds.
128 return VK_TRUE;
129#endif
130 }
131 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
132 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500133 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500134 }
135 else
136 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500137 // Uncomment this if you want Vulkan spam.
138 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500139 }
140
141 return VK_FALSE;
142}
143
Yuly Novikov199f4292018-01-19 19:04:05 -0500144// If we're loading the validation layers, we could be running from any random directory.
145// Change to the executable directory so we can find the layers, then change back to the
146// previous directory to be safe we don't disrupt the application.
147class ScopedVkLoaderEnvironment : angle::NonCopyable
148{
149 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600150 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
151 : mEnableValidationLayers(enableValidationLayers),
152 mEnableMockICD(enableMockICD),
153 mChangedCWD(false),
154 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500155 {
156// Changing CWD and setting environment variables makes no sense on Android,
157// since this code is a part of Java application there.
158// Android Vulkan loader doesn't need this either.
159#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600160 if (enableMockICD)
161 {
162 // Override environment variable to use built Mock ICD
163 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
164 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
165 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
166 if (!mChangedICDPath)
167 {
168 ERR() << "Error setting Path for Mock/Null Driver.";
169 mEnableMockICD = false;
170 }
171 }
Jamie Madill46848422018-08-09 10:46:06 -0400172 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500173 {
174 const auto &cwd = angle::GetCWD();
175 if (!cwd.valid())
176 {
177 ERR() << "Error getting CWD for Vulkan layers init.";
178 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400179 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500180 }
181 else
182 {
183 mPreviousCWD = cwd.value();
184 const char *exeDir = angle::GetExecutableDirectory();
185 mChangedCWD = angle::SetCWD(exeDir);
186 if (!mChangedCWD)
187 {
188 ERR() << "Error setting CWD for Vulkan layers init.";
189 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400190 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500191 }
192 }
193 }
194
195 // Override environment variable to use the ANGLE layers.
196 if (mEnableValidationLayers)
197 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700198 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500199 {
200 ERR() << "Error setting environment for Vulkan layers init.";
201 mEnableValidationLayers = false;
202 }
203 }
204#endif // !defined(ANGLE_PLATFORM_ANDROID)
205 }
206
207 ~ScopedVkLoaderEnvironment()
208 {
209 if (mChangedCWD)
210 {
211#if !defined(ANGLE_PLATFORM_ANDROID)
212 ASSERT(mPreviousCWD.valid());
213 angle::SetCWD(mPreviousCWD.value().c_str());
214#endif // !defined(ANGLE_PLATFORM_ANDROID)
215 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600216 if (mChangedICDPath)
217 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600218 if (mPreviousICDPath.value().empty())
219 {
220 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
221 }
222 else
223 {
224 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
225 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600226 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500227 }
228
Jamie Madillaaca96e2018-06-12 10:19:48 -0400229 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500230
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600231 bool canEnableMockICD() const { return mEnableMockICD; }
232
Yuly Novikov199f4292018-01-19 19:04:05 -0500233 private:
234 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600235 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500236 bool mChangedCWD;
237 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600238 bool mChangedICDPath;
239 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500240};
241
Jamie Madill21061022018-07-12 23:56:30 -0400242void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
243 bool preferMockICD,
244 VkPhysicalDevice *physicalDeviceOut,
245 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
246{
247 ASSERT(!physicalDevices.empty());
248 if (preferMockICD)
249 {
250 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
251 {
252 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
253 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
254 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
255 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
256 {
257 *physicalDeviceOut = physicalDevice;
258 return;
259 }
260 }
261 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
262 "physicalDevice instead.";
263 }
264
265 // Fall back to first device.
266 *physicalDeviceOut = physicalDevices[0];
267 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
268}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400269
270// Initially dumping the command graphs is disabled.
271constexpr bool kEnableCommandGraphDiagnostics = false;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500272} // anonymous namespace
273
Jamie Madill49ac74b2017-12-21 14:42:33 -0500274// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400275RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500276
Jamie Madillaaca96e2018-06-12 10:19:48 -0400277RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500278
279RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
280 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500281{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500282
283RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
284{
285 std::swap(commandPool, other.commandPool);
286 std::swap(fence, other.fence);
287 std::swap(serial, other.serial);
288 return *this;
289}
290
Jamie Madillbea35a62018-07-05 11:54:10 -0400291void RendererVk::CommandBatch::destroy(VkDevice device)
292{
293 commandPool.destroy(device);
294 fence.destroy(device);
295}
296
Jamie Madill9f2a8612017-11-30 12:43:09 -0500297// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500298RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400299 : mDisplay(nullptr),
300 mCapsInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500301 mInstance(VK_NULL_HANDLE),
302 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400303 mEnableMockICD(false),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500304 mDebugReportCallback(VK_NULL_HANDLE),
305 mPhysicalDevice(VK_NULL_HANDLE),
306 mQueue(VK_NULL_HANDLE),
307 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
308 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400309 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400310 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400311 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400312 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400313 mCommandGraph(kEnableCommandGraphDiagnostics),
314 mGpuEventsEnabled(false),
315 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
316 mGpuEventTimestampOrigin(0)
Jamie Madillb980c562018-11-27 11:34:27 -0500317{}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400318
Jamie Madillb980c562018-11-27 11:34:27 -0500319RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400320
321void RendererVk::onDestroy(vk::Context *context)
322{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500323 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500324 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500325 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400326 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500327 }
328
Jamie Madillc7918ce2018-06-13 13:25:31 -0400329 mPipelineLayoutCache.destroy(mDevice);
330 mDescriptorSetLayoutCache.destroy(mDevice);
331
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500332 mFullScreenClearShaderProgram.destroy(mDevice);
333
Jamie Madill9f2a8612017-11-30 12:43:09 -0500334 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500335 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400336 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400337 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400338 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500339
Jamie Madill06ca6342018-07-12 15:56:53 -0400340 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500341
Jamie Madill5deea722017-02-16 10:44:46 -0500342 if (mCommandPool.valid())
343 {
344 mCommandPool.destroy(mDevice);
345 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500346
347 if (mDevice)
348 {
349 vkDestroyDevice(mDevice, nullptr);
350 mDevice = VK_NULL_HANDLE;
351 }
352
Jamie Madill0448ec82016-12-23 13:41:47 -0500353 if (mDebugReportCallback)
354 {
355 ASSERT(mInstance);
356 auto destroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
357 vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT"));
358 ASSERT(destroyDebugReportCallback);
359 destroyDebugReportCallback(mInstance, mDebugReportCallback, nullptr);
360 }
361
Jamie Madill4d0bf552016-12-28 15:45:24 -0500362 if (mInstance)
363 {
364 vkDestroyInstance(mInstance, nullptr);
365 mInstance = VK_NULL_HANDLE;
366 }
367
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600368 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500369 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500370}
371
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400372void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400373{
374 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400375
376 mCommandGraph.clear();
377 mLastSubmittedQueueSerial = mCurrentQueueSerial;
378 mCurrentQueueSerial = mQueueSerialFactory.generate();
379 freeAllInFlightResources();
380
381 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400382}
383
384bool RendererVk::isDeviceLost() const
385{
386 return mDeviceLost;
387}
388
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400389angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400390 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400391 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500392{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400393 mDisplay = display;
394 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600395 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
396 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500397 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400398 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500399
Jamie Madill0448ec82016-12-23 13:41:47 -0500400 // Gather global layer properties.
401 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400402 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500403
404 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
405 if (instanceLayerCount > 0)
406 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400407 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
408 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500409 }
410
Jamie Madille09bd5d2016-11-29 16:20:35 -0500411 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400412 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400413 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500414
415 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
416 if (instanceExtensionCount > 0)
417 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400418 ANGLE_VK_TRY(displayVk,
419 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
420 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500421 }
422
Yuly Novikov199f4292018-01-19 19:04:05 -0500423 const char *const *enabledLayerNames = nullptr;
424 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500425 if (mEnableValidationLayers)
426 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500427 bool layersRequested =
428 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
429 mEnableValidationLayers = GetAvailableValidationLayers(
430 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500431 }
432
Jamie Madille09bd5d2016-11-29 16:20:35 -0500433 std::vector<const char *> enabledInstanceExtensions;
434 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500435 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500436
Jamie Madill0448ec82016-12-23 13:41:47 -0500437 // TODO(jmadill): Should be able to continue initialization if debug report ext missing.
438 if (mEnableValidationLayers)
439 {
440 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
441 }
442
Jamie Madille09bd5d2016-11-29 16:20:35 -0500443 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400444 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400445 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500446
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400447 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500448 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500449 applicationInfo.pApplicationName = "ANGLE";
450 applicationInfo.applicationVersion = 1;
451 applicationInfo.pEngineName = "ANGLE";
452 applicationInfo.engineVersion = 1;
453 applicationInfo.apiVersion = VK_API_VERSION_1_0;
454
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400455 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500456 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
457 instanceInfo.flags = 0;
458 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500459
Jamie Madille09bd5d2016-11-29 16:20:35 -0500460 // Enable requested layers and extensions.
461 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
462 instanceInfo.ppEnabledExtensionNames =
463 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500464 instanceInfo.enabledLayerCount = enabledLayerCount;
465 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500466
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400467 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500468
Jamie Madill0448ec82016-12-23 13:41:47 -0500469 if (mEnableValidationLayers)
470 {
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400471 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500472
473 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500474 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
475 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
476 VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
477 debugReportInfo.pfnCallback = &DebugReportCallback;
478 debugReportInfo.pUserData = this;
479
480 auto createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
481 vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT"));
482 ASSERT(createDebugReportCallback);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400483 ANGLE_VK_TRY(displayVk, createDebugReportCallback(mInstance, &debugReportInfo, nullptr,
484 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500485 }
486
Jamie Madill4d0bf552016-12-28 15:45:24 -0500487 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400488 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
489 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500490
491 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700492 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400493 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
494 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400495 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700496 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500497
Jamie Madill30b5d842018-08-31 17:19:12 -0400498 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
499
Jamie Madill4d0bf552016-12-28 15:45:24 -0500500 // Ensure we can find a graphics queue family.
501 uint32_t queueCount = 0;
502 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
503
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400504 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500505
506 mQueueFamilyProperties.resize(queueCount);
507 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
508 mQueueFamilyProperties.data());
509
Jamie Madillb980c562018-11-27 11:34:27 -0500510 size_t graphicsQueueFamilyCount = false;
511 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500512 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500513 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
514 {
515 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500516 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500517 {
518 ASSERT(queueInfo.queueCount > 0);
519 graphicsQueueFamilyCount++;
520 if (firstGraphicsQueueFamily == 0)
521 {
522 firstGraphicsQueueFamily = familyIndex;
523 }
524 break;
525 }
526 }
527
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400528 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500529
Jamie Madill12222072018-07-11 14:59:48 -0400530 initFeatures();
531
Jamie Madill4d0bf552016-12-28 15:45:24 -0500532 // If only one queue family, go ahead and initialize the device. If there is more than one
533 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
534 if (graphicsQueueFamilyCount == 1)
535 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400536 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500537 }
538
Jamie Madill035fd6b2017-10-03 15:43:22 -0400539 // Store the physical device memory properties so we can find the right memory pools.
540 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500541
Jamie Madill06ca6342018-07-12 15:56:53 -0400542 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500543
Jamie Madill6a89d222017-11-02 11:59:51 -0400544 // Initialize the format table.
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500545 mFormatTable.initialize(mPhysicalDevice, mPhysicalDeviceProperties, mFeatures,
546 &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400547
Jamie Madill21061022018-07-12 23:56:30 -0400548 return angle::Result::Continue();
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400549}
550
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400551angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500552{
553 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400554 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400555 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500556
557 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
558 if (deviceLayerCount > 0)
559 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400560 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
561 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500562 }
563
564 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400565 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
566 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567
568 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
569 if (deviceExtensionCount > 0)
570 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400571 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
572 &deviceExtensionCount,
573 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500574 }
575
Yuly Novikov199f4292018-01-19 19:04:05 -0500576 const char *const *enabledLayerNames = nullptr;
577 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500578 if (mEnableValidationLayers)
579 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500580 mEnableValidationLayers = GetAvailableValidationLayers(
581 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500582 }
583
584 std::vector<const char *> enabledDeviceExtensions;
585 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
586
Luc Ferronbf6dc372018-06-28 15:24:19 -0400587 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
588 if (getFeatures().flipViewportY)
589 {
590 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
591 }
592
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400593 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500594
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400595 // Select additional features to be enabled
596 VkPhysicalDeviceFeatures enabledFeatures = {};
597 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
598
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400599 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500600
601 float zeroPriority = 0.0f;
602
603 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500604 queueCreateInfo.flags = 0;
605 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
606 queueCreateInfo.queueCount = 1;
607 queueCreateInfo.pQueuePriorities = &zeroPriority;
608
609 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400610 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500611
Jamie Madill50cf2be2018-06-15 09:46:57 -0400612 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400613 createInfo.flags = 0;
614 createInfo.queueCreateInfoCount = 1;
615 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500616 createInfo.enabledLayerCount = enabledLayerCount;
617 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500618 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
619 createInfo.ppEnabledExtensionNames =
620 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400621 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500622
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400623 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500624
625 mCurrentQueueFamilyIndex = queueFamilyIndex;
626
627 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
628
629 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400630 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500631 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
632 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
633 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500634
Yuly Novikov27780292018-11-09 11:19:49 -0500635 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400636
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400637 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500638 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500639
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400640 // Initialize the submission semaphore pool.
641 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
642
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400643#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
644 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
645 ASSERT(platform);
646
647 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
648 // platform discovery.
649 const unsigned char *gpuEventsEnabled =
650 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
651 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
652#endif
653
654 if (mGpuEventsEnabled)
655 {
656 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
657 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
658 vk::kDefaultTimestampQueryPoolSize));
659 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
660 }
661
Jamie Madill21061022018-07-12 23:56:30 -0400662 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500663}
664
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400665angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400666 VkSurfaceKHR surface,
667 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500668{
669 // We've already initialized a device, and can't re-create it unless it's never been used.
670 // TODO(jmadill): Handle the re-creation case if necessary.
671 if (mDevice != VK_NULL_HANDLE)
672 {
673 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
674
675 // Check if the current device supports present on this surface.
676 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400677 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400678 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500679 surface, &supportsPresent));
680
Jamie Madill6cad7732018-07-11 09:01:17 -0400681 if (supportsPresent == VK_TRUE)
682 {
683 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill21061022018-07-12 23:56:30 -0400684 return angle::Result::Continue();
Jamie Madill6cad7732018-07-11 09:01:17 -0400685 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500686 }
687
688 // Find a graphics and present queue.
689 Optional<uint32_t> newPresentQueue;
690 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500691 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500692 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
693 {
694 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500695 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500696 {
697 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400698 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
699 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500700
701 if (supportsPresent == VK_TRUE)
702 {
703 newPresentQueue = queueIndex;
704 break;
705 }
706 }
707 }
708
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400709 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
710 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500711
Jamie Madill6cad7732018-07-11 09:01:17 -0400712 *presentQueueOut = newPresentQueue.value();
Jamie Madill21061022018-07-12 23:56:30 -0400713 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500714}
715
716std::string RendererVk::getVendorString() const
717{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300718 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500719}
720
Jamie Madille09bd5d2016-11-29 16:20:35 -0500721std::string RendererVk::getRendererDescription() const
722{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500723 std::stringstream strstr;
724
725 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
726
727 strstr << "Vulkan ";
728 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
729 strstr << VK_VERSION_MINOR(apiVersion) << ".";
730 strstr << VK_VERSION_PATCH(apiVersion);
731
Olli Etuahoc6a06182018-04-13 14:11:46 +0300732 strstr << "(";
733
734 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
735 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
736 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
737 // driver detection.
738 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
739 {
740 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
741 }
742
743 strstr << mPhysicalDeviceProperties.deviceName << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500744
745 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500746}
747
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500748gl::Version RendererVk::getMaxSupportedESVersion() const
749{
750 // Declare GLES2 support if necessary features for GLES3 are missing
751 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
752
753 if (!necessaryFeaturesForES3)
754 {
755 return gl::Version(2, 0);
756 }
757
758 return gl::Version(3, 0);
759}
760
Jamie Madill12222072018-07-11 14:59:48 -0400761void RendererVk::initFeatures()
762{
Jamie Madillb36a4812018-09-25 10:15:11 -0400763// Use OpenGL line rasterization rules by default.
764// TODO(jmadill): Fix Android support. http://anglebug.com/2830
765#if defined(ANGLE_PLATFORM_ANDROID)
766 mFeatures.basicGLLineRasterization = false;
767#else
Jamie Madill12222072018-07-11 14:59:48 -0400768 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400769#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400770
Luc Ferronf786b702018-07-10 11:01:43 -0400771 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
772 // investigation. http://anglebug.com/2728
773 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400774
775#ifdef ANGLE_PLATFORM_WINDOWS
776 // http://anglebug.com/2838
777 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
778#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400779
780 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
781 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -0500782
783 // Work around incorrect NVIDIA point size range clamping.
784 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
785 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
786 {
787 mFeatures.clampPointSize = true;
788 }
Jamie Madill12222072018-07-11 14:59:48 -0400789}
790
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400791void RendererVk::initPipelineCacheVkKey()
792{
793 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
794 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
795 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
796 // there is no '\0' in the result.
797 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
798 {
799 hashStream << std::hex << c;
800 }
801 // Add the vendor and device id too for good measure.
802 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
803 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
804
805 const std::string &hashString = hashStream.str();
806 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
807 hashString.length(), mPipelineCacheVkBlobKey.data());
808}
809
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500810angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400811{
812 initPipelineCacheVkKey();
813
814 egl::BlobCache::Value initialData;
815 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
816 mPipelineCacheVkBlobKey, &initialData);
817
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400818 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400819
820 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400821 pipelineCacheCreateInfo.flags = 0;
822 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
823 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
824
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500825 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400826 return angle::Result::Continue();
827}
828
Jamie Madillacccc6c2016-05-03 17:22:10 -0400829void RendererVk::ensureCapsInitialized() const
830{
831 if (!mCapsInitialized)
832 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400833 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
834 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
835 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400836 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400837 mCapsInitialized = true;
838 }
839}
840
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400841void RendererVk::getSubmitWaitSemaphores(
842 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400843 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
844 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400845{
846 if (mSubmitLastSignaledSemaphore.getSemaphore())
847 {
848 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400849 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400850
851 // Return the semaphore to the pool (which will remain valid and unused until the
852 // queue it's about to be waited on has finished execution).
853 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
854 }
855
856 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
857 {
858 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400859 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
860
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400861 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
862 }
863 mSubmitWaitSemaphores.clear();
864}
865
Jamie Madillacccc6c2016-05-03 17:22:10 -0400866const gl::Caps &RendererVk::getNativeCaps() const
867{
868 ensureCapsInitialized();
869 return mNativeCaps;
870}
871
872const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
873{
874 ensureCapsInitialized();
875 return mNativeTextureCaps;
876}
877
878const gl::Extensions &RendererVk::getNativeExtensions() const
879{
880 ensureCapsInitialized();
881 return mNativeExtensions;
882}
883
884const gl::Limitations &RendererVk::getNativeLimitations() const
885{
886 ensureCapsInitialized();
887 return mNativeLimitations;
888}
889
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400890uint32_t RendererVk::getMaxActiveTextures()
891{
892 // TODO(lucferron): expose this limitation to GL in Context Caps
893 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
894 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
895}
896
Jamie Madill49ac74b2017-12-21 14:42:33 -0500897const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500898{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500899 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500900}
901
Jamie Madill21061022018-07-12 23:56:30 -0400902angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500903{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500904 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500905 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400906 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
907
Luc Ferron1617e692018-07-11 11:08:19 -0400908 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
909 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400910
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400911 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400912 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
913 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400914
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400915 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500916 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400917 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
918 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400919 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500920 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400921 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500922 submitInfo.signalSemaphoreCount = 0;
923 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500924
Jamie Madill21061022018-07-12 23:56:30 -0400925 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500926 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500927
Jamie Madill4c26fc22017-02-24 11:04:10 -0500928 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400929 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400930 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400931
932 if (mGpuEventsEnabled)
933 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400934 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400935 while (mInFlightGpuEventQueries.size() > 0)
936 {
937 ANGLE_TRY(checkCompletedGpuEvents(context));
938 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400939 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
940 // synchronization if there is no event to be adjusted (happens when finish() gets called
941 // multiple times towards the end of the application).
942 if (mGpuEvents.size() > 0)
943 {
944 ANGLE_TRY(synchronizeCpuGpuTime(context));
945 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400946 }
947
Jamie Madill21061022018-07-12 23:56:30 -0400948 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -0500949}
950
Jamie Madill0c0dc342017-03-24 14:18:51 -0400951void RendererVk::freeAllInFlightResources()
952{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500953 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400954 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400955 // On device loss we need to wait for fence to be signaled before destroying it
956 if (mDeviceLost)
957 {
958 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
959 // If wait times out, it is probably not possible to recover from lost device
960 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
961 }
Jamie Madill49ac74b2017-12-21 14:42:33 -0500962 batch.fence.destroy(mDevice);
963 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400964 }
965 mInFlightCommands.clear();
966
967 for (auto &garbage : mGarbage)
968 {
Jamie Madille88ec8e2017-10-31 17:18:14 -0400969 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400970 }
971 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400972
973 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400974}
975
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -0400976angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500977{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500978 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -0500979
Jamie Madill49ac74b2017-12-21 14:42:33 -0500980 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500981 {
Yuly Novikov27780292018-11-09 11:19:49 -0500982 VkResult result = batch.fence.getStatus(mDevice);
983 if (result == VK_NOT_READY)
984 {
Jamie Madill0c0dc342017-03-24 14:18:51 -0400985 break;
Yuly Novikov27780292018-11-09 11:19:49 -0500986 }
987 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -0500988
Jamie Madill49ac74b2017-12-21 14:42:33 -0500989 ASSERT(batch.serial > mLastCompletedQueueSerial);
990 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400991
Jamie Madill49ac74b2017-12-21 14:42:33 -0500992 batch.fence.destroy(mDevice);
993 batch.commandPool.destroy(mDevice);
994 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500995 }
996
Jamie Madill49ac74b2017-12-21 14:42:33 -0500997 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400998
999 size_t freeIndex = 0;
1000 for (; freeIndex < mGarbage.size(); ++freeIndex)
1001 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001002 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001003 break;
1004 }
1005
1006 // Remove the entries from the garbage list - they should be ready to go.
1007 if (freeIndex > 0)
1008 {
1009 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001010 }
1011
Jamie Madill21061022018-07-12 23:56:30 -04001012 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001013}
1014
Jamie Madill21061022018-07-12 23:56:30 -04001015angle::Result RendererVk::submitFrame(vk::Context *context,
1016 const VkSubmitInfo &submitInfo,
1017 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001018{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001019 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001020 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001021 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1022 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001023
Jamie Madillbea35a62018-07-05 11:54:10 -04001024 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1025 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001026 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001027
Jamie Madill21061022018-07-12 23:56:30 -04001028 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001029
1030 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001031 batch.commandPool = std::move(mCommandPool);
1032 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001033
Jamie Madillbea35a62018-07-05 11:54:10 -04001034 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001035
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001036 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1037 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
1038 // so the limit is larger than the expected number of images.
1039 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001040
1041 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001042 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001043 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001044 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001045
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001046 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001047
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001048 if (mGpuEventsEnabled)
1049 {
1050 ANGLE_TRY(checkCompletedGpuEvents(context));
1051 }
1052
Jamie Madill49ac74b2017-12-21 14:42:33 -05001053 // Simply null out the command buffer here - it was allocated using the command pool.
1054 commandBuffer.releaseHandle();
1055
1056 // Reallocate the command pool for next frame.
1057 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001058 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001059 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001060 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001061 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001062
Yuly Novikov27780292018-11-09 11:19:49 -05001063 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
1064 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001065}
1066
Jamie Madillaaca96e2018-06-12 10:19:48 -04001067bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001068{
1069 return serial > mLastCompletedQueueSerial;
1070}
1071
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001072angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1073{
1074 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1075 {
1076 return angle::Result::Continue();
1077 }
1078
1079 // Find the first batch with serial equal to or bigger than given serial (note that
1080 // the batch serials are unique, otherwise upper-bound would have been necessary).
1081 size_t batchIndex = mInFlightCommands.size() - 1;
1082 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1083 {
1084 if (mInFlightCommands[i].serial >= serial)
1085 {
1086 batchIndex = i;
1087 break;
1088 }
1089 }
1090 const CommandBatch &batch = mInFlightCommands[batchIndex];
1091
1092 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001093 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001094
1095 // Clean up finished batches.
1096 return checkCompletedCommands(context);
1097}
1098
Jamie Madill21061022018-07-12 23:56:30 -04001099angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1100 const vk::RenderPassDesc &desc,
1101 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001102{
Jamie Madill21061022018-07-12 23:56:30 -04001103 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001104 renderPassOut);
1105}
1106
Jamie Madill21061022018-07-12 23:56:30 -04001107angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1108 const vk::RenderPassDesc &desc,
1109 const vk::AttachmentOpsArray &ops,
1110 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001111{
Jamie Madill21061022018-07-12 23:56:30 -04001112 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001113 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001114}
1115
Jamie Madilla5e06072018-05-18 14:36:05 -04001116vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001117{
Jamie Madilla5e06072018-05-18 14:36:05 -04001118 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001119}
1120
Jamie Madill21061022018-07-12 23:56:30 -04001121angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001122{
Jamie Madill21061022018-07-12 23:56:30 -04001123 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001124 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001125}
1126
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001127angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001128{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001129 if (mCommandGraph.empty())
1130 {
1131 return angle::Result::Continue();
1132 }
1133
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001134 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1135
Jamie Madillbea35a62018-07-05 11:54:10 -04001136 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1137 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001138
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001139 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001140 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1141 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001142
1143 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1144 // will be waited on.
1145 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001146
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001147 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001148 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001149 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1150 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001151 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001152 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001153 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001154 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001155 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001156
Jamie Madill21061022018-07-12 23:56:30 -04001157 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001158
Jamie Madill21061022018-07-12 23:56:30 -04001159 return angle::Result::Continue();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001160}
1161
Jamie Madill78feddc2018-04-27 11:45:05 -04001162Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001163{
Jamie Madill78feddc2018-04-27 11:45:05 -04001164 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001165}
1166
Jamie Madill21061022018-07-12 23:56:30 -04001167angle::Result RendererVk::getDescriptorSetLayout(
1168 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001169 const vk::DescriptorSetLayoutDesc &desc,
1170 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1171{
Jamie Madill21061022018-07-12 23:56:30 -04001172 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001173}
1174
Jamie Madill21061022018-07-12 23:56:30 -04001175angle::Result RendererVk::getPipelineLayout(
1176 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001177 const vk::PipelineLayoutDesc &desc,
1178 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1179 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1180{
Jamie Madill21061022018-07-12 23:56:30 -04001181 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001182 pipelineLayoutOut);
1183}
1184
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001185angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1186{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001187 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001188
1189 if (--mPipelineCacheVkUpdateTimeout > 0)
1190 {
1191 return angle::Result::Continue();
1192 }
1193
1194 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1195
1196 // Get the size of the cache.
1197 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001198 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001199 if (result != VK_INCOMPLETE)
1200 {
1201 ANGLE_VK_TRY(displayVk, result);
1202 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001203
1204 angle::MemoryBuffer *pipelineCacheData = nullptr;
1205 ANGLE_VK_CHECK_ALLOC(displayVk,
1206 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1207
1208 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001209 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001210 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1211 // was determined just above), so receiving it hints at an implementation bug we would want
1212 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001213 ASSERT(result != VK_INCOMPLETE);
1214 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001215
1216 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1217 // the buffer to avoid leaking garbage memory.
1218 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1219 if (pipelineCacheSize < originalPipelineCacheSize)
1220 {
1221 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1222 originalPipelineCacheSize - pipelineCacheSize);
1223 }
1224
1225 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1226
1227 return angle::Result::Continue();
1228}
1229
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001230angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1231 const vk::Semaphore **outSemaphore)
1232{
1233 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1234
1235 vk::SemaphoreHelper semaphore;
1236 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1237
1238 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1239 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1240
1241 return angle::Result::Continue();
1242}
1243
1244const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1245{
1246 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1247
1248 // Return the semaphore to the pool (which will remain valid and unused until the
1249 // queue it's about to be waited on has finished execution). The caller is about
1250 // to wait on it.
1251 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1252
1253 return semaphore;
1254}
1255
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001256angle::Result RendererVk::getFullScreenClearShaderProgram(vk::Context *context,
1257 vk::ShaderProgramHelper **programOut)
Jamie Madilld47044a2018-04-27 11:45:03 -04001258{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001259 if (!mFullScreenClearShaderProgram.valid())
1260 {
1261 vk::RefCounted<vk::ShaderAndSerial> *fullScreenQuad = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001262 ANGLE_TRY(mShaderLibrary.getFullScreenQuad_vert(context, 0, &fullScreenQuad));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001263
1264 vk::RefCounted<vk::ShaderAndSerial> *pushConstantColor = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001265 ANGLE_TRY(mShaderLibrary.getPushConstantColor_frag(context, 0, &pushConstantColor));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001266
1267 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Vertex, fullScreenQuad);
1268 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Fragment, pushConstantColor);
1269 }
1270
1271 *programOut = &mFullScreenClearShaderProgram;
1272 return angle::Result::Continue();
Jamie Madilld47044a2018-04-27 11:45:03 -04001273}
Luc Ferron90968362018-05-04 08:47:22 -04001274
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001275angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1276{
1277 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1278 // that seems impossible, so instead, we are going to make a small submission with just a
1279 // timestamp query. First, the disjoint timer query extension says:
1280 //
1281 // > This will return the GL time after all previous commands have reached the GL server but
1282 // have not yet necessarily executed.
1283 //
1284 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1285 // The wording allows us to make a submission to get the timestamp without performing a flush.
1286 //
1287 // Second:
1288 //
1289 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1290 // object target, applications can measure the latency between when commands reach the GL server
1291 // and when they are realized in the framebuffer.
1292 //
1293 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1294 // GPU bubble. This function directly generates a command buffer and submits it instead of
1295 // using the other member functions. This is to avoid changing any state, such as the queue
1296 // serial.
1297
1298 // Create a query used to receive the GPU timestamp
1299 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1300 vk::QueryHelper timestampQuery;
1301 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1302 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1303
1304 // Record the command buffer
1305 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1306 vk::CommandBuffer &commandBuffer = commandBatch.get();
1307
1308 VkCommandBufferAllocateInfo commandBufferInfo = {};
1309 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1310 commandBufferInfo.commandPool = mCommandPool.getHandle();
1311 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1312 commandBufferInfo.commandBufferCount = 1;
1313
Yuly Novikov27780292018-11-09 11:19:49 -05001314 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001315
1316 VkCommandBufferBeginInfo beginInfo = {};
1317 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1318 beginInfo.flags = 0;
1319 beginInfo.pInheritanceInfo = nullptr;
1320
Yuly Novikov27780292018-11-09 11:19:49 -05001321 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001322
1323 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1324 timestampQuery.getQuery(), 1);
1325 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1326 timestampQuery.getQueryPool()->getHandle(),
1327 timestampQuery.getQuery());
1328
Yuly Novikov27780292018-11-09 11:19:49 -05001329 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001330
1331 // Create fence for the submission
1332 VkFenceCreateInfo fenceInfo = {};
1333 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1334 fenceInfo.flags = 0;
1335
1336 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001337 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001338
1339 // Submit the command buffer
1340 VkSubmitInfo submitInfo = {};
1341 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1342 submitInfo.waitSemaphoreCount = 0;
1343 submitInfo.pWaitSemaphores = nullptr;
1344 submitInfo.pWaitDstStageMask = nullptr;
1345 submitInfo.commandBufferCount = 1;
1346 submitInfo.pCommandBuffers = commandBuffer.ptr();
1347 submitInfo.signalSemaphoreCount = 0;
1348 submitInfo.pSignalSemaphores = nullptr;
1349
1350 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1351
1352 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1353 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001354 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001355
1356 // Get the query results
1357 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1358
Yuly Novikov27780292018-11-09 11:19:49 -05001359 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1360 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1361 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001362
1363 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1364
1365 return angle::Result::Continue();
1366}
1367
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001368angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1369{
1370 ASSERT(mGpuEventsEnabled);
1371
1372 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1373 ASSERT(platform);
1374
1375 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1376 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1377 //
1378 // CPU GPU
1379 //
1380 // Record command buffer
1381 // with timestamp query
1382 //
1383 // Submit command buffer
1384 //
1385 // Post-submission work Begin execution
1386 //
1387 // ???? Write timstamp Tgpu
1388 //
1389 // ???? End execution
1390 //
1391 // ???? Return query results
1392 //
1393 // ????
1394 //
1395 // Get query results
1396 //
1397 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1398 // finished post-submission work while the GPU is executing in parallel. With no further work,
1399 // querying CPU timestamps before submission and after getting query results give the bounds to
1400 // Tgpu, which could be quite large.
1401 //
1402 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1403 // reduce this range. This function implements the following procedure:
1404 //
1405 // CPU GPU
1406 //
1407 // Record command buffer
1408 // with timestamp query
1409 //
1410 // Submit command buffer
1411 //
1412 // Post-submission work Begin execution
1413 //
1414 // ???? Set Event GPUReady
1415 //
1416 // Wait on Event GPUReady Wait on Event CPUReady
1417 //
1418 // Get CPU Time Ts Wait on Event CPUReady
1419 //
1420 // Set Event CPUReady Wait on Event CPUReady
1421 //
1422 // Get CPU Time Tcpu Get GPU Time Tgpu
1423 //
1424 // Wait on Event GPUDone Set Event GPUDone
1425 //
1426 // Get CPU Time Te End Execution
1427 //
1428 // Idle Return query results
1429 //
1430 // Get query results
1431 //
1432 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1433 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1434 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1435 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1436 // calibration.
1437 //
1438 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1439
1440 // Make sure nothing is running
1441 ASSERT(mCommandGraph.empty());
1442
1443 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1444
1445 // Create a query used to receive the GPU timestamp
1446 vk::QueryHelper timestampQuery;
1447 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1448
1449 // Create the three events
1450 VkEventCreateInfo eventCreateInfo = {};
1451 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1452 eventCreateInfo.flags = 0;
1453
1454 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001455 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1456 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1457 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001458
1459 constexpr uint32_t kRetries = 10;
1460
1461 // Time suffixes used are S for seconds and Cycles for cycles
1462 double tightestRangeS = 1e6f;
1463 double TcpuS = 0;
1464 uint64_t TgpuCycles = 0;
1465 for (uint32_t i = 0; i < kRetries; ++i)
1466 {
1467 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001468 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1469 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1470 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001471
1472 // Record the command buffer
1473 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1474 vk::CommandBuffer &commandBuffer = commandBatch.get();
1475
1476 VkCommandBufferAllocateInfo commandBufferInfo = {};
1477 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1478 commandBufferInfo.commandPool = mCommandPool.getHandle();
1479 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1480 commandBufferInfo.commandBufferCount = 1;
1481
Yuly Novikov27780292018-11-09 11:19:49 -05001482 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001483
1484 VkCommandBufferBeginInfo beginInfo = {};
1485 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1486 beginInfo.flags = 0;
1487 beginInfo.pInheritanceInfo = nullptr;
1488
Yuly Novikov27780292018-11-09 11:19:49 -05001489 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001490
1491 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1492 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1493 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1494 nullptr);
1495
1496 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1497 timestampQuery.getQuery(), 1);
1498 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1499 timestampQuery.getQueryPool()->getHandle(),
1500 timestampQuery.getQuery());
1501
1502 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1503
Yuly Novikov27780292018-11-09 11:19:49 -05001504 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001505
1506 // Submit the command buffer
1507 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1508 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1509 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1510
1511 VkSubmitInfo submitInfo = {};
1512 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1513 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1514 submitInfo.pWaitSemaphores = waitSemaphores.data();
1515 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1516 submitInfo.commandBufferCount = 1;
1517 submitInfo.pCommandBuffers = commandBuffer.ptr();
1518 submitInfo.signalSemaphoreCount = 0;
1519 submitInfo.pSignalSemaphores = nullptr;
1520
1521 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1522
1523 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001524 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001525 do
1526 {
Yuly Novikov27780292018-11-09 11:19:49 -05001527 result = gpuReady.get().getStatus(mDevice);
1528 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1529 {
1530 ANGLE_VK_TRY(context, result);
1531 }
1532 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001533
1534 double TsS = platform->monotonicallyIncreasingTime(platform);
1535
1536 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001537 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001538 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1539
1540 // Wait for GPU to be done. Another short busy wait.
1541 do
1542 {
Yuly Novikov27780292018-11-09 11:19:49 -05001543 result = gpuDone.get().getStatus(mDevice);
1544 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1545 {
1546 ANGLE_VK_TRY(context, result);
1547 }
1548 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001549
1550 double TeS = platform->monotonicallyIncreasingTime(platform);
1551
1552 // Get the query results
1553 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1554
1555 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1556
1557 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001558 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1559 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1560 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001561
1562 // Use the first timestamp queried as origin.
1563 if (mGpuEventTimestampOrigin == 0)
1564 {
1565 mGpuEventTimestampOrigin = gpuTimestampCycles;
1566 }
1567
1568 // Take these CPU and GPU timestamps if there is better confidence.
1569 double confidenceRangeS = TeS - TsS;
1570 if (confidenceRangeS < tightestRangeS)
1571 {
1572 tightestRangeS = confidenceRangeS;
1573 TcpuS = cpuTimestampS;
1574 TgpuCycles = gpuTimestampCycles;
1575 }
1576 }
1577
1578 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1579
1580 // timestampPeriod gives nanoseconds/cycle.
1581 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1582 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1583 1'000'000'000.0;
1584
1585 flushGpuEvents(TgpuS, TcpuS);
1586
1587 mGpuClockSync.gpuTimestampS = TgpuS;
1588 mGpuClockSync.cpuTimestampS = TcpuS;
1589
1590 return angle::Result::Continue();
1591}
1592
1593angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1594 vk::CommandBuffer *commandBuffer,
1595 char phase,
1596 const char *name)
1597{
1598 ASSERT(mGpuEventsEnabled);
1599
1600 GpuEventQuery event;
1601
1602 event.name = name;
1603 event.phase = phase;
1604 event.serial = mCurrentQueueSerial;
1605
1606 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1607
1608 commandBuffer->resetQueryPool(
1609 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1610 commandBuffer->writeTimestamp(
1611 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1612 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1613
1614 mInFlightGpuEventQueries.push_back(std::move(event));
1615
1616 return angle::Result::Continue();
1617}
1618
1619angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1620{
1621 ASSERT(mGpuEventsEnabled);
1622
1623 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1624 ASSERT(platform);
1625
1626 int finishedCount = 0;
1627
1628 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1629 {
1630 // Only check the timestamp query if the submission has finished.
1631 if (eventQuery.serial > mLastCompletedQueueSerial)
1632 {
1633 break;
1634 }
1635
1636 // See if the results are available.
1637 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001638 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1639 ->getResults(mDevice, eventQuery.queryIndex, 1,
1640 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1641 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1642 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001643 {
1644 break;
1645 }
Yuly Novikov27780292018-11-09 11:19:49 -05001646 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001647
1648 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1649
1650 GpuEvent event;
1651 event.gpuTimestampCycles = gpuTimestampCycles;
1652 event.name = eventQuery.name;
1653 event.phase = eventQuery.phase;
1654
1655 mGpuEvents.emplace_back(event);
1656
1657 ++finishedCount;
1658 }
1659
1660 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1661 mInFlightGpuEventQueries.begin() + finishedCount);
1662
1663 return angle::Result::Continue();
1664}
1665
1666void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1667{
1668 if (mGpuEvents.size() == 0)
1669 {
1670 return;
1671 }
1672
1673 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1674 ASSERT(platform);
1675
1676 // Find the slope of the clock drift for adjustment
1677 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1678 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1679 double gpuSyncDriftSlope = 0;
1680
1681 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1682 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1683
1684 // No gpu trace events should have been generated before the clock sync, so if there is no
1685 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1686 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1687 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1688
1689 gpuSyncDriftSlope =
1690 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1691
1692 for (const GpuEvent &event : mGpuEvents)
1693 {
1694 double gpuTimestampS =
1695 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1696 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1697
1698 // Account for clock drift.
1699 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1700
1701 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1702 // for.
1703 static long long eventId = 1;
1704 static const unsigned char *categoryEnabled =
1705 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1706 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1707 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1708 }
1709
1710 mGpuEvents.clear();
1711}
1712
Jamie Madillaaca96e2018-06-12 10:19:48 -04001713uint32_t GetUniformBufferDescriptorCount()
1714{
1715 return kUniformBufferDescriptorsPerDescriptorSet;
1716}
1717
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001718} // namespace rx