blob: f148613c2d6b7e123403d7211671fb63f9bf6c35 [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{
37const 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)
281{
282}
283
284RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
285{
286 std::swap(commandPool, other.commandPool);
287 std::swap(fence, other.fence);
288 std::swap(serial, other.serial);
289 return *this;
290}
291
Jamie Madillbea35a62018-07-05 11:54:10 -0400292void RendererVk::CommandBatch::destroy(VkDevice device)
293{
294 commandPool.destroy(device);
295 fence.destroy(device);
296}
297
Jamie Madill9f2a8612017-11-30 12:43:09 -0500298// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500299RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400300 : mDisplay(nullptr),
301 mCapsInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500302 mInstance(VK_NULL_HANDLE),
303 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400304 mEnableMockICD(false),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500305 mDebugReportCallback(VK_NULL_HANDLE),
306 mPhysicalDevice(VK_NULL_HANDLE),
307 mQueue(VK_NULL_HANDLE),
308 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
309 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400310 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400311 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400312 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400313 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400314 mCommandGraph(kEnableCommandGraphDiagnostics),
315 mGpuEventsEnabled(false),
316 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
317 mGpuEventTimestampOrigin(0)
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400318{
319}
320
321RendererVk::~RendererVk()
322{
Jamie Madill21061022018-07-12 23:56:30 -0400323}
324
325void RendererVk::onDestroy(vk::Context *context)
326{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500327 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500328 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500329 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400330 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500331 }
332
Jamie Madillc7918ce2018-06-13 13:25:31 -0400333 mPipelineLayoutCache.destroy(mDevice);
334 mDescriptorSetLayoutCache.destroy(mDevice);
335
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500336 mFullScreenClearShaderProgram.destroy(mDevice);
337
Jamie Madill9f2a8612017-11-30 12:43:09 -0500338 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500339 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400340 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400341 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400342 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500343
Jamie Madill06ca6342018-07-12 15:56:53 -0400344 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500345
Jamie Madill5deea722017-02-16 10:44:46 -0500346 if (mCommandPool.valid())
347 {
348 mCommandPool.destroy(mDevice);
349 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500350
351 if (mDevice)
352 {
353 vkDestroyDevice(mDevice, nullptr);
354 mDevice = VK_NULL_HANDLE;
355 }
356
Jamie Madill0448ec82016-12-23 13:41:47 -0500357 if (mDebugReportCallback)
358 {
359 ASSERT(mInstance);
360 auto destroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
361 vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT"));
362 ASSERT(destroyDebugReportCallback);
363 destroyDebugReportCallback(mInstance, mDebugReportCallback, nullptr);
364 }
365
Jamie Madill4d0bf552016-12-28 15:45:24 -0500366 if (mInstance)
367 {
368 vkDestroyInstance(mInstance, nullptr);
369 mInstance = VK_NULL_HANDLE;
370 }
371
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600372 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500373 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500374}
375
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400376void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400377{
378 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400379
380 mCommandGraph.clear();
381 mLastSubmittedQueueSerial = mCurrentQueueSerial;
382 mCurrentQueueSerial = mQueueSerialFactory.generate();
383 freeAllInFlightResources();
384
385 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400386}
387
388bool RendererVk::isDeviceLost() const
389{
390 return mDeviceLost;
391}
392
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400393angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400394 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400395 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500396{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400397 mDisplay = display;
398 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600399 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
400 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500401 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400402 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500403
Jamie Madill0448ec82016-12-23 13:41:47 -0500404 // Gather global layer properties.
405 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400406 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500407
408 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
409 if (instanceLayerCount > 0)
410 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400411 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
412 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500413 }
414
Jamie Madille09bd5d2016-11-29 16:20:35 -0500415 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400416 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400417 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500418
419 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
420 if (instanceExtensionCount > 0)
421 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400422 ANGLE_VK_TRY(displayVk,
423 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
424 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500425 }
426
Yuly Novikov199f4292018-01-19 19:04:05 -0500427 const char *const *enabledLayerNames = nullptr;
428 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500429 if (mEnableValidationLayers)
430 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500431 bool layersRequested =
432 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
433 mEnableValidationLayers = GetAvailableValidationLayers(
434 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500435 }
436
Jamie Madille09bd5d2016-11-29 16:20:35 -0500437 std::vector<const char *> enabledInstanceExtensions;
438 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500439 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500440
Jamie Madill0448ec82016-12-23 13:41:47 -0500441 // TODO(jmadill): Should be able to continue initialization if debug report ext missing.
442 if (mEnableValidationLayers)
443 {
444 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
445 }
446
Jamie Madille09bd5d2016-11-29 16:20:35 -0500447 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400448 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400449 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500450
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400451 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500452 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500453 applicationInfo.pApplicationName = "ANGLE";
454 applicationInfo.applicationVersion = 1;
455 applicationInfo.pEngineName = "ANGLE";
456 applicationInfo.engineVersion = 1;
457 applicationInfo.apiVersion = VK_API_VERSION_1_0;
458
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400459 VkInstanceCreateInfo instanceInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500460 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500461 instanceInfo.flags = 0;
462 instanceInfo.pApplicationInfo = &applicationInfo;
463
Jamie Madille09bd5d2016-11-29 16:20:35 -0500464 // Enable requested layers and extensions.
465 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
466 instanceInfo.ppEnabledExtensionNames =
467 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500468 instanceInfo.enabledLayerCount = enabledLayerCount;
469 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500470
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400471 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500472
Jamie Madill0448ec82016-12-23 13:41:47 -0500473 if (mEnableValidationLayers)
474 {
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400475 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500476
477 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500478 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
479 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
480 VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
481 debugReportInfo.pfnCallback = &DebugReportCallback;
482 debugReportInfo.pUserData = this;
483
484 auto createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
485 vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT"));
486 ASSERT(createDebugReportCallback);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400487 ANGLE_VK_TRY(displayVk, createDebugReportCallback(mInstance, &debugReportInfo, nullptr,
488 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500489 }
490
Jamie Madill4d0bf552016-12-28 15:45:24 -0500491 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400492 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
493 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500494
495 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700496 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400497 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
498 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400499 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700500 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500501
Jamie Madill30b5d842018-08-31 17:19:12 -0400502 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
503
Jamie Madill4d0bf552016-12-28 15:45:24 -0500504 // Ensure we can find a graphics queue family.
505 uint32_t queueCount = 0;
506 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
507
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400508 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500509
510 mQueueFamilyProperties.resize(queueCount);
511 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
512 mQueueFamilyProperties.data());
513
514 size_t graphicsQueueFamilyCount = false;
515 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500516 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500517 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
518 {
519 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500520 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500521 {
522 ASSERT(queueInfo.queueCount > 0);
523 graphicsQueueFamilyCount++;
524 if (firstGraphicsQueueFamily == 0)
525 {
526 firstGraphicsQueueFamily = familyIndex;
527 }
528 break;
529 }
530 }
531
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400532 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500533
Jamie Madill12222072018-07-11 14:59:48 -0400534 initFeatures();
535
Jamie Madill4d0bf552016-12-28 15:45:24 -0500536 // If only one queue family, go ahead and initialize the device. If there is more than one
537 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
538 if (graphicsQueueFamilyCount == 1)
539 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400540 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500541 }
542
Jamie Madill035fd6b2017-10-03 15:43:22 -0400543 // Store the physical device memory properties so we can find the right memory pools.
544 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500545
Jamie Madill06ca6342018-07-12 15:56:53 -0400546 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500547
Jamie Madill6a89d222017-11-02 11:59:51 -0400548 // Initialize the format table.
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500549 mFormatTable.initialize(mPhysicalDevice, mPhysicalDeviceProperties, mFeatures,
550 &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400551
Jamie Madill21061022018-07-12 23:56:30 -0400552 return angle::Result::Continue();
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400553}
554
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400555angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500556{
557 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400558 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400559 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500560
561 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
562 if (deviceLayerCount > 0)
563 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400564 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
565 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500566 }
567
568 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400569 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
570 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500571
572 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
573 if (deviceExtensionCount > 0)
574 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400575 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
576 &deviceExtensionCount,
577 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500578 }
579
Yuly Novikov199f4292018-01-19 19:04:05 -0500580 const char *const *enabledLayerNames = nullptr;
581 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500582 if (mEnableValidationLayers)
583 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500584 mEnableValidationLayers = GetAvailableValidationLayers(
585 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500586 }
587
588 std::vector<const char *> enabledDeviceExtensions;
589 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
590
Luc Ferronbf6dc372018-06-28 15:24:19 -0400591 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
592 if (getFeatures().flipViewportY)
593 {
594 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
595 }
596
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400597 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500598
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400599 // Select additional features to be enabled
600 VkPhysicalDeviceFeatures enabledFeatures = {};
601 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
602
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400603 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500604
605 float zeroPriority = 0.0f;
606
607 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500608 queueCreateInfo.flags = 0;
609 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
610 queueCreateInfo.queueCount = 1;
611 queueCreateInfo.pQueuePriorities = &zeroPriority;
612
613 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400614 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500615
Jamie Madill50cf2be2018-06-15 09:46:57 -0400616 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400617 createInfo.flags = 0;
618 createInfo.queueCreateInfoCount = 1;
619 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500620 createInfo.enabledLayerCount = enabledLayerCount;
621 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500622 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
623 createInfo.ppEnabledExtensionNames =
624 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400625 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500626
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400627 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500628
629 mCurrentQueueFamilyIndex = queueFamilyIndex;
630
631 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
632
633 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400634 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500635 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500636 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500637 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
638
Yuly Novikov27780292018-11-09 11:19:49 -0500639 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400640
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400641 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500642 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500643
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400644 // Initialize the submission semaphore pool.
645 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
646
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400647#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
648 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
649 ASSERT(platform);
650
651 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
652 // platform discovery.
653 const unsigned char *gpuEventsEnabled =
654 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
655 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
656#endif
657
658 if (mGpuEventsEnabled)
659 {
660 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
661 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
662 vk::kDefaultTimestampQueryPoolSize));
663 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
664 }
665
Jamie Madill21061022018-07-12 23:56:30 -0400666 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500667}
668
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400669angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400670 VkSurfaceKHR surface,
671 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500672{
673 // We've already initialized a device, and can't re-create it unless it's never been used.
674 // TODO(jmadill): Handle the re-creation case if necessary.
675 if (mDevice != VK_NULL_HANDLE)
676 {
677 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
678
679 // Check if the current device supports present on this surface.
680 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400681 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400682 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500683 surface, &supportsPresent));
684
Jamie Madill6cad7732018-07-11 09:01:17 -0400685 if (supportsPresent == VK_TRUE)
686 {
687 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill21061022018-07-12 23:56:30 -0400688 return angle::Result::Continue();
Jamie Madill6cad7732018-07-11 09:01:17 -0400689 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500690 }
691
692 // Find a graphics and present queue.
693 Optional<uint32_t> newPresentQueue;
694 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500695 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500696 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
697 {
698 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500699 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500700 {
701 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400702 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
703 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500704
705 if (supportsPresent == VK_TRUE)
706 {
707 newPresentQueue = queueIndex;
708 break;
709 }
710 }
711 }
712
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400713 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
714 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500715
Jamie Madill6cad7732018-07-11 09:01:17 -0400716 *presentQueueOut = newPresentQueue.value();
Jamie Madill21061022018-07-12 23:56:30 -0400717 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500718}
719
720std::string RendererVk::getVendorString() const
721{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300722 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500723}
724
Jamie Madille09bd5d2016-11-29 16:20:35 -0500725std::string RendererVk::getRendererDescription() const
726{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500727 std::stringstream strstr;
728
729 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
730
731 strstr << "Vulkan ";
732 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
733 strstr << VK_VERSION_MINOR(apiVersion) << ".";
734 strstr << VK_VERSION_PATCH(apiVersion);
735
Olli Etuahoc6a06182018-04-13 14:11:46 +0300736 strstr << "(";
737
738 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
739 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
740 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
741 // driver detection.
742 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
743 {
744 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
745 }
746
747 strstr << mPhysicalDeviceProperties.deviceName << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500748
749 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500750}
751
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500752gl::Version RendererVk::getMaxSupportedESVersion() const
753{
754 // Declare GLES2 support if necessary features for GLES3 are missing
755 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
756
757 if (!necessaryFeaturesForES3)
758 {
759 return gl::Version(2, 0);
760 }
761
762 return gl::Version(3, 0);
763}
764
Jamie Madill12222072018-07-11 14:59:48 -0400765void RendererVk::initFeatures()
766{
Jamie Madillb36a4812018-09-25 10:15:11 -0400767// Use OpenGL line rasterization rules by default.
768// TODO(jmadill): Fix Android support. http://anglebug.com/2830
769#if defined(ANGLE_PLATFORM_ANDROID)
770 mFeatures.basicGLLineRasterization = false;
771#else
Jamie Madill12222072018-07-11 14:59:48 -0400772 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400773#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400774
Luc Ferronf786b702018-07-10 11:01:43 -0400775 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
776 // investigation. http://anglebug.com/2728
777 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400778
779#ifdef ANGLE_PLATFORM_WINDOWS
780 // http://anglebug.com/2838
781 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
782#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400783
784 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
785 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -0500786
787 // Work around incorrect NVIDIA point size range clamping.
788 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
789 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
790 {
791 mFeatures.clampPointSize = true;
792 }
Jamie Madill12222072018-07-11 14:59:48 -0400793}
794
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400795void RendererVk::initPipelineCacheVkKey()
796{
797 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
798 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
799 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
800 // there is no '\0' in the result.
801 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
802 {
803 hashStream << std::hex << c;
804 }
805 // Add the vendor and device id too for good measure.
806 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
807 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
808
809 const std::string &hashString = hashStream.str();
810 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
811 hashString.length(), mPipelineCacheVkBlobKey.data());
812}
813
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500814angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400815{
816 initPipelineCacheVkKey();
817
818 egl::BlobCache::Value initialData;
819 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
820 mPipelineCacheVkBlobKey, &initialData);
821
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400822 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400823
824 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400825 pipelineCacheCreateInfo.flags = 0;
826 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
827 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
828
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500829 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400830 return angle::Result::Continue();
831}
832
Jamie Madillacccc6c2016-05-03 17:22:10 -0400833void RendererVk::ensureCapsInitialized() const
834{
835 if (!mCapsInitialized)
836 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400837 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
838 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
839 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400840 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400841 mCapsInitialized = true;
842 }
843}
844
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400845void RendererVk::getSubmitWaitSemaphores(
846 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400847 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
848 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400849{
850 if (mSubmitLastSignaledSemaphore.getSemaphore())
851 {
852 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400853 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400854
855 // Return the semaphore to the pool (which will remain valid and unused until the
856 // queue it's about to be waited on has finished execution).
857 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
858 }
859
860 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
861 {
862 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400863 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
864
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400865 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
866 }
867 mSubmitWaitSemaphores.clear();
868}
869
Jamie Madillacccc6c2016-05-03 17:22:10 -0400870const gl::Caps &RendererVk::getNativeCaps() const
871{
872 ensureCapsInitialized();
873 return mNativeCaps;
874}
875
876const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
877{
878 ensureCapsInitialized();
879 return mNativeTextureCaps;
880}
881
882const gl::Extensions &RendererVk::getNativeExtensions() const
883{
884 ensureCapsInitialized();
885 return mNativeExtensions;
886}
887
888const gl::Limitations &RendererVk::getNativeLimitations() const
889{
890 ensureCapsInitialized();
891 return mNativeLimitations;
892}
893
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400894uint32_t RendererVk::getMaxActiveTextures()
895{
896 // TODO(lucferron): expose this limitation to GL in Context Caps
897 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
898 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
899}
900
Jamie Madill49ac74b2017-12-21 14:42:33 -0500901const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500902{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500903 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500904}
905
Jamie Madill21061022018-07-12 23:56:30 -0400906angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500907{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500908 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500909 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400910 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
911
Luc Ferron1617e692018-07-11 11:08:19 -0400912 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
913 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400914
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400915 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400916 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
917 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400918
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400919 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500920 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400921 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
922 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400923 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500924 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400925 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500926 submitInfo.signalSemaphoreCount = 0;
927 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500928
Jamie Madill21061022018-07-12 23:56:30 -0400929 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500930 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500931
Jamie Madill4c26fc22017-02-24 11:04:10 -0500932 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400933 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400934 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400935
936 if (mGpuEventsEnabled)
937 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400938 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400939 while (mInFlightGpuEventQueries.size() > 0)
940 {
941 ANGLE_TRY(checkCompletedGpuEvents(context));
942 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400943 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
944 // synchronization if there is no event to be adjusted (happens when finish() gets called
945 // multiple times towards the end of the application).
946 if (mGpuEvents.size() > 0)
947 {
948 ANGLE_TRY(synchronizeCpuGpuTime(context));
949 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400950 }
951
Jamie Madill21061022018-07-12 23:56:30 -0400952 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -0500953}
954
Jamie Madill0c0dc342017-03-24 14:18:51 -0400955void RendererVk::freeAllInFlightResources()
956{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500957 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400958 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400959 // On device loss we need to wait for fence to be signaled before destroying it
960 if (mDeviceLost)
961 {
962 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
963 // If wait times out, it is probably not possible to recover from lost device
964 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
965 }
Jamie Madill49ac74b2017-12-21 14:42:33 -0500966 batch.fence.destroy(mDevice);
967 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400968 }
969 mInFlightCommands.clear();
970
971 for (auto &garbage : mGarbage)
972 {
Jamie Madille88ec8e2017-10-31 17:18:14 -0400973 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400974 }
975 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400976
977 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400978}
979
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -0400980angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500981{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500982 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -0500983
Jamie Madill49ac74b2017-12-21 14:42:33 -0500984 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500985 {
Yuly Novikov27780292018-11-09 11:19:49 -0500986 VkResult result = batch.fence.getStatus(mDevice);
987 if (result == VK_NOT_READY)
988 {
Jamie Madill0c0dc342017-03-24 14:18:51 -0400989 break;
Yuly Novikov27780292018-11-09 11:19:49 -0500990 }
991 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -0500992
Jamie Madill49ac74b2017-12-21 14:42:33 -0500993 ASSERT(batch.serial > mLastCompletedQueueSerial);
994 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400995
Jamie Madill49ac74b2017-12-21 14:42:33 -0500996 batch.fence.destroy(mDevice);
997 batch.commandPool.destroy(mDevice);
998 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500999 }
1000
Jamie Madill49ac74b2017-12-21 14:42:33 -05001001 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001002
1003 size_t freeIndex = 0;
1004 for (; freeIndex < mGarbage.size(); ++freeIndex)
1005 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001006 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001007 break;
1008 }
1009
1010 // Remove the entries from the garbage list - they should be ready to go.
1011 if (freeIndex > 0)
1012 {
1013 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001014 }
1015
Jamie Madill21061022018-07-12 23:56:30 -04001016 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001017}
1018
Jamie Madill21061022018-07-12 23:56:30 -04001019angle::Result RendererVk::submitFrame(vk::Context *context,
1020 const VkSubmitInfo &submitInfo,
1021 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001022{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001023 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001024 VkFenceCreateInfo fenceInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001025 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001026 fenceInfo.flags = 0;
1027
Jamie Madillbea35a62018-07-05 11:54:10 -04001028 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1029 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001030 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001031
Jamie Madill21061022018-07-12 23:56:30 -04001032 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001033
1034 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001035 batch.commandPool = std::move(mCommandPool);
1036 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001037
Jamie Madillbea35a62018-07-05 11:54:10 -04001038 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001039
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001040 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1041 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
1042 // so the limit is larger than the expected number of images.
1043 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001044
1045 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001046 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001047 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001048 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001049
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001050 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001051
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001052 if (mGpuEventsEnabled)
1053 {
1054 ANGLE_TRY(checkCompletedGpuEvents(context));
1055 }
1056
Jamie Madill49ac74b2017-12-21 14:42:33 -05001057 // Simply null out the command buffer here - it was allocated using the command pool.
1058 commandBuffer.releaseHandle();
1059
1060 // Reallocate the command pool for next frame.
1061 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001062 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001063 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001064 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001065 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001066
Yuly Novikov27780292018-11-09 11:19:49 -05001067 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
1068 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001069}
1070
Jamie Madillaaca96e2018-06-12 10:19:48 -04001071bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001072{
1073 return serial > mLastCompletedQueueSerial;
1074}
1075
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001076angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1077{
1078 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1079 {
1080 return angle::Result::Continue();
1081 }
1082
1083 // Find the first batch with serial equal to or bigger than given serial (note that
1084 // the batch serials are unique, otherwise upper-bound would have been necessary).
1085 size_t batchIndex = mInFlightCommands.size() - 1;
1086 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1087 {
1088 if (mInFlightCommands[i].serial >= serial)
1089 {
1090 batchIndex = i;
1091 break;
1092 }
1093 }
1094 const CommandBatch &batch = mInFlightCommands[batchIndex];
1095
1096 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001097 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001098
1099 // Clean up finished batches.
1100 return checkCompletedCommands(context);
1101}
1102
Jamie Madill21061022018-07-12 23:56:30 -04001103angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1104 const vk::RenderPassDesc &desc,
1105 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001106{
Jamie Madill21061022018-07-12 23:56:30 -04001107 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001108 renderPassOut);
1109}
1110
Jamie Madill21061022018-07-12 23:56:30 -04001111angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1112 const vk::RenderPassDesc &desc,
1113 const vk::AttachmentOpsArray &ops,
1114 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001115{
Jamie Madill21061022018-07-12 23:56:30 -04001116 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001117 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001118}
1119
Jamie Madilla5e06072018-05-18 14:36:05 -04001120vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001121{
Jamie Madilla5e06072018-05-18 14:36:05 -04001122 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001123}
1124
Jamie Madill21061022018-07-12 23:56:30 -04001125angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001126{
Jamie Madill21061022018-07-12 23:56:30 -04001127 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001128 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001129}
1130
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001131angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001132{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001133 if (mCommandGraph.empty())
1134 {
1135 return angle::Result::Continue();
1136 }
1137
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001138 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1139
Jamie Madillbea35a62018-07-05 11:54:10 -04001140 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1141 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001142
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001143 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001144 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1145 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001146
1147 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1148 // will be waited on.
1149 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001150
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001151 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001152 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001153 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1154 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001155 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001156 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001157 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001158 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001159 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001160
Jamie Madill21061022018-07-12 23:56:30 -04001161 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001162
Jamie Madill21061022018-07-12 23:56:30 -04001163 return angle::Result::Continue();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001164}
1165
Jamie Madill78feddc2018-04-27 11:45:05 -04001166Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001167{
Jamie Madill78feddc2018-04-27 11:45:05 -04001168 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001169}
1170
Jamie Madill21061022018-07-12 23:56:30 -04001171angle::Result RendererVk::getDescriptorSetLayout(
1172 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001173 const vk::DescriptorSetLayoutDesc &desc,
1174 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1175{
Jamie Madill21061022018-07-12 23:56:30 -04001176 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001177}
1178
Jamie Madill21061022018-07-12 23:56:30 -04001179angle::Result RendererVk::getPipelineLayout(
1180 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001181 const vk::PipelineLayoutDesc &desc,
1182 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1183 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1184{
Jamie Madill21061022018-07-12 23:56:30 -04001185 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001186 pipelineLayoutOut);
1187}
1188
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001189angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1190{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001191 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001192
1193 if (--mPipelineCacheVkUpdateTimeout > 0)
1194 {
1195 return angle::Result::Continue();
1196 }
1197
1198 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1199
1200 // Get the size of the cache.
1201 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001202 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001203 if (result != VK_INCOMPLETE)
1204 {
1205 ANGLE_VK_TRY(displayVk, result);
1206 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001207
1208 angle::MemoryBuffer *pipelineCacheData = nullptr;
1209 ANGLE_VK_CHECK_ALLOC(displayVk,
1210 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1211
1212 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001213 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001214 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1215 // was determined just above), so receiving it hints at an implementation bug we would want
1216 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001217 ASSERT(result != VK_INCOMPLETE);
1218 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001219
1220 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1221 // the buffer to avoid leaking garbage memory.
1222 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1223 if (pipelineCacheSize < originalPipelineCacheSize)
1224 {
1225 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1226 originalPipelineCacheSize - pipelineCacheSize);
1227 }
1228
1229 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1230
1231 return angle::Result::Continue();
1232}
1233
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001234angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1235 const vk::Semaphore **outSemaphore)
1236{
1237 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1238
1239 vk::SemaphoreHelper semaphore;
1240 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1241
1242 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1243 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1244
1245 return angle::Result::Continue();
1246}
1247
1248const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1249{
1250 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1251
1252 // Return the semaphore to the pool (which will remain valid and unused until the
1253 // queue it's about to be waited on has finished execution). The caller is about
1254 // to wait on it.
1255 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1256
1257 return semaphore;
1258}
1259
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001260angle::Result RendererVk::getFullScreenClearShaderProgram(vk::Context *context,
1261 vk::ShaderProgramHelper **programOut)
Jamie Madilld47044a2018-04-27 11:45:03 -04001262{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001263 if (!mFullScreenClearShaderProgram.valid())
1264 {
1265 vk::RefCounted<vk::ShaderAndSerial> *fullScreenQuad = nullptr;
1266 ANGLE_TRY(mShaderLibrary.getShader(context, vk::InternalShaderID::FullScreenQuad_vert,
1267 &fullScreenQuad));
1268
1269 vk::RefCounted<vk::ShaderAndSerial> *pushConstantColor = nullptr;
1270 ANGLE_TRY(mShaderLibrary.getShader(context, vk::InternalShaderID::PushConstantColor_frag,
1271 &pushConstantColor));
1272
1273 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Vertex, fullScreenQuad);
1274 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Fragment, pushConstantColor);
1275 }
1276
1277 *programOut = &mFullScreenClearShaderProgram;
1278 return angle::Result::Continue();
Jamie Madilld47044a2018-04-27 11:45:03 -04001279}
Luc Ferron90968362018-05-04 08:47:22 -04001280
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001281angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1282{
1283 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1284 // that seems impossible, so instead, we are going to make a small submission with just a
1285 // timestamp query. First, the disjoint timer query extension says:
1286 //
1287 // > This will return the GL time after all previous commands have reached the GL server but
1288 // have not yet necessarily executed.
1289 //
1290 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1291 // The wording allows us to make a submission to get the timestamp without performing a flush.
1292 //
1293 // Second:
1294 //
1295 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1296 // object target, applications can measure the latency between when commands reach the GL server
1297 // and when they are realized in the framebuffer.
1298 //
1299 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1300 // GPU bubble. This function directly generates a command buffer and submits it instead of
1301 // using the other member functions. This is to avoid changing any state, such as the queue
1302 // serial.
1303
1304 // Create a query used to receive the GPU timestamp
1305 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1306 vk::QueryHelper timestampQuery;
1307 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1308 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1309
1310 // Record the command buffer
1311 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1312 vk::CommandBuffer &commandBuffer = commandBatch.get();
1313
1314 VkCommandBufferAllocateInfo commandBufferInfo = {};
1315 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1316 commandBufferInfo.commandPool = mCommandPool.getHandle();
1317 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1318 commandBufferInfo.commandBufferCount = 1;
1319
Yuly Novikov27780292018-11-09 11:19:49 -05001320 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001321
1322 VkCommandBufferBeginInfo beginInfo = {};
1323 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1324 beginInfo.flags = 0;
1325 beginInfo.pInheritanceInfo = nullptr;
1326
Yuly Novikov27780292018-11-09 11:19:49 -05001327 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001328
1329 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1330 timestampQuery.getQuery(), 1);
1331 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1332 timestampQuery.getQueryPool()->getHandle(),
1333 timestampQuery.getQuery());
1334
Yuly Novikov27780292018-11-09 11:19:49 -05001335 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001336
1337 // Create fence for the submission
1338 VkFenceCreateInfo fenceInfo = {};
1339 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1340 fenceInfo.flags = 0;
1341
1342 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001343 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001344
1345 // Submit the command buffer
1346 VkSubmitInfo submitInfo = {};
1347 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1348 submitInfo.waitSemaphoreCount = 0;
1349 submitInfo.pWaitSemaphores = nullptr;
1350 submitInfo.pWaitDstStageMask = nullptr;
1351 submitInfo.commandBufferCount = 1;
1352 submitInfo.pCommandBuffers = commandBuffer.ptr();
1353 submitInfo.signalSemaphoreCount = 0;
1354 submitInfo.pSignalSemaphores = nullptr;
1355
1356 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1357
1358 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1359 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001360 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001361
1362 // Get the query results
1363 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1364
Yuly Novikov27780292018-11-09 11:19:49 -05001365 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1366 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1367 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001368
1369 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1370
1371 return angle::Result::Continue();
1372}
1373
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001374angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1375{
1376 ASSERT(mGpuEventsEnabled);
1377
1378 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1379 ASSERT(platform);
1380
1381 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1382 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1383 //
1384 // CPU GPU
1385 //
1386 // Record command buffer
1387 // with timestamp query
1388 //
1389 // Submit command buffer
1390 //
1391 // Post-submission work Begin execution
1392 //
1393 // ???? Write timstamp Tgpu
1394 //
1395 // ???? End execution
1396 //
1397 // ???? Return query results
1398 //
1399 // ????
1400 //
1401 // Get query results
1402 //
1403 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1404 // finished post-submission work while the GPU is executing in parallel. With no further work,
1405 // querying CPU timestamps before submission and after getting query results give the bounds to
1406 // Tgpu, which could be quite large.
1407 //
1408 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1409 // reduce this range. This function implements the following procedure:
1410 //
1411 // CPU GPU
1412 //
1413 // Record command buffer
1414 // with timestamp query
1415 //
1416 // Submit command buffer
1417 //
1418 // Post-submission work Begin execution
1419 //
1420 // ???? Set Event GPUReady
1421 //
1422 // Wait on Event GPUReady Wait on Event CPUReady
1423 //
1424 // Get CPU Time Ts Wait on Event CPUReady
1425 //
1426 // Set Event CPUReady Wait on Event CPUReady
1427 //
1428 // Get CPU Time Tcpu Get GPU Time Tgpu
1429 //
1430 // Wait on Event GPUDone Set Event GPUDone
1431 //
1432 // Get CPU Time Te End Execution
1433 //
1434 // Idle Return query results
1435 //
1436 // Get query results
1437 //
1438 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1439 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1440 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1441 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1442 // calibration.
1443 //
1444 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1445
1446 // Make sure nothing is running
1447 ASSERT(mCommandGraph.empty());
1448
1449 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1450
1451 // Create a query used to receive the GPU timestamp
1452 vk::QueryHelper timestampQuery;
1453 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1454
1455 // Create the three events
1456 VkEventCreateInfo eventCreateInfo = {};
1457 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1458 eventCreateInfo.flags = 0;
1459
1460 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001461 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1462 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1463 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001464
1465 constexpr uint32_t kRetries = 10;
1466
1467 // Time suffixes used are S for seconds and Cycles for cycles
1468 double tightestRangeS = 1e6f;
1469 double TcpuS = 0;
1470 uint64_t TgpuCycles = 0;
1471 for (uint32_t i = 0; i < kRetries; ++i)
1472 {
1473 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001474 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1475 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1476 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001477
1478 // Record the command buffer
1479 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1480 vk::CommandBuffer &commandBuffer = commandBatch.get();
1481
1482 VkCommandBufferAllocateInfo commandBufferInfo = {};
1483 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1484 commandBufferInfo.commandPool = mCommandPool.getHandle();
1485 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1486 commandBufferInfo.commandBufferCount = 1;
1487
Yuly Novikov27780292018-11-09 11:19:49 -05001488 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001489
1490 VkCommandBufferBeginInfo beginInfo = {};
1491 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1492 beginInfo.flags = 0;
1493 beginInfo.pInheritanceInfo = nullptr;
1494
Yuly Novikov27780292018-11-09 11:19:49 -05001495 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001496
1497 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1498 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1499 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1500 nullptr);
1501
1502 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1503 timestampQuery.getQuery(), 1);
1504 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1505 timestampQuery.getQueryPool()->getHandle(),
1506 timestampQuery.getQuery());
1507
1508 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1509
Yuly Novikov27780292018-11-09 11:19:49 -05001510 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001511
1512 // Submit the command buffer
1513 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1514 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1515 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1516
1517 VkSubmitInfo submitInfo = {};
1518 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1519 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1520 submitInfo.pWaitSemaphores = waitSemaphores.data();
1521 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1522 submitInfo.commandBufferCount = 1;
1523 submitInfo.pCommandBuffers = commandBuffer.ptr();
1524 submitInfo.signalSemaphoreCount = 0;
1525 submitInfo.pSignalSemaphores = nullptr;
1526
1527 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1528
1529 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001530 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001531 do
1532 {
Yuly Novikov27780292018-11-09 11:19:49 -05001533 result = gpuReady.get().getStatus(mDevice);
1534 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1535 {
1536 ANGLE_VK_TRY(context, result);
1537 }
1538 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001539
1540 double TsS = platform->monotonicallyIncreasingTime(platform);
1541
1542 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001543 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001544 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1545
1546 // Wait for GPU to be done. Another short busy wait.
1547 do
1548 {
Yuly Novikov27780292018-11-09 11:19:49 -05001549 result = gpuDone.get().getStatus(mDevice);
1550 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1551 {
1552 ANGLE_VK_TRY(context, result);
1553 }
1554 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001555
1556 double TeS = platform->monotonicallyIncreasingTime(platform);
1557
1558 // Get the query results
1559 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1560
1561 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1562
1563 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001564 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1565 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1566 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001567
1568 // Use the first timestamp queried as origin.
1569 if (mGpuEventTimestampOrigin == 0)
1570 {
1571 mGpuEventTimestampOrigin = gpuTimestampCycles;
1572 }
1573
1574 // Take these CPU and GPU timestamps if there is better confidence.
1575 double confidenceRangeS = TeS - TsS;
1576 if (confidenceRangeS < tightestRangeS)
1577 {
1578 tightestRangeS = confidenceRangeS;
1579 TcpuS = cpuTimestampS;
1580 TgpuCycles = gpuTimestampCycles;
1581 }
1582 }
1583
1584 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1585
1586 // timestampPeriod gives nanoseconds/cycle.
1587 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1588 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1589 1'000'000'000.0;
1590
1591 flushGpuEvents(TgpuS, TcpuS);
1592
1593 mGpuClockSync.gpuTimestampS = TgpuS;
1594 mGpuClockSync.cpuTimestampS = TcpuS;
1595
1596 return angle::Result::Continue();
1597}
1598
1599angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1600 vk::CommandBuffer *commandBuffer,
1601 char phase,
1602 const char *name)
1603{
1604 ASSERT(mGpuEventsEnabled);
1605
1606 GpuEventQuery event;
1607
1608 event.name = name;
1609 event.phase = phase;
1610 event.serial = mCurrentQueueSerial;
1611
1612 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1613
1614 commandBuffer->resetQueryPool(
1615 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1616 commandBuffer->writeTimestamp(
1617 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1618 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1619
1620 mInFlightGpuEventQueries.push_back(std::move(event));
1621
1622 return angle::Result::Continue();
1623}
1624
1625angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1626{
1627 ASSERT(mGpuEventsEnabled);
1628
1629 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1630 ASSERT(platform);
1631
1632 int finishedCount = 0;
1633
1634 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1635 {
1636 // Only check the timestamp query if the submission has finished.
1637 if (eventQuery.serial > mLastCompletedQueueSerial)
1638 {
1639 break;
1640 }
1641
1642 // See if the results are available.
1643 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001644 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1645 ->getResults(mDevice, eventQuery.queryIndex, 1,
1646 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1647 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1648 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001649 {
1650 break;
1651 }
Yuly Novikov27780292018-11-09 11:19:49 -05001652 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001653
1654 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1655
1656 GpuEvent event;
1657 event.gpuTimestampCycles = gpuTimestampCycles;
1658 event.name = eventQuery.name;
1659 event.phase = eventQuery.phase;
1660
1661 mGpuEvents.emplace_back(event);
1662
1663 ++finishedCount;
1664 }
1665
1666 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1667 mInFlightGpuEventQueries.begin() + finishedCount);
1668
1669 return angle::Result::Continue();
1670}
1671
1672void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1673{
1674 if (mGpuEvents.size() == 0)
1675 {
1676 return;
1677 }
1678
1679 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1680 ASSERT(platform);
1681
1682 // Find the slope of the clock drift for adjustment
1683 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1684 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1685 double gpuSyncDriftSlope = 0;
1686
1687 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1688 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1689
1690 // No gpu trace events should have been generated before the clock sync, so if there is no
1691 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1692 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1693 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1694
1695 gpuSyncDriftSlope =
1696 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1697
1698 for (const GpuEvent &event : mGpuEvents)
1699 {
1700 double gpuTimestampS =
1701 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1702 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1703
1704 // Account for clock drift.
1705 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1706
1707 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1708 // for.
1709 static long long eventId = 1;
1710 static const unsigned char *categoryEnabled =
1711 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1712 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1713 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1714 }
1715
1716 mGpuEvents.clear();
1717}
1718
Jamie Madillaaca96e2018-06-12 10:19:48 -04001719uint32_t GetUniformBufferDescriptorCount()
1720{
1721 return kUniformBufferDescriptorsPerDescriptorSet;
1722}
1723
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001724} // namespace rx