blob: 520a621ebe112e8ef252ccb5369d1ab28e5a3ca6 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050018#include "common/system_utils.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040019#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050020#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050021#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050022#include "libANGLE/renderer/vulkan/CompilerVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040023#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050025#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050026#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050028#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050029#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040031
Shahbaz Youssefi61656022018-10-24 15:00:50 -040032#include "third_party/trace_event/trace_event.h"
33
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070034// Consts
35namespace
36{
Jamie Madill7c985f52018-11-29 18:16:17 -050037const uint32_t kMockVendorID = 0xba5eba11;
38const uint32_t kMockDeviceID = 0xf005ba11;
39constexpr char kMockDeviceName[] = "Vulkan Mock Device";
40constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050041constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070042} // anonymous namespace
43
Jamie Madill9e54b5a2016-05-25 12:57:39 -040044namespace rx
45{
46
Jamie Madille09bd5d2016-11-29 16:20:35 -050047namespace
48{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040049// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
50// one for the vertex shader.
51constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040052// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
53static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040054// Wait a maximum of 10s. If that times out, we declare it a failure.
55static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050056
Omar El Sheikh26c61b22018-06-29 12:50:59 -060057bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
58{
59#if !defined(ANGLE_PLATFORM_ANDROID)
60 // Mock ICD does not currently run on Android
61 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
62 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
63 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
64#else
65 return false;
66#endif // !defined(ANGLE_PLATFORM_ANDROID)
67}
68
Jamie Madille09bd5d2016-11-29 16:20:35 -050069VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
70 const std::vector<const char *> &enabledExtensionNames)
71{
72 // Compile the extensions names into a set.
73 std::set<std::string> extensionNames;
74 for (const auto &extensionProp : extensionProps)
75 {
76 extensionNames.insert(extensionProp.extensionName);
77 }
78
Jamie Madillacf2f3a2017-11-21 19:22:44 -050079 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050080 {
81 if (extensionNames.count(extensionName) == 0)
82 {
83 return VK_ERROR_EXTENSION_NOT_PRESENT;
84 }
85 }
86
87 return VK_SUCCESS;
88}
89
Tobin Ehlis3a181e32018-08-29 15:17:05 -060090// Array of Validation error/warning messages that will be ignored, should include bugID
91constexpr std::array<const char *, 1> kSkippedMessages = {
92 // http://anglebug.com/2796
93 " [ UNASSIGNED-CoreValidation-Shader-PointSizeMissing ] Object: VK_NULL_HANDLE (Type = 19) "
94 "| Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader "
95 "corresponding to VK_SHADER_STAGE_VERTEX_BIT."};
96
97// Suppress validation errors that are known
98// return "true" if given code/prefix/message is known, else return "false"
99bool IsIgnoredDebugMessage(const char *message)
100{
101 for (const auto &msg : kSkippedMessages)
102 {
103 if (strcmp(msg, message) == 0)
104 {
105 return true;
106 }
107 }
108 return false;
109}
110
Yuly Novikov199f4292018-01-19 19:04:05 -0500111VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
112 VkDebugReportObjectTypeEXT objectType,
113 uint64_t object,
114 size_t location,
115 int32_t messageCode,
116 const char *layerPrefix,
117 const char *message,
118 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500119{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600120 if (IsIgnoredDebugMessage(message))
121 {
122 return VK_FALSE;
123 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500124 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
125 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500126 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500127#if !defined(NDEBUG)
128 // Abort the call in Debug builds.
129 return VK_TRUE;
130#endif
131 }
132 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
133 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500134 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500135 }
136 else
137 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500138 // Uncomment this if you want Vulkan spam.
139 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500140 }
141
142 return VK_FALSE;
143}
144
Yuly Novikov199f4292018-01-19 19:04:05 -0500145// If we're loading the validation layers, we could be running from any random directory.
146// Change to the executable directory so we can find the layers, then change back to the
147// previous directory to be safe we don't disrupt the application.
148class ScopedVkLoaderEnvironment : angle::NonCopyable
149{
150 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600151 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
152 : mEnableValidationLayers(enableValidationLayers),
153 mEnableMockICD(enableMockICD),
154 mChangedCWD(false),
155 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500156 {
157// Changing CWD and setting environment variables makes no sense on Android,
158// since this code is a part of Java application there.
159// Android Vulkan loader doesn't need this either.
160#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600161 if (enableMockICD)
162 {
163 // Override environment variable to use built Mock ICD
164 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
165 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
166 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
167 if (!mChangedICDPath)
168 {
169 ERR() << "Error setting Path for Mock/Null Driver.";
170 mEnableMockICD = false;
171 }
172 }
Jamie Madill46848422018-08-09 10:46:06 -0400173 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500174 {
175 const auto &cwd = angle::GetCWD();
176 if (!cwd.valid())
177 {
178 ERR() << "Error getting CWD for Vulkan layers init.";
179 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400180 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500181 }
182 else
183 {
184 mPreviousCWD = cwd.value();
185 const char *exeDir = angle::GetExecutableDirectory();
186 mChangedCWD = angle::SetCWD(exeDir);
187 if (!mChangedCWD)
188 {
189 ERR() << "Error setting CWD for Vulkan layers init.";
190 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400191 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500192 }
193 }
194 }
195
196 // Override environment variable to use the ANGLE layers.
197 if (mEnableValidationLayers)
198 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700199 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500200 {
201 ERR() << "Error setting environment for Vulkan layers init.";
202 mEnableValidationLayers = false;
203 }
204 }
205#endif // !defined(ANGLE_PLATFORM_ANDROID)
206 }
207
208 ~ScopedVkLoaderEnvironment()
209 {
210 if (mChangedCWD)
211 {
212#if !defined(ANGLE_PLATFORM_ANDROID)
213 ASSERT(mPreviousCWD.valid());
214 angle::SetCWD(mPreviousCWD.value().c_str());
215#endif // !defined(ANGLE_PLATFORM_ANDROID)
216 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600217 if (mChangedICDPath)
218 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600219 if (mPreviousICDPath.value().empty())
220 {
221 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
222 }
223 else
224 {
225 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
226 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600227 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500228 }
229
Jamie Madillaaca96e2018-06-12 10:19:48 -0400230 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500231
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600232 bool canEnableMockICD() const { return mEnableMockICD; }
233
Yuly Novikov199f4292018-01-19 19:04:05 -0500234 private:
235 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600236 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500237 bool mChangedCWD;
238 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600239 bool mChangedICDPath;
240 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500241};
242
Jamie Madill21061022018-07-12 23:56:30 -0400243void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
244 bool preferMockICD,
245 VkPhysicalDevice *physicalDeviceOut,
246 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
247{
248 ASSERT(!physicalDevices.empty());
249 if (preferMockICD)
250 {
251 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
252 {
253 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
254 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
255 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
256 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
257 {
258 *physicalDeviceOut = physicalDevice;
259 return;
260 }
261 }
262 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
263 "physicalDevice instead.";
264 }
265
266 // Fall back to first device.
267 *physicalDeviceOut = physicalDevices[0];
268 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
269}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400270
271// Initially dumping the command graphs is disabled.
272constexpr bool kEnableCommandGraphDiagnostics = false;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500273} // anonymous namespace
274
Jamie Madill49ac74b2017-12-21 14:42:33 -0500275// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400276RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500277
Jamie Madillaaca96e2018-06-12 10:19:48 -0400278RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500279
280RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
281 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500282{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500283
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)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500318{
319 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
320 mFormatProperties.fill(invalid);
321}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400322
Jamie Madillb980c562018-11-27 11:34:27 -0500323RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400324
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
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500333 mDispatchUtils.destroy(mDevice);
334
Jamie Madillc7918ce2018-06-13 13:25:31 -0400335 mPipelineLayoutCache.destroy(mDevice);
336 mDescriptorSetLayoutCache.destroy(mDevice);
337
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500338 mFullScreenClearShaderProgram.destroy(mDevice);
339
Jamie Madill9f2a8612017-11-30 12:43:09 -0500340 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500341 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400342 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400343 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400344 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500345
Jamie Madill06ca6342018-07-12 15:56:53 -0400346 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500347
Jamie Madill5deea722017-02-16 10:44:46 -0500348 if (mCommandPool.valid())
349 {
350 mCommandPool.destroy(mDevice);
351 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500352
353 if (mDevice)
354 {
355 vkDestroyDevice(mDevice, nullptr);
356 mDevice = VK_NULL_HANDLE;
357 }
358
Jamie Madill0448ec82016-12-23 13:41:47 -0500359 if (mDebugReportCallback)
360 {
361 ASSERT(mInstance);
362 auto destroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
363 vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT"));
364 ASSERT(destroyDebugReportCallback);
365 destroyDebugReportCallback(mInstance, mDebugReportCallback, nullptr);
366 }
367
Jamie Madill4d0bf552016-12-28 15:45:24 -0500368 if (mInstance)
369 {
370 vkDestroyInstance(mInstance, nullptr);
371 mInstance = VK_NULL_HANDLE;
372 }
373
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600374 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500375 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500376}
377
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400378void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400379{
380 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400381
382 mCommandGraph.clear();
383 mLastSubmittedQueueSerial = mCurrentQueueSerial;
384 mCurrentQueueSerial = mQueueSerialFactory.generate();
385 freeAllInFlightResources();
386
387 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400388}
389
390bool RendererVk::isDeviceLost() const
391{
392 return mDeviceLost;
393}
394
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400395angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400396 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400397 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500398{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400399 mDisplay = display;
400 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600401 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
402 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500403 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400404 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500405
Jamie Madill0448ec82016-12-23 13:41:47 -0500406 // Gather global layer properties.
407 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400408 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500409
410 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
411 if (instanceLayerCount > 0)
412 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400413 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
414 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500415 }
416
Jamie Madille09bd5d2016-11-29 16:20:35 -0500417 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400418 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400419 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500420
421 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
422 if (instanceExtensionCount > 0)
423 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400424 ANGLE_VK_TRY(displayVk,
425 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
426 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500427 }
428
Yuly Novikov199f4292018-01-19 19:04:05 -0500429 const char *const *enabledLayerNames = nullptr;
430 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500431 if (mEnableValidationLayers)
432 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500433 bool layersRequested =
434 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
435 mEnableValidationLayers = GetAvailableValidationLayers(
436 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500437 }
438
Jamie Madille09bd5d2016-11-29 16:20:35 -0500439 std::vector<const char *> enabledInstanceExtensions;
440 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500441 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500442
Jamie Madill0448ec82016-12-23 13:41:47 -0500443 // TODO(jmadill): Should be able to continue initialization if debug report ext missing.
444 if (mEnableValidationLayers)
445 {
446 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
447 }
448
Jamie Madille09bd5d2016-11-29 16:20:35 -0500449 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400450 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400451 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500452
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400453 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500454 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500455 applicationInfo.pApplicationName = "ANGLE";
456 applicationInfo.applicationVersion = 1;
457 applicationInfo.pEngineName = "ANGLE";
458 applicationInfo.engineVersion = 1;
459 applicationInfo.apiVersion = VK_API_VERSION_1_0;
460
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400461 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500462 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
463 instanceInfo.flags = 0;
464 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500465
Jamie Madille09bd5d2016-11-29 16:20:35 -0500466 // Enable requested layers and extensions.
467 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
468 instanceInfo.ppEnabledExtensionNames =
469 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500470 instanceInfo.enabledLayerCount = enabledLayerCount;
471 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500472
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400473 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500474
Jamie Madill0448ec82016-12-23 13:41:47 -0500475 if (mEnableValidationLayers)
476 {
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400477 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500478
479 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500480 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
481 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
482 VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
483 debugReportInfo.pfnCallback = &DebugReportCallback;
484 debugReportInfo.pUserData = this;
485
486 auto createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
487 vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT"));
488 ASSERT(createDebugReportCallback);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400489 ANGLE_VK_TRY(displayVk, createDebugReportCallback(mInstance, &debugReportInfo, nullptr,
490 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500491 }
492
Jamie Madill4d0bf552016-12-28 15:45:24 -0500493 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400494 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
495 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500496
497 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700498 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400499 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
500 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400501 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700502 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500503
Jamie Madill30b5d842018-08-31 17:19:12 -0400504 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
505
Jamie Madill4d0bf552016-12-28 15:45:24 -0500506 // Ensure we can find a graphics queue family.
507 uint32_t queueCount = 0;
508 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
509
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400510 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500511
512 mQueueFamilyProperties.resize(queueCount);
513 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
514 mQueueFamilyProperties.data());
515
Jamie Madillb980c562018-11-27 11:34:27 -0500516 size_t graphicsQueueFamilyCount = false;
517 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500518 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500519 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
520 {
521 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500522 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500523 {
524 ASSERT(queueInfo.queueCount > 0);
525 graphicsQueueFamilyCount++;
526 if (firstGraphicsQueueFamily == 0)
527 {
528 firstGraphicsQueueFamily = familyIndex;
529 }
530 break;
531 }
532 }
533
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400534 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500535
Jamie Madill12222072018-07-11 14:59:48 -0400536 initFeatures();
537
Jamie Madill4d0bf552016-12-28 15:45:24 -0500538 // If only one queue family, go ahead and initialize the device. If there is more than one
539 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
540 if (graphicsQueueFamilyCount == 1)
541 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400542 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500543 }
544
Jamie Madill035fd6b2017-10-03 15:43:22 -0400545 // Store the physical device memory properties so we can find the right memory pools.
546 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500547
Jamie Madill06ca6342018-07-12 15:56:53 -0400548 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500549
Jamie Madill6a89d222017-11-02 11:59:51 -0400550 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500551 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400552
Jamie Madill7c985f52018-11-29 18:16:17 -0500553 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400554}
555
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400556angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500557{
558 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400559 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400560 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500561
562 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
563 if (deviceLayerCount > 0)
564 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400565 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
566 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 }
568
569 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400570 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
571 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500572
573 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
574 if (deviceExtensionCount > 0)
575 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400576 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
577 &deviceExtensionCount,
578 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500579 }
580
Yuly Novikov199f4292018-01-19 19:04:05 -0500581 const char *const *enabledLayerNames = nullptr;
582 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500583 if (mEnableValidationLayers)
584 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500585 mEnableValidationLayers = GetAvailableValidationLayers(
586 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500587 }
588
589 std::vector<const char *> enabledDeviceExtensions;
590 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
591
Luc Ferronbf6dc372018-06-28 15:24:19 -0400592 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
593 if (getFeatures().flipViewportY)
594 {
595 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
596 }
597
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400598 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500599
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400600 // Select additional features to be enabled
601 VkPhysicalDeviceFeatures enabledFeatures = {};
602 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
603
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400604 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500605
606 float zeroPriority = 0.0f;
607
608 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500609 queueCreateInfo.flags = 0;
610 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
611 queueCreateInfo.queueCount = 1;
612 queueCreateInfo.pQueuePriorities = &zeroPriority;
613
614 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400615 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500616
Jamie Madill50cf2be2018-06-15 09:46:57 -0400617 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400618 createInfo.flags = 0;
619 createInfo.queueCreateInfoCount = 1;
620 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500621 createInfo.enabledLayerCount = enabledLayerCount;
622 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500623 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
624 createInfo.ppEnabledExtensionNames =
625 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400626 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500627
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400628 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500629
630 mCurrentQueueFamilyIndex = queueFamilyIndex;
631
632 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
633
634 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400635 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500636 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
637 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
638 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500639
Yuly Novikov27780292018-11-09 11:19:49 -0500640 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400641
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400642 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500643 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500644
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400645 // Initialize the submission semaphore pool.
646 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
647
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400648#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
649 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
650 ASSERT(platform);
651
652 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
653 // platform discovery.
654 const unsigned char *gpuEventsEnabled =
655 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
656 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
657#endif
658
659 if (mGpuEventsEnabled)
660 {
661 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
662 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
663 vk::kDefaultTimestampQueryPoolSize));
664 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
665 }
666
Jamie Madill7c985f52018-11-29 18:16:17 -0500667 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500668}
669
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400670angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400671 VkSurfaceKHR surface,
672 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500673{
674 // We've already initialized a device, and can't re-create it unless it's never been used.
675 // TODO(jmadill): Handle the re-creation case if necessary.
676 if (mDevice != VK_NULL_HANDLE)
677 {
678 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
679
680 // Check if the current device supports present on this surface.
681 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400682 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400683 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500684 surface, &supportsPresent));
685
Jamie Madill6cad7732018-07-11 09:01:17 -0400686 if (supportsPresent == VK_TRUE)
687 {
688 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500689 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400690 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500691 }
692
693 // Find a graphics and present queue.
694 Optional<uint32_t> newPresentQueue;
695 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500696 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500697 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
698 {
699 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500700 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500701 {
702 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400703 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
704 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500705
706 if (supportsPresent == VK_TRUE)
707 {
708 newPresentQueue = queueIndex;
709 break;
710 }
711 }
712 }
713
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400714 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
715 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500716
Jamie Madill6cad7732018-07-11 09:01:17 -0400717 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500718 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500719}
720
721std::string RendererVk::getVendorString() const
722{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300723 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500724}
725
Jamie Madille09bd5d2016-11-29 16:20:35 -0500726std::string RendererVk::getRendererDescription() const
727{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500728 std::stringstream strstr;
729
730 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
731
732 strstr << "Vulkan ";
733 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
734 strstr << VK_VERSION_MINOR(apiVersion) << ".";
735 strstr << VK_VERSION_PATCH(apiVersion);
736
Olli Etuahoc6a06182018-04-13 14:11:46 +0300737 strstr << "(";
738
739 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
740 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
741 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
742 // driver detection.
743 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
744 {
745 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
746 }
747
748 strstr << mPhysicalDeviceProperties.deviceName << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500749
750 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500751}
752
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500753gl::Version RendererVk::getMaxSupportedESVersion() const
754{
755 // Declare GLES2 support if necessary features for GLES3 are missing
756 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
757
758 if (!necessaryFeaturesForES3)
759 {
760 return gl::Version(2, 0);
761 }
762
763 return gl::Version(3, 0);
764}
765
Jamie Madill12222072018-07-11 14:59:48 -0400766void RendererVk::initFeatures()
767{
Jamie Madillb36a4812018-09-25 10:15:11 -0400768// Use OpenGL line rasterization rules by default.
769// TODO(jmadill): Fix Android support. http://anglebug.com/2830
770#if defined(ANGLE_PLATFORM_ANDROID)
771 mFeatures.basicGLLineRasterization = false;
772#else
Jamie Madill12222072018-07-11 14:59:48 -0400773 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400774#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400775
Luc Ferronf786b702018-07-10 11:01:43 -0400776 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
777 // investigation. http://anglebug.com/2728
778 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400779
780#ifdef ANGLE_PLATFORM_WINDOWS
781 // http://anglebug.com/2838
782 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
783#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400784
785 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
786 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -0500787
788 // Work around incorrect NVIDIA point size range clamping.
789 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
790 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
791 {
792 mFeatures.clampPointSize = true;
793 }
Jamie Madill12222072018-07-11 14:59:48 -0400794}
795
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400796void RendererVk::initPipelineCacheVkKey()
797{
798 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
799 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
800 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
801 // there is no '\0' in the result.
802 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
803 {
804 hashStream << std::hex << c;
805 }
806 // Add the vendor and device id too for good measure.
807 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
808 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
809
810 const std::string &hashString = hashStream.str();
811 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
812 hashString.length(), mPipelineCacheVkBlobKey.data());
813}
814
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500815angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400816{
817 initPipelineCacheVkKey();
818
819 egl::BlobCache::Value initialData;
820 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
821 mPipelineCacheVkBlobKey, &initialData);
822
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400823 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400824
825 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400826 pipelineCacheCreateInfo.flags = 0;
827 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
828 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
829
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500830 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -0500831 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400832}
833
Jamie Madillacccc6c2016-05-03 17:22:10 -0400834void RendererVk::ensureCapsInitialized() const
835{
836 if (!mCapsInitialized)
837 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400838 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
839 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
840 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400841 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400842 mCapsInitialized = true;
843 }
844}
845
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400846void RendererVk::getSubmitWaitSemaphores(
847 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400848 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
849 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400850{
851 if (mSubmitLastSignaledSemaphore.getSemaphore())
852 {
853 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400854 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400855
856 // Return the semaphore to the pool (which will remain valid and unused until the
857 // queue it's about to be waited on has finished execution).
858 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
859 }
860
861 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
862 {
863 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400864 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
865
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400866 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
867 }
868 mSubmitWaitSemaphores.clear();
869}
870
Jamie Madillacccc6c2016-05-03 17:22:10 -0400871const gl::Caps &RendererVk::getNativeCaps() const
872{
873 ensureCapsInitialized();
874 return mNativeCaps;
875}
876
877const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
878{
879 ensureCapsInitialized();
880 return mNativeTextureCaps;
881}
882
883const gl::Extensions &RendererVk::getNativeExtensions() const
884{
885 ensureCapsInitialized();
886 return mNativeExtensions;
887}
888
889const gl::Limitations &RendererVk::getNativeLimitations() const
890{
891 ensureCapsInitialized();
892 return mNativeLimitations;
893}
894
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400895uint32_t RendererVk::getMaxActiveTextures()
896{
897 // TODO(lucferron): expose this limitation to GL in Context Caps
898 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
899 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
900}
901
Jamie Madill49ac74b2017-12-21 14:42:33 -0500902const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500903{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500904 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500905}
906
Jamie Madill21061022018-07-12 23:56:30 -0400907angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500908{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500909 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500910 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400911 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
912
Luc Ferron1617e692018-07-11 11:08:19 -0400913 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
914 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400915
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400916 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400917 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
918 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400919
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400920 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500921 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400922 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
923 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400924 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500925 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400926 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500927 submitInfo.signalSemaphoreCount = 0;
928 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500929
Jamie Madill21061022018-07-12 23:56:30 -0400930 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500931 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500932
Jamie Madill4c26fc22017-02-24 11:04:10 -0500933 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400934 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400935 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400936
937 if (mGpuEventsEnabled)
938 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400939 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400940 while (mInFlightGpuEventQueries.size() > 0)
941 {
942 ANGLE_TRY(checkCompletedGpuEvents(context));
943 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400944 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
945 // synchronization if there is no event to be adjusted (happens when finish() gets called
946 // multiple times towards the end of the application).
947 if (mGpuEvents.size() > 0)
948 {
949 ANGLE_TRY(synchronizeCpuGpuTime(context));
950 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400951 }
952
Jamie Madill7c985f52018-11-29 18:16:17 -0500953 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500954}
955
Jamie Madill0c0dc342017-03-24 14:18:51 -0400956void RendererVk::freeAllInFlightResources()
957{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500958 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400959 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400960 // On device loss we need to wait for fence to be signaled before destroying it
961 if (mDeviceLost)
962 {
963 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
964 // If wait times out, it is probably not possible to recover from lost device
965 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
966 }
Jamie Madill49ac74b2017-12-21 14:42:33 -0500967 batch.fence.destroy(mDevice);
968 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400969 }
970 mInFlightCommands.clear();
971
972 for (auto &garbage : mGarbage)
973 {
Jamie Madille88ec8e2017-10-31 17:18:14 -0400974 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400975 }
976 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400977
978 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400979}
980
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -0400981angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500982{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500983 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -0500984
Jamie Madill49ac74b2017-12-21 14:42:33 -0500985 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500986 {
Yuly Novikov27780292018-11-09 11:19:49 -0500987 VkResult result = batch.fence.getStatus(mDevice);
988 if (result == VK_NOT_READY)
989 {
Jamie Madill0c0dc342017-03-24 14:18:51 -0400990 break;
Yuly Novikov27780292018-11-09 11:19:49 -0500991 }
992 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -0500993
Jamie Madill49ac74b2017-12-21 14:42:33 -0500994 ASSERT(batch.serial > mLastCompletedQueueSerial);
995 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400996
Jamie Madill49ac74b2017-12-21 14:42:33 -0500997 batch.fence.destroy(mDevice);
998 batch.commandPool.destroy(mDevice);
999 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001000 }
1001
Jamie Madill49ac74b2017-12-21 14:42:33 -05001002 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001003
1004 size_t freeIndex = 0;
1005 for (; freeIndex < mGarbage.size(); ++freeIndex)
1006 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001007 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001008 break;
1009 }
1010
1011 // Remove the entries from the garbage list - they should be ready to go.
1012 if (freeIndex > 0)
1013 {
1014 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001015 }
1016
Jamie Madill7c985f52018-11-29 18:16:17 -05001017 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001018}
1019
Jamie Madill21061022018-07-12 23:56:30 -04001020angle::Result RendererVk::submitFrame(vk::Context *context,
1021 const VkSubmitInfo &submitInfo,
1022 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001023{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001024 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001025 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001026 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1027 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001028
Jamie Madillbea35a62018-07-05 11:54:10 -04001029 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1030 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001031 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001032
Jamie Madill21061022018-07-12 23:56:30 -04001033 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001034
1035 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001036 batch.commandPool = std::move(mCommandPool);
1037 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001038
Jamie Madillbea35a62018-07-05 11:54:10 -04001039 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001040
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001041 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1042 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
1043 // so the limit is larger than the expected number of images.
1044 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001045
1046 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001047 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001048 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001049 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001050
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001051 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001052
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001053 if (mGpuEventsEnabled)
1054 {
1055 ANGLE_TRY(checkCompletedGpuEvents(context));
1056 }
1057
Jamie Madill49ac74b2017-12-21 14:42:33 -05001058 // Simply null out the command buffer here - it was allocated using the command pool.
1059 commandBuffer.releaseHandle();
1060
1061 // Reallocate the command pool for next frame.
1062 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001063 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001064 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001065 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001066 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001067
Yuly Novikov27780292018-11-09 11:19:49 -05001068 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001069 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001070}
1071
Jamie Madillaaca96e2018-06-12 10:19:48 -04001072bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001073{
1074 return serial > mLastCompletedQueueSerial;
1075}
1076
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001077angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1078{
1079 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1080 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001081 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001082 }
1083
1084 // Find the first batch with serial equal to or bigger than given serial (note that
1085 // the batch serials are unique, otherwise upper-bound would have been necessary).
1086 size_t batchIndex = mInFlightCommands.size() - 1;
1087 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1088 {
1089 if (mInFlightCommands[i].serial >= serial)
1090 {
1091 batchIndex = i;
1092 break;
1093 }
1094 }
1095 const CommandBatch &batch = mInFlightCommands[batchIndex];
1096
1097 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001098 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001099
1100 // Clean up finished batches.
1101 return checkCompletedCommands(context);
1102}
1103
Jamie Madill21061022018-07-12 23:56:30 -04001104angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1105 const vk::RenderPassDesc &desc,
1106 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001107{
Jamie Madill21061022018-07-12 23:56:30 -04001108 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001109 renderPassOut);
1110}
1111
Jamie Madill21061022018-07-12 23:56:30 -04001112angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1113 const vk::RenderPassDesc &desc,
1114 const vk::AttachmentOpsArray &ops,
1115 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001116{
Jamie Madill21061022018-07-12 23:56:30 -04001117 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001118 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001119}
1120
Jamie Madilla5e06072018-05-18 14:36:05 -04001121vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001122{
Jamie Madilla5e06072018-05-18 14:36:05 -04001123 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001124}
1125
Jamie Madill21061022018-07-12 23:56:30 -04001126angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001127{
Jamie Madill21061022018-07-12 23:56:30 -04001128 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001129 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001130}
1131
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001132angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001133{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001134 if (mCommandGraph.empty())
1135 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001136 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001137 }
1138
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001139 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1140
Jamie Madillbea35a62018-07-05 11:54:10 -04001141 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1142 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001143
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001144 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001145 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1146 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001147
1148 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1149 // will be waited on.
1150 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001151
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001152 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001153 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001154 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1155 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001156 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001157 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001158 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001159 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001160 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001161
Jamie Madill21061022018-07-12 23:56:30 -04001162 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001163
Jamie Madill7c985f52018-11-29 18:16:17 -05001164 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001165}
1166
Jamie Madill78feddc2018-04-27 11:45:05 -04001167Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001168{
Jamie Madill78feddc2018-04-27 11:45:05 -04001169 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001170}
1171
Jamie Madill21061022018-07-12 23:56:30 -04001172angle::Result RendererVk::getDescriptorSetLayout(
1173 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001174 const vk::DescriptorSetLayoutDesc &desc,
1175 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1176{
Jamie Madill21061022018-07-12 23:56:30 -04001177 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001178}
1179
Jamie Madill21061022018-07-12 23:56:30 -04001180angle::Result RendererVk::getPipelineLayout(
1181 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001182 const vk::PipelineLayoutDesc &desc,
1183 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1184 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1185{
Jamie Madill21061022018-07-12 23:56:30 -04001186 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001187 pipelineLayoutOut);
1188}
1189
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001190angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1191{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001192 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001193
1194 if (--mPipelineCacheVkUpdateTimeout > 0)
1195 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001196 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001197 }
1198
1199 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1200
1201 // Get the size of the cache.
1202 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001203 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001204 if (result != VK_INCOMPLETE)
1205 {
1206 ANGLE_VK_TRY(displayVk, result);
1207 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001208
1209 angle::MemoryBuffer *pipelineCacheData = nullptr;
1210 ANGLE_VK_CHECK_ALLOC(displayVk,
1211 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1212
1213 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001214 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001215 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1216 // was determined just above), so receiving it hints at an implementation bug we would want
1217 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001218 ASSERT(result != VK_INCOMPLETE);
1219 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001220
1221 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1222 // the buffer to avoid leaking garbage memory.
1223 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1224 if (pipelineCacheSize < originalPipelineCacheSize)
1225 {
1226 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1227 originalPipelineCacheSize - pipelineCacheSize);
1228 }
1229
1230 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1231
Jamie Madill7c985f52018-11-29 18:16:17 -05001232 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001233}
1234
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001235angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1236 const vk::Semaphore **outSemaphore)
1237{
1238 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1239
1240 vk::SemaphoreHelper semaphore;
1241 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1242
1243 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1244 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1245
Jamie Madill7c985f52018-11-29 18:16:17 -05001246 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001247}
1248
1249const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1250{
1251 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1252
1253 // Return the semaphore to the pool (which will remain valid and unused until the
1254 // queue it's about to be waited on has finished execution). The caller is about
1255 // to wait on it.
1256 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1257
1258 return semaphore;
1259}
1260
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001261angle::Result RendererVk::getFullScreenClearShaderProgram(vk::Context *context,
1262 vk::ShaderProgramHelper **programOut)
Jamie Madilld47044a2018-04-27 11:45:03 -04001263{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001264 if (!mFullScreenClearShaderProgram.valid())
1265 {
1266 vk::RefCounted<vk::ShaderAndSerial> *fullScreenQuad = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001267 ANGLE_TRY(mShaderLibrary.getFullScreenQuad_vert(context, 0, &fullScreenQuad));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001268
1269 vk::RefCounted<vk::ShaderAndSerial> *pushConstantColor = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001270 ANGLE_TRY(mShaderLibrary.getPushConstantColor_frag(context, 0, &pushConstantColor));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001271
1272 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Vertex, fullScreenQuad);
1273 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Fragment, pushConstantColor);
1274 }
1275
1276 *programOut = &mFullScreenClearShaderProgram;
Jamie Madill7c985f52018-11-29 18:16:17 -05001277 return angle::Result::Continue;
Jamie Madilld47044a2018-04-27 11:45:03 -04001278}
Luc Ferron90968362018-05-04 08:47:22 -04001279
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001280angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1281{
1282 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1283 // that seems impossible, so instead, we are going to make a small submission with just a
1284 // timestamp query. First, the disjoint timer query extension says:
1285 //
1286 // > This will return the GL time after all previous commands have reached the GL server but
1287 // have not yet necessarily executed.
1288 //
1289 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1290 // The wording allows us to make a submission to get the timestamp without performing a flush.
1291 //
1292 // Second:
1293 //
1294 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1295 // object target, applications can measure the latency between when commands reach the GL server
1296 // and when they are realized in the framebuffer.
1297 //
1298 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1299 // GPU bubble. This function directly generates a command buffer and submits it instead of
1300 // using the other member functions. This is to avoid changing any state, such as the queue
1301 // serial.
1302
1303 // Create a query used to receive the GPU timestamp
1304 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1305 vk::QueryHelper timestampQuery;
1306 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1307 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1308
1309 // Record the command buffer
1310 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1311 vk::CommandBuffer &commandBuffer = commandBatch.get();
1312
1313 VkCommandBufferAllocateInfo commandBufferInfo = {};
1314 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1315 commandBufferInfo.commandPool = mCommandPool.getHandle();
1316 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1317 commandBufferInfo.commandBufferCount = 1;
1318
Yuly Novikov27780292018-11-09 11:19:49 -05001319 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001320
1321 VkCommandBufferBeginInfo beginInfo = {};
1322 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1323 beginInfo.flags = 0;
1324 beginInfo.pInheritanceInfo = nullptr;
1325
Yuly Novikov27780292018-11-09 11:19:49 -05001326 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001327
1328 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1329 timestampQuery.getQuery(), 1);
1330 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1331 timestampQuery.getQueryPool()->getHandle(),
1332 timestampQuery.getQuery());
1333
Yuly Novikov27780292018-11-09 11:19:49 -05001334 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001335
1336 // Create fence for the submission
1337 VkFenceCreateInfo fenceInfo = {};
1338 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1339 fenceInfo.flags = 0;
1340
1341 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001342 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001343
1344 // Submit the command buffer
1345 VkSubmitInfo submitInfo = {};
1346 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1347 submitInfo.waitSemaphoreCount = 0;
1348 submitInfo.pWaitSemaphores = nullptr;
1349 submitInfo.pWaitDstStageMask = nullptr;
1350 submitInfo.commandBufferCount = 1;
1351 submitInfo.pCommandBuffers = commandBuffer.ptr();
1352 submitInfo.signalSemaphoreCount = 0;
1353 submitInfo.pSignalSemaphores = nullptr;
1354
1355 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1356
1357 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1358 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001359 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001360
1361 // Get the query results
1362 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1363
Yuly Novikov27780292018-11-09 11:19:49 -05001364 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1365 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1366 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001367
1368 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1369
Jamie Madill7c985f52018-11-29 18:16:17 -05001370 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001371}
1372
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001373// These functions look at the mandatory format for support, and fallback to querying the device (if
1374// necessary) to test the availability of the bits.
1375bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1376 const VkFormatFeatureFlags featureBits)
1377{
1378 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1379}
1380
1381bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1382 const VkFormatFeatureFlags featureBits)
1383{
1384 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1385}
1386
1387bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1388{
1389 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1390}
1391
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001392angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1393{
1394 ASSERT(mGpuEventsEnabled);
1395
1396 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1397 ASSERT(platform);
1398
1399 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1400 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1401 //
1402 // CPU GPU
1403 //
1404 // Record command buffer
1405 // with timestamp query
1406 //
1407 // Submit command buffer
1408 //
1409 // Post-submission work Begin execution
1410 //
1411 // ???? Write timstamp Tgpu
1412 //
1413 // ???? End execution
1414 //
1415 // ???? Return query results
1416 //
1417 // ????
1418 //
1419 // Get query results
1420 //
1421 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1422 // finished post-submission work while the GPU is executing in parallel. With no further work,
1423 // querying CPU timestamps before submission and after getting query results give the bounds to
1424 // Tgpu, which could be quite large.
1425 //
1426 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1427 // reduce this range. This function implements the following procedure:
1428 //
1429 // CPU GPU
1430 //
1431 // Record command buffer
1432 // with timestamp query
1433 //
1434 // Submit command buffer
1435 //
1436 // Post-submission work Begin execution
1437 //
1438 // ???? Set Event GPUReady
1439 //
1440 // Wait on Event GPUReady Wait on Event CPUReady
1441 //
1442 // Get CPU Time Ts Wait on Event CPUReady
1443 //
1444 // Set Event CPUReady Wait on Event CPUReady
1445 //
1446 // Get CPU Time Tcpu Get GPU Time Tgpu
1447 //
1448 // Wait on Event GPUDone Set Event GPUDone
1449 //
1450 // Get CPU Time Te End Execution
1451 //
1452 // Idle Return query results
1453 //
1454 // Get query results
1455 //
1456 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1457 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1458 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1459 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1460 // calibration.
1461 //
1462 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1463
1464 // Make sure nothing is running
1465 ASSERT(mCommandGraph.empty());
1466
1467 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1468
1469 // Create a query used to receive the GPU timestamp
1470 vk::QueryHelper timestampQuery;
1471 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1472
1473 // Create the three events
1474 VkEventCreateInfo eventCreateInfo = {};
1475 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1476 eventCreateInfo.flags = 0;
1477
1478 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001479 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1480 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1481 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001482
1483 constexpr uint32_t kRetries = 10;
1484
1485 // Time suffixes used are S for seconds and Cycles for cycles
1486 double tightestRangeS = 1e6f;
1487 double TcpuS = 0;
1488 uint64_t TgpuCycles = 0;
1489 for (uint32_t i = 0; i < kRetries; ++i)
1490 {
1491 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001492 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1493 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1494 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001495
1496 // Record the command buffer
1497 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1498 vk::CommandBuffer &commandBuffer = commandBatch.get();
1499
1500 VkCommandBufferAllocateInfo commandBufferInfo = {};
1501 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1502 commandBufferInfo.commandPool = mCommandPool.getHandle();
1503 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1504 commandBufferInfo.commandBufferCount = 1;
1505
Yuly Novikov27780292018-11-09 11:19:49 -05001506 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001507
1508 VkCommandBufferBeginInfo beginInfo = {};
1509 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1510 beginInfo.flags = 0;
1511 beginInfo.pInheritanceInfo = nullptr;
1512
Yuly Novikov27780292018-11-09 11:19:49 -05001513 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001514
1515 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1516 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1517 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1518 nullptr);
1519
1520 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1521 timestampQuery.getQuery(), 1);
1522 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1523 timestampQuery.getQueryPool()->getHandle(),
1524 timestampQuery.getQuery());
1525
1526 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1527
Yuly Novikov27780292018-11-09 11:19:49 -05001528 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001529
1530 // Submit the command buffer
1531 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1532 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1533 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1534
1535 VkSubmitInfo submitInfo = {};
1536 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1537 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1538 submitInfo.pWaitSemaphores = waitSemaphores.data();
1539 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1540 submitInfo.commandBufferCount = 1;
1541 submitInfo.pCommandBuffers = commandBuffer.ptr();
1542 submitInfo.signalSemaphoreCount = 0;
1543 submitInfo.pSignalSemaphores = nullptr;
1544
1545 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1546
1547 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001548 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001549 do
1550 {
Yuly Novikov27780292018-11-09 11:19:49 -05001551 result = gpuReady.get().getStatus(mDevice);
1552 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1553 {
1554 ANGLE_VK_TRY(context, result);
1555 }
1556 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001557
1558 double TsS = platform->monotonicallyIncreasingTime(platform);
1559
1560 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001561 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001562 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1563
1564 // Wait for GPU to be done. Another short busy wait.
1565 do
1566 {
Yuly Novikov27780292018-11-09 11:19:49 -05001567 result = gpuDone.get().getStatus(mDevice);
1568 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1569 {
1570 ANGLE_VK_TRY(context, result);
1571 }
1572 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001573
1574 double TeS = platform->monotonicallyIncreasingTime(platform);
1575
1576 // Get the query results
1577 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1578
1579 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1580
1581 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001582 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1583 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1584 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001585
1586 // Use the first timestamp queried as origin.
1587 if (mGpuEventTimestampOrigin == 0)
1588 {
1589 mGpuEventTimestampOrigin = gpuTimestampCycles;
1590 }
1591
1592 // Take these CPU and GPU timestamps if there is better confidence.
1593 double confidenceRangeS = TeS - TsS;
1594 if (confidenceRangeS < tightestRangeS)
1595 {
1596 tightestRangeS = confidenceRangeS;
1597 TcpuS = cpuTimestampS;
1598 TgpuCycles = gpuTimestampCycles;
1599 }
1600 }
1601
1602 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1603
1604 // timestampPeriod gives nanoseconds/cycle.
1605 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1606 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1607 1'000'000'000.0;
1608
1609 flushGpuEvents(TgpuS, TcpuS);
1610
1611 mGpuClockSync.gpuTimestampS = TgpuS;
1612 mGpuClockSync.cpuTimestampS = TcpuS;
1613
Jamie Madill7c985f52018-11-29 18:16:17 -05001614 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001615}
1616
1617angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1618 vk::CommandBuffer *commandBuffer,
1619 char phase,
1620 const char *name)
1621{
1622 ASSERT(mGpuEventsEnabled);
1623
1624 GpuEventQuery event;
1625
1626 event.name = name;
1627 event.phase = phase;
1628 event.serial = mCurrentQueueSerial;
1629
1630 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1631
1632 commandBuffer->resetQueryPool(
1633 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1634 commandBuffer->writeTimestamp(
1635 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1636 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1637
1638 mInFlightGpuEventQueries.push_back(std::move(event));
1639
Jamie Madill7c985f52018-11-29 18:16:17 -05001640 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001641}
1642
1643angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1644{
1645 ASSERT(mGpuEventsEnabled);
1646
1647 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1648 ASSERT(platform);
1649
1650 int finishedCount = 0;
1651
1652 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1653 {
1654 // Only check the timestamp query if the submission has finished.
1655 if (eventQuery.serial > mLastCompletedQueueSerial)
1656 {
1657 break;
1658 }
1659
1660 // See if the results are available.
1661 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001662 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1663 ->getResults(mDevice, eventQuery.queryIndex, 1,
1664 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1665 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1666 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001667 {
1668 break;
1669 }
Yuly Novikov27780292018-11-09 11:19:49 -05001670 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001671
1672 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1673
1674 GpuEvent event;
1675 event.gpuTimestampCycles = gpuTimestampCycles;
1676 event.name = eventQuery.name;
1677 event.phase = eventQuery.phase;
1678
1679 mGpuEvents.emplace_back(event);
1680
1681 ++finishedCount;
1682 }
1683
1684 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1685 mInFlightGpuEventQueries.begin() + finishedCount);
1686
Jamie Madill7c985f52018-11-29 18:16:17 -05001687 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001688}
1689
1690void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1691{
1692 if (mGpuEvents.size() == 0)
1693 {
1694 return;
1695 }
1696
1697 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1698 ASSERT(platform);
1699
1700 // Find the slope of the clock drift for adjustment
1701 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1702 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1703 double gpuSyncDriftSlope = 0;
1704
1705 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1706 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1707
1708 // No gpu trace events should have been generated before the clock sync, so if there is no
1709 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1710 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1711 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1712
1713 gpuSyncDriftSlope =
1714 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1715
1716 for (const GpuEvent &event : mGpuEvents)
1717 {
1718 double gpuTimestampS =
1719 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1720 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1721
1722 // Account for clock drift.
1723 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1724
1725 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1726 // for.
1727 static long long eventId = 1;
1728 static const unsigned char *categoryEnabled =
1729 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1730 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1731 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1732 }
1733
1734 mGpuEvents.clear();
1735}
1736
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001737template <VkFormatFeatureFlags VkFormatProperties::*features>
1738bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1739{
1740 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
1741 VkFormatProperties &deviceProperties = mFormatProperties[format];
1742
1743 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
1744 {
1745 // If we don't have the actual device features, see if the requested features are mandatory.
1746 // If so, there's no need to query the device.
1747 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
1748 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
1749 {
1750 return true;
1751 }
1752
1753 // Otherwise query the format features and cache it.
1754 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
1755 }
1756
1757 return IsMaskFlagSet(deviceProperties.*features, featureBits);
1758}
1759
Jamie Madillaaca96e2018-06-12 10:19:48 -04001760uint32_t GetUniformBufferDescriptorCount()
1761{
1762 return kUniformBufferDescriptorsPerDescriptorSet;
1763}
1764
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001765} // namespace rx