blob: b14eb9e4d37c3b53d3d3b28e54859ad21f5c1bac [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;
Ian Elliottbcb78902018-12-19 11:46:29 -0700273
274bool ExtensionFound(const char *extensionName,
275 const std::vector<VkExtensionProperties> &extensionProps)
276{
277 for (const auto &extensionProp : extensionProps)
278 {
279 if (strcmp(extensionProp.extensionName, extensionName) == 0)
280 {
281 return true;
282 }
283 }
284 return false;
285}
Jamie Madille09bd5d2016-11-29 16:20:35 -0500286} // anonymous namespace
287
Jamie Madill49ac74b2017-12-21 14:42:33 -0500288// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400289RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500290
Jamie Madillaaca96e2018-06-12 10:19:48 -0400291RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500292
293RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
294 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500295{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500296
297RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
298{
299 std::swap(commandPool, other.commandPool);
300 std::swap(fence, other.fence);
301 std::swap(serial, other.serial);
302 return *this;
303}
304
Jamie Madillbea35a62018-07-05 11:54:10 -0400305void RendererVk::CommandBatch::destroy(VkDevice device)
306{
307 commandPool.destroy(device);
308 fence.destroy(device);
309}
310
Jamie Madill9f2a8612017-11-30 12:43:09 -0500311// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500312RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400313 : mDisplay(nullptr),
314 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700315 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500316 mInstance(VK_NULL_HANDLE),
317 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400318 mEnableMockICD(false),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500319 mDebugReportCallback(VK_NULL_HANDLE),
320 mPhysicalDevice(VK_NULL_HANDLE),
321 mQueue(VK_NULL_HANDLE),
322 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
323 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400324 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400325 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400326 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400327 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400328 mCommandGraph(kEnableCommandGraphDiagnostics),
329 mGpuEventsEnabled(false),
330 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
331 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500332{
333 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
334 mFormatProperties.fill(invalid);
335}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400336
Jamie Madillb980c562018-11-27 11:34:27 -0500337RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400338
339void RendererVk::onDestroy(vk::Context *context)
340{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500341 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500342 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500343 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400344 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500345 }
346
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500347 mDispatchUtils.destroy(mDevice);
348
Jamie Madillc7918ce2018-06-13 13:25:31 -0400349 mPipelineLayoutCache.destroy(mDevice);
350 mDescriptorSetLayoutCache.destroy(mDevice);
351
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500352 mFullScreenClearShaderProgram.destroy(mDevice);
353
Jamie Madill9f2a8612017-11-30 12:43:09 -0500354 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500355 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400356 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400357 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400358 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500359
Jamie Madill06ca6342018-07-12 15:56:53 -0400360 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500361
Jamie Madill5deea722017-02-16 10:44:46 -0500362 if (mCommandPool.valid())
363 {
364 mCommandPool.destroy(mDevice);
365 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500366
367 if (mDevice)
368 {
369 vkDestroyDevice(mDevice, nullptr);
370 mDevice = VK_NULL_HANDLE;
371 }
372
Jamie Madill0448ec82016-12-23 13:41:47 -0500373 if (mDebugReportCallback)
374 {
375 ASSERT(mInstance);
376 auto destroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
377 vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT"));
378 ASSERT(destroyDebugReportCallback);
379 destroyDebugReportCallback(mInstance, mDebugReportCallback, nullptr);
380 }
381
Jamie Madill4d0bf552016-12-28 15:45:24 -0500382 if (mInstance)
383 {
384 vkDestroyInstance(mInstance, nullptr);
385 mInstance = VK_NULL_HANDLE;
386 }
387
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600388 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500389 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500390}
391
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400392void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400393{
394 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400395
396 mCommandGraph.clear();
397 mLastSubmittedQueueSerial = mCurrentQueueSerial;
398 mCurrentQueueSerial = mQueueSerialFactory.generate();
399 freeAllInFlightResources();
400
401 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400402}
403
404bool RendererVk::isDeviceLost() const
405{
406 return mDeviceLost;
407}
408
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400409angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400410 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400411 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500412{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400413 mDisplay = display;
414 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600415 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
416 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500417 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400418 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500419
Jamie Madill0448ec82016-12-23 13:41:47 -0500420 // Gather global layer properties.
421 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400422 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500423
424 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
425 if (instanceLayerCount > 0)
426 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400427 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
428 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500429 }
430
Jamie Madille09bd5d2016-11-29 16:20:35 -0500431 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400432 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400433 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500434
435 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
436 if (instanceExtensionCount > 0)
437 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400438 ANGLE_VK_TRY(displayVk,
439 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
440 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500441 }
442
Yuly Novikov199f4292018-01-19 19:04:05 -0500443 const char *const *enabledLayerNames = nullptr;
444 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500445 if (mEnableValidationLayers)
446 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500447 bool layersRequested =
448 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
449 mEnableValidationLayers = GetAvailableValidationLayers(
450 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500451 }
452
Jamie Madille09bd5d2016-11-29 16:20:35 -0500453 std::vector<const char *> enabledInstanceExtensions;
454 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500455 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500456
Jamie Madill0448ec82016-12-23 13:41:47 -0500457 // TODO(jmadill): Should be able to continue initialization if debug report ext missing.
458 if (mEnableValidationLayers)
459 {
460 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
461 }
462
Jamie Madille09bd5d2016-11-29 16:20:35 -0500463 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400464 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400465 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500466
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400467 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500468 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500469 applicationInfo.pApplicationName = "ANGLE";
470 applicationInfo.applicationVersion = 1;
471 applicationInfo.pEngineName = "ANGLE";
472 applicationInfo.engineVersion = 1;
473 applicationInfo.apiVersion = VK_API_VERSION_1_0;
474
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400475 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500476 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
477 instanceInfo.flags = 0;
478 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500479
Jamie Madille09bd5d2016-11-29 16:20:35 -0500480 // Enable requested layers and extensions.
481 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
482 instanceInfo.ppEnabledExtensionNames =
483 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500484 instanceInfo.enabledLayerCount = enabledLayerCount;
485 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500486
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400487 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500488
Jamie Madill0448ec82016-12-23 13:41:47 -0500489 if (mEnableValidationLayers)
490 {
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400491 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500492
493 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500494 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
495 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
496 VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
497 debugReportInfo.pfnCallback = &DebugReportCallback;
498 debugReportInfo.pUserData = this;
499
500 auto createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
501 vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT"));
502 ASSERT(createDebugReportCallback);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400503 ANGLE_VK_TRY(displayVk, createDebugReportCallback(mInstance, &debugReportInfo, nullptr,
504 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500505 }
506
Jamie Madill4d0bf552016-12-28 15:45:24 -0500507 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400508 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
509 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500510
511 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700512 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400513 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
514 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400515 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700516 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500517
Jamie Madill30b5d842018-08-31 17:19:12 -0400518 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
519
Jamie Madill4d0bf552016-12-28 15:45:24 -0500520 // Ensure we can find a graphics queue family.
521 uint32_t queueCount = 0;
522 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
523
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400524 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500525
526 mQueueFamilyProperties.resize(queueCount);
527 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
528 mQueueFamilyProperties.data());
529
Jamie Madillb980c562018-11-27 11:34:27 -0500530 size_t graphicsQueueFamilyCount = false;
531 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500532 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500533 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
534 {
535 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500536 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500537 {
538 ASSERT(queueInfo.queueCount > 0);
539 graphicsQueueFamilyCount++;
540 if (firstGraphicsQueueFamily == 0)
541 {
542 firstGraphicsQueueFamily = familyIndex;
543 }
544 break;
545 }
546 }
547
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400548 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500549
550 // If only one queue family, go ahead and initialize the device. If there is more than one
551 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
552 if (graphicsQueueFamilyCount == 1)
553 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400554 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500555 }
556
Jamie Madill035fd6b2017-10-03 15:43:22 -0400557 // Store the physical device memory properties so we can find the right memory pools.
558 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500559
Jamie Madill06ca6342018-07-12 15:56:53 -0400560 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500561
Jamie Madill6a89d222017-11-02 11:59:51 -0400562 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500563 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400564
Jamie Madill7c985f52018-11-29 18:16:17 -0500565 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400566}
567
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400568angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500569{
570 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400571 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400572 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500573
574 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
575 if (deviceLayerCount > 0)
576 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400577 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
578 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500579 }
580
581 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400582 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
583 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500584
585 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
586 if (deviceExtensionCount > 0)
587 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400588 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
589 &deviceExtensionCount,
590 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500591 }
592
Yuly Novikov199f4292018-01-19 19:04:05 -0500593 const char *const *enabledLayerNames = nullptr;
594 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500595 if (mEnableValidationLayers)
596 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500597 mEnableValidationLayers = GetAvailableValidationLayers(
598 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500599 }
600
601 std::vector<const char *> enabledDeviceExtensions;
602 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
603
Ian Elliottbcb78902018-12-19 11:46:29 -0700604 initFeatures(deviceExtensionProps);
605 mFeaturesInitialized = true;
606
Luc Ferronbf6dc372018-06-28 15:24:19 -0400607 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
608 if (getFeatures().flipViewportY)
609 {
610 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
611 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700612 if (getFeatures().supportsIncrementalPresent)
613 {
614 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
615 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400616
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400617 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500618
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400619 // Select additional features to be enabled
620 VkPhysicalDeviceFeatures enabledFeatures = {};
621 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
622
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400623 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500624
625 float zeroPriority = 0.0f;
626
627 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500628 queueCreateInfo.flags = 0;
629 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
630 queueCreateInfo.queueCount = 1;
631 queueCreateInfo.pQueuePriorities = &zeroPriority;
632
633 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400634 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500635
Jamie Madill50cf2be2018-06-15 09:46:57 -0400636 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400637 createInfo.flags = 0;
638 createInfo.queueCreateInfoCount = 1;
639 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500640 createInfo.enabledLayerCount = enabledLayerCount;
641 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500642 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
643 createInfo.ppEnabledExtensionNames =
644 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400645 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500646
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400647 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500648
649 mCurrentQueueFamilyIndex = queueFamilyIndex;
650
651 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
652
653 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400654 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500655 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
656 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
657 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500658
Yuly Novikov27780292018-11-09 11:19:49 -0500659 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400660
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400661 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500662 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500663
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400664 // Initialize the submission semaphore pool.
665 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
666
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400667#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
668 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
669 ASSERT(platform);
670
671 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
672 // platform discovery.
673 const unsigned char *gpuEventsEnabled =
674 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
675 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
676#endif
677
678 if (mGpuEventsEnabled)
679 {
680 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
681 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
682 vk::kDefaultTimestampQueryPoolSize));
683 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
684 }
685
Jamie Madill7c985f52018-11-29 18:16:17 -0500686 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500687}
688
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400689angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400690 VkSurfaceKHR surface,
691 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500692{
693 // We've already initialized a device, and can't re-create it unless it's never been used.
694 // TODO(jmadill): Handle the re-creation case if necessary.
695 if (mDevice != VK_NULL_HANDLE)
696 {
697 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
698
699 // Check if the current device supports present on this surface.
700 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400701 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400702 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500703 surface, &supportsPresent));
704
Jamie Madill6cad7732018-07-11 09:01:17 -0400705 if (supportsPresent == VK_TRUE)
706 {
707 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500708 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400709 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500710 }
711
712 // Find a graphics and present queue.
713 Optional<uint32_t> newPresentQueue;
714 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500715 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500716 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
717 {
718 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500719 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500720 {
721 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400722 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
723 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500724
725 if (supportsPresent == VK_TRUE)
726 {
727 newPresentQueue = queueIndex;
728 break;
729 }
730 }
731 }
732
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400733 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
734 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500735
Jamie Madill6cad7732018-07-11 09:01:17 -0400736 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500737 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500738}
739
740std::string RendererVk::getVendorString() const
741{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300742 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500743}
744
Jamie Madille09bd5d2016-11-29 16:20:35 -0500745std::string RendererVk::getRendererDescription() const
746{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500747 std::stringstream strstr;
748
749 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
750
751 strstr << "Vulkan ";
752 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
753 strstr << VK_VERSION_MINOR(apiVersion) << ".";
754 strstr << VK_VERSION_PATCH(apiVersion);
755
Olli Etuahoc6a06182018-04-13 14:11:46 +0300756 strstr << "(";
757
758 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
759 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
760 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
761 // driver detection.
762 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
763 {
764 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
765 }
766
Geoff Langa7af56b2018-12-14 14:20:28 -0500767 strstr << mPhysicalDeviceProperties.deviceName;
768 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
769
770 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500771
772 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500773}
774
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500775gl::Version RendererVk::getMaxSupportedESVersion() const
776{
777 // Declare GLES2 support if necessary features for GLES3 are missing
778 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
779
780 if (!necessaryFeaturesForES3)
781 {
782 return gl::Version(2, 0);
783 }
784
785 return gl::Version(3, 0);
786}
787
Ian Elliottbcb78902018-12-19 11:46:29 -0700788void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -0400789{
Jamie Madillb36a4812018-09-25 10:15:11 -0400790// Use OpenGL line rasterization rules by default.
791// TODO(jmadill): Fix Android support. http://anglebug.com/2830
792#if defined(ANGLE_PLATFORM_ANDROID)
793 mFeatures.basicGLLineRasterization = false;
794#else
Jamie Madill12222072018-07-11 14:59:48 -0400795 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400796#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400797
Ian Elliottd50521f2018-12-20 12:05:14 -0700798 if (ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
799 {
800 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
801 // investigation. http://anglebug.com/2728
802 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
803 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400804
805#ifdef ANGLE_PLATFORM_WINDOWS
806 // http://anglebug.com/2838
807 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
808#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400809
810 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
811 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -0500812
813 // Work around incorrect NVIDIA point size range clamping.
814 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
815 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
816 {
817 mFeatures.clampPointSize = true;
818 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +0100819
820#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -0500821 // Work around ineffective compute-graphics barriers on Nexus 5X.
822 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
823 // http://anglebug.com/3019
824 mFeatures.flushAfterVertexConversion =
825 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +0100826#endif
Ian Elliottbcb78902018-12-19 11:46:29 -0700827
828 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
829 {
830 mFeatures.supportsIncrementalPresent = true;
831 }
Jamie Madill12222072018-07-11 14:59:48 -0400832}
833
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400834void RendererVk::initPipelineCacheVkKey()
835{
836 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
837 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
838 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
839 // there is no '\0' in the result.
840 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
841 {
842 hashStream << std::hex << c;
843 }
844 // Add the vendor and device id too for good measure.
845 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
846 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
847
848 const std::string &hashString = hashStream.str();
849 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
850 hashString.length(), mPipelineCacheVkBlobKey.data());
851}
852
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500853angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400854{
855 initPipelineCacheVkKey();
856
857 egl::BlobCache::Value initialData;
858 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
859 mPipelineCacheVkBlobKey, &initialData);
860
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400861 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400862
863 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400864 pipelineCacheCreateInfo.flags = 0;
865 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
866 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
867
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500868 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -0500869 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400870}
871
Jamie Madillacccc6c2016-05-03 17:22:10 -0400872void RendererVk::ensureCapsInitialized() const
873{
874 if (!mCapsInitialized)
875 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400876 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
877 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
878 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400879 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400880 mCapsInitialized = true;
881 }
882}
883
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400884void RendererVk::getSubmitWaitSemaphores(
885 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400886 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
887 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400888{
889 if (mSubmitLastSignaledSemaphore.getSemaphore())
890 {
891 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400892 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400893
894 // Return the semaphore to the pool (which will remain valid and unused until the
895 // queue it's about to be waited on has finished execution).
896 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
897 }
898
899 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
900 {
901 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400902 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
903
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400904 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
905 }
906 mSubmitWaitSemaphores.clear();
907}
908
Jamie Madillacccc6c2016-05-03 17:22:10 -0400909const gl::Caps &RendererVk::getNativeCaps() const
910{
911 ensureCapsInitialized();
912 return mNativeCaps;
913}
914
915const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
916{
917 ensureCapsInitialized();
918 return mNativeTextureCaps;
919}
920
921const gl::Extensions &RendererVk::getNativeExtensions() const
922{
923 ensureCapsInitialized();
924 return mNativeExtensions;
925}
926
927const gl::Limitations &RendererVk::getNativeLimitations() const
928{
929 ensureCapsInitialized();
930 return mNativeLimitations;
931}
932
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400933uint32_t RendererVk::getMaxActiveTextures()
934{
935 // TODO(lucferron): expose this limitation to GL in Context Caps
936 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
937 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
938}
939
Jamie Madill49ac74b2017-12-21 14:42:33 -0500940const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500941{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500942 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500943}
944
Jamie Madill21061022018-07-12 23:56:30 -0400945angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500946{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500947 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500948 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400949 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
950
Luc Ferron1617e692018-07-11 11:08:19 -0400951 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
952 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400953
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400954 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400955 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
956 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400957
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400958 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500959 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400960 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
961 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400962 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500963 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400964 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500965 submitInfo.signalSemaphoreCount = 0;
966 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500967
Jamie Madill21061022018-07-12 23:56:30 -0400968 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500969 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500970
Jamie Madill4c26fc22017-02-24 11:04:10 -0500971 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400972 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400973 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400974
975 if (mGpuEventsEnabled)
976 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400977 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400978 while (mInFlightGpuEventQueries.size() > 0)
979 {
980 ANGLE_TRY(checkCompletedGpuEvents(context));
981 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400982 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
983 // synchronization if there is no event to be adjusted (happens when finish() gets called
984 // multiple times towards the end of the application).
985 if (mGpuEvents.size() > 0)
986 {
987 ANGLE_TRY(synchronizeCpuGpuTime(context));
988 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400989 }
990
Jamie Madill7c985f52018-11-29 18:16:17 -0500991 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500992}
993
Jamie Madill0c0dc342017-03-24 14:18:51 -0400994void RendererVk::freeAllInFlightResources()
995{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500996 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400997 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400998 // On device loss we need to wait for fence to be signaled before destroying it
999 if (mDeviceLost)
1000 {
1001 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1002 // If wait times out, it is probably not possible to recover from lost device
1003 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1004 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001005 batch.fence.destroy(mDevice);
1006 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001007 }
1008 mInFlightCommands.clear();
1009
1010 for (auto &garbage : mGarbage)
1011 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001012 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001013 }
1014 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001015
1016 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001017}
1018
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001019angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001020{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001021 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001022
Jamie Madill49ac74b2017-12-21 14:42:33 -05001023 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001024 {
Yuly Novikov27780292018-11-09 11:19:49 -05001025 VkResult result = batch.fence.getStatus(mDevice);
1026 if (result == VK_NOT_READY)
1027 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001028 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001029 }
1030 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001031
Jamie Madill49ac74b2017-12-21 14:42:33 -05001032 ASSERT(batch.serial > mLastCompletedQueueSerial);
1033 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001034
Jamie Madill49ac74b2017-12-21 14:42:33 -05001035 batch.fence.destroy(mDevice);
1036 batch.commandPool.destroy(mDevice);
1037 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001038 }
1039
Jamie Madill49ac74b2017-12-21 14:42:33 -05001040 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001041
1042 size_t freeIndex = 0;
1043 for (; freeIndex < mGarbage.size(); ++freeIndex)
1044 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001045 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001046 break;
1047 }
1048
1049 // Remove the entries from the garbage list - they should be ready to go.
1050 if (freeIndex > 0)
1051 {
1052 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001053 }
1054
Jamie Madill7c985f52018-11-29 18:16:17 -05001055 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001056}
1057
Jamie Madill21061022018-07-12 23:56:30 -04001058angle::Result RendererVk::submitFrame(vk::Context *context,
1059 const VkSubmitInfo &submitInfo,
1060 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001061{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001062 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001063 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001064 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1065 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001066
Jamie Madillbea35a62018-07-05 11:54:10 -04001067 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1068 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001069 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001070
Jamie Madill21061022018-07-12 23:56:30 -04001071 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001072
1073 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001074 batch.commandPool = std::move(mCommandPool);
1075 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001076
Jamie Madillbea35a62018-07-05 11:54:10 -04001077 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001078
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001079 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1080 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001081 // so the limit is larger than the expected number of images. The
1082 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001083 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001084
1085 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001086 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001087 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001088 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001089
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001090 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001091
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001092 if (mGpuEventsEnabled)
1093 {
1094 ANGLE_TRY(checkCompletedGpuEvents(context));
1095 }
1096
Jamie Madill49ac74b2017-12-21 14:42:33 -05001097 // Simply null out the command buffer here - it was allocated using the command pool.
1098 commandBuffer.releaseHandle();
1099
1100 // Reallocate the command pool for next frame.
1101 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001102 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001103 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001104 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001105 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001106
Yuly Novikov27780292018-11-09 11:19:49 -05001107 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001108 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001109}
1110
Jamie Madillaaca96e2018-06-12 10:19:48 -04001111bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001112{
1113 return serial > mLastCompletedQueueSerial;
1114}
1115
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001116angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1117{
1118 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1119 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001120 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001121 }
1122
1123 // Find the first batch with serial equal to or bigger than given serial (note that
1124 // the batch serials are unique, otherwise upper-bound would have been necessary).
1125 size_t batchIndex = mInFlightCommands.size() - 1;
1126 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1127 {
1128 if (mInFlightCommands[i].serial >= serial)
1129 {
1130 batchIndex = i;
1131 break;
1132 }
1133 }
1134 const CommandBatch &batch = mInFlightCommands[batchIndex];
1135
1136 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001137 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001138
1139 // Clean up finished batches.
1140 return checkCompletedCommands(context);
1141}
1142
Jamie Madill21061022018-07-12 23:56:30 -04001143angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1144 const vk::RenderPassDesc &desc,
1145 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001146{
Jamie Madill21061022018-07-12 23:56:30 -04001147 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001148 renderPassOut);
1149}
1150
Jamie Madill21061022018-07-12 23:56:30 -04001151angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1152 const vk::RenderPassDesc &desc,
1153 const vk::AttachmentOpsArray &ops,
1154 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001155{
Jamie Madill21061022018-07-12 23:56:30 -04001156 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001157 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001158}
1159
Jamie Madilla5e06072018-05-18 14:36:05 -04001160vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001161{
Jamie Madilla5e06072018-05-18 14:36:05 -04001162 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001163}
1164
Jamie Madill21061022018-07-12 23:56:30 -04001165angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001166{
Jamie Madill21061022018-07-12 23:56:30 -04001167 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001168 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001169}
1170
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001171angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001172{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001173 if (mCommandGraph.empty())
1174 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001175 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001176 }
1177
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001178 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1179
Jamie Madillbea35a62018-07-05 11:54:10 -04001180 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1181 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001182
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001183 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001184 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1185 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001186
1187 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1188 // will be waited on.
1189 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001190
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001191 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001192 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001193 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1194 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001195 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001196 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001197 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001198 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001199 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001200
Jamie Madill21061022018-07-12 23:56:30 -04001201 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001202
Jamie Madill7c985f52018-11-29 18:16:17 -05001203 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001204}
1205
Jamie Madill78feddc2018-04-27 11:45:05 -04001206Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001207{
Jamie Madill78feddc2018-04-27 11:45:05 -04001208 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001209}
1210
Jamie Madill21061022018-07-12 23:56:30 -04001211angle::Result RendererVk::getDescriptorSetLayout(
1212 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001213 const vk::DescriptorSetLayoutDesc &desc,
1214 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1215{
Jamie Madill21061022018-07-12 23:56:30 -04001216 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001217}
1218
Jamie Madill21061022018-07-12 23:56:30 -04001219angle::Result RendererVk::getPipelineLayout(
1220 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001221 const vk::PipelineLayoutDesc &desc,
1222 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1223 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1224{
Jamie Madill21061022018-07-12 23:56:30 -04001225 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001226 pipelineLayoutOut);
1227}
1228
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001229angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1230{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001231 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001232
1233 if (--mPipelineCacheVkUpdateTimeout > 0)
1234 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001235 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001236 }
1237
1238 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1239
1240 // Get the size of the cache.
1241 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001242 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001243 if (result != VK_INCOMPLETE)
1244 {
1245 ANGLE_VK_TRY(displayVk, result);
1246 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001247
1248 angle::MemoryBuffer *pipelineCacheData = nullptr;
1249 ANGLE_VK_CHECK_ALLOC(displayVk,
1250 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1251
1252 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001253 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001254 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1255 // was determined just above), so receiving it hints at an implementation bug we would want
1256 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001257 ASSERT(result != VK_INCOMPLETE);
1258 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001259
1260 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1261 // the buffer to avoid leaking garbage memory.
1262 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1263 if (pipelineCacheSize < originalPipelineCacheSize)
1264 {
1265 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1266 originalPipelineCacheSize - pipelineCacheSize);
1267 }
1268
1269 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1270
Jamie Madill7c985f52018-11-29 18:16:17 -05001271 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001272}
1273
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001274angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1275 const vk::Semaphore **outSemaphore)
1276{
1277 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1278
1279 vk::SemaphoreHelper semaphore;
1280 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1281
1282 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1283 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1284
Jamie Madill7c985f52018-11-29 18:16:17 -05001285 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001286}
1287
1288const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1289{
1290 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1291
1292 // Return the semaphore to the pool (which will remain valid and unused until the
1293 // queue it's about to be waited on has finished execution). The caller is about
1294 // to wait on it.
1295 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1296
1297 return semaphore;
1298}
1299
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001300angle::Result RendererVk::getFullScreenClearShaderProgram(vk::Context *context,
1301 vk::ShaderProgramHelper **programOut)
Jamie Madilld47044a2018-04-27 11:45:03 -04001302{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001303 if (!mFullScreenClearShaderProgram.valid())
1304 {
1305 vk::RefCounted<vk::ShaderAndSerial> *fullScreenQuad = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001306 ANGLE_TRY(mShaderLibrary.getFullScreenQuad_vert(context, 0, &fullScreenQuad));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001307
1308 vk::RefCounted<vk::ShaderAndSerial> *pushConstantColor = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001309 ANGLE_TRY(mShaderLibrary.getPushConstantColor_frag(context, 0, &pushConstantColor));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001310
1311 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Vertex, fullScreenQuad);
1312 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Fragment, pushConstantColor);
1313 }
1314
1315 *programOut = &mFullScreenClearShaderProgram;
Jamie Madill7c985f52018-11-29 18:16:17 -05001316 return angle::Result::Continue;
Jamie Madilld47044a2018-04-27 11:45:03 -04001317}
Luc Ferron90968362018-05-04 08:47:22 -04001318
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001319angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1320{
1321 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1322 // that seems impossible, so instead, we are going to make a small submission with just a
1323 // timestamp query. First, the disjoint timer query extension says:
1324 //
1325 // > This will return the GL time after all previous commands have reached the GL server but
1326 // have not yet necessarily executed.
1327 //
1328 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1329 // The wording allows us to make a submission to get the timestamp without performing a flush.
1330 //
1331 // Second:
1332 //
1333 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1334 // object target, applications can measure the latency between when commands reach the GL server
1335 // and when they are realized in the framebuffer.
1336 //
1337 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1338 // GPU bubble. This function directly generates a command buffer and submits it instead of
1339 // using the other member functions. This is to avoid changing any state, such as the queue
1340 // serial.
1341
1342 // Create a query used to receive the GPU timestamp
1343 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1344 vk::QueryHelper timestampQuery;
1345 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1346 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1347
1348 // Record the command buffer
1349 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1350 vk::CommandBuffer &commandBuffer = commandBatch.get();
1351
1352 VkCommandBufferAllocateInfo commandBufferInfo = {};
1353 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1354 commandBufferInfo.commandPool = mCommandPool.getHandle();
1355 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1356 commandBufferInfo.commandBufferCount = 1;
1357
Yuly Novikov27780292018-11-09 11:19:49 -05001358 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001359
1360 VkCommandBufferBeginInfo beginInfo = {};
1361 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1362 beginInfo.flags = 0;
1363 beginInfo.pInheritanceInfo = nullptr;
1364
Yuly Novikov27780292018-11-09 11:19:49 -05001365 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001366
1367 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1368 timestampQuery.getQuery(), 1);
1369 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1370 timestampQuery.getQueryPool()->getHandle(),
1371 timestampQuery.getQuery());
1372
Yuly Novikov27780292018-11-09 11:19:49 -05001373 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001374
1375 // Create fence for the submission
1376 VkFenceCreateInfo fenceInfo = {};
1377 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1378 fenceInfo.flags = 0;
1379
1380 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001381 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001382
1383 // Submit the command buffer
1384 VkSubmitInfo submitInfo = {};
1385 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1386 submitInfo.waitSemaphoreCount = 0;
1387 submitInfo.pWaitSemaphores = nullptr;
1388 submitInfo.pWaitDstStageMask = nullptr;
1389 submitInfo.commandBufferCount = 1;
1390 submitInfo.pCommandBuffers = commandBuffer.ptr();
1391 submitInfo.signalSemaphoreCount = 0;
1392 submitInfo.pSignalSemaphores = nullptr;
1393
1394 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1395
1396 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1397 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001398 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001399
1400 // Get the query results
1401 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1402
Yuly Novikov27780292018-11-09 11:19:49 -05001403 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1404 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1405 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001406
1407 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1408
Jamie Madill7c985f52018-11-29 18:16:17 -05001409 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001410}
1411
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001412// These functions look at the mandatory format for support, and fallback to querying the device (if
1413// necessary) to test the availability of the bits.
1414bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1415 const VkFormatFeatureFlags featureBits)
1416{
1417 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1418}
1419
1420bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1421 const VkFormatFeatureFlags featureBits)
1422{
1423 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1424}
1425
1426bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1427{
1428 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1429}
1430
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001431angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1432{
1433 ASSERT(mGpuEventsEnabled);
1434
1435 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1436 ASSERT(platform);
1437
1438 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1439 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1440 //
1441 // CPU GPU
1442 //
1443 // Record command buffer
1444 // with timestamp query
1445 //
1446 // Submit command buffer
1447 //
1448 // Post-submission work Begin execution
1449 //
1450 // ???? Write timstamp Tgpu
1451 //
1452 // ???? End execution
1453 //
1454 // ???? Return query results
1455 //
1456 // ????
1457 //
1458 // Get query results
1459 //
1460 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1461 // finished post-submission work while the GPU is executing in parallel. With no further work,
1462 // querying CPU timestamps before submission and after getting query results give the bounds to
1463 // Tgpu, which could be quite large.
1464 //
1465 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1466 // reduce this range. This function implements the following procedure:
1467 //
1468 // CPU GPU
1469 //
1470 // Record command buffer
1471 // with timestamp query
1472 //
1473 // Submit command buffer
1474 //
1475 // Post-submission work Begin execution
1476 //
1477 // ???? Set Event GPUReady
1478 //
1479 // Wait on Event GPUReady Wait on Event CPUReady
1480 //
1481 // Get CPU Time Ts Wait on Event CPUReady
1482 //
1483 // Set Event CPUReady Wait on Event CPUReady
1484 //
1485 // Get CPU Time Tcpu Get GPU Time Tgpu
1486 //
1487 // Wait on Event GPUDone Set Event GPUDone
1488 //
1489 // Get CPU Time Te End Execution
1490 //
1491 // Idle Return query results
1492 //
1493 // Get query results
1494 //
1495 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1496 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1497 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1498 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1499 // calibration.
1500 //
1501 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1502
1503 // Make sure nothing is running
1504 ASSERT(mCommandGraph.empty());
1505
1506 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1507
1508 // Create a query used to receive the GPU timestamp
1509 vk::QueryHelper timestampQuery;
1510 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1511
1512 // Create the three events
1513 VkEventCreateInfo eventCreateInfo = {};
1514 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1515 eventCreateInfo.flags = 0;
1516
1517 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001518 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1519 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1520 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001521
1522 constexpr uint32_t kRetries = 10;
1523
1524 // Time suffixes used are S for seconds and Cycles for cycles
1525 double tightestRangeS = 1e6f;
1526 double TcpuS = 0;
1527 uint64_t TgpuCycles = 0;
1528 for (uint32_t i = 0; i < kRetries; ++i)
1529 {
1530 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001531 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1532 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1533 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001534
1535 // Record the command buffer
1536 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1537 vk::CommandBuffer &commandBuffer = commandBatch.get();
1538
1539 VkCommandBufferAllocateInfo commandBufferInfo = {};
1540 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1541 commandBufferInfo.commandPool = mCommandPool.getHandle();
1542 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1543 commandBufferInfo.commandBufferCount = 1;
1544
Yuly Novikov27780292018-11-09 11:19:49 -05001545 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001546
1547 VkCommandBufferBeginInfo beginInfo = {};
1548 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1549 beginInfo.flags = 0;
1550 beginInfo.pInheritanceInfo = nullptr;
1551
Yuly Novikov27780292018-11-09 11:19:49 -05001552 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001553
1554 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1555 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1556 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1557 nullptr);
1558
1559 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1560 timestampQuery.getQuery(), 1);
1561 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1562 timestampQuery.getQueryPool()->getHandle(),
1563 timestampQuery.getQuery());
1564
1565 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1566
Yuly Novikov27780292018-11-09 11:19:49 -05001567 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001568
1569 // Submit the command buffer
1570 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1571 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1572 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1573
1574 VkSubmitInfo submitInfo = {};
1575 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1576 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1577 submitInfo.pWaitSemaphores = waitSemaphores.data();
1578 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1579 submitInfo.commandBufferCount = 1;
1580 submitInfo.pCommandBuffers = commandBuffer.ptr();
1581 submitInfo.signalSemaphoreCount = 0;
1582 submitInfo.pSignalSemaphores = nullptr;
1583
1584 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1585
1586 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001587 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001588 do
1589 {
Yuly Novikov27780292018-11-09 11:19:49 -05001590 result = gpuReady.get().getStatus(mDevice);
1591 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1592 {
1593 ANGLE_VK_TRY(context, result);
1594 }
1595 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001596
1597 double TsS = platform->monotonicallyIncreasingTime(platform);
1598
1599 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001600 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001601 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1602
1603 // Wait for GPU to be done. Another short busy wait.
1604 do
1605 {
Yuly Novikov27780292018-11-09 11:19:49 -05001606 result = gpuDone.get().getStatus(mDevice);
1607 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1608 {
1609 ANGLE_VK_TRY(context, result);
1610 }
1611 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001612
1613 double TeS = platform->monotonicallyIncreasingTime(platform);
1614
1615 // Get the query results
1616 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1617
1618 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1619
1620 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001621 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1622 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1623 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001624
1625 // Use the first timestamp queried as origin.
1626 if (mGpuEventTimestampOrigin == 0)
1627 {
1628 mGpuEventTimestampOrigin = gpuTimestampCycles;
1629 }
1630
1631 // Take these CPU and GPU timestamps if there is better confidence.
1632 double confidenceRangeS = TeS - TsS;
1633 if (confidenceRangeS < tightestRangeS)
1634 {
1635 tightestRangeS = confidenceRangeS;
1636 TcpuS = cpuTimestampS;
1637 TgpuCycles = gpuTimestampCycles;
1638 }
1639 }
1640
1641 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1642
1643 // timestampPeriod gives nanoseconds/cycle.
1644 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1645 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1646 1'000'000'000.0;
1647
1648 flushGpuEvents(TgpuS, TcpuS);
1649
1650 mGpuClockSync.gpuTimestampS = TgpuS;
1651 mGpuClockSync.cpuTimestampS = TcpuS;
1652
Jamie Madill7c985f52018-11-29 18:16:17 -05001653 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001654}
1655
1656angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1657 vk::CommandBuffer *commandBuffer,
1658 char phase,
1659 const char *name)
1660{
1661 ASSERT(mGpuEventsEnabled);
1662
1663 GpuEventQuery event;
1664
1665 event.name = name;
1666 event.phase = phase;
1667 event.serial = mCurrentQueueSerial;
1668
1669 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1670
1671 commandBuffer->resetQueryPool(
1672 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1673 commandBuffer->writeTimestamp(
1674 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1675 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1676
1677 mInFlightGpuEventQueries.push_back(std::move(event));
1678
Jamie Madill7c985f52018-11-29 18:16:17 -05001679 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001680}
1681
1682angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1683{
1684 ASSERT(mGpuEventsEnabled);
1685
1686 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1687 ASSERT(platform);
1688
1689 int finishedCount = 0;
1690
1691 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1692 {
1693 // Only check the timestamp query if the submission has finished.
1694 if (eventQuery.serial > mLastCompletedQueueSerial)
1695 {
1696 break;
1697 }
1698
1699 // See if the results are available.
1700 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001701 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1702 ->getResults(mDevice, eventQuery.queryIndex, 1,
1703 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1704 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1705 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001706 {
1707 break;
1708 }
Yuly Novikov27780292018-11-09 11:19:49 -05001709 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001710
1711 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1712
1713 GpuEvent event;
1714 event.gpuTimestampCycles = gpuTimestampCycles;
1715 event.name = eventQuery.name;
1716 event.phase = eventQuery.phase;
1717
1718 mGpuEvents.emplace_back(event);
1719
1720 ++finishedCount;
1721 }
1722
1723 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1724 mInFlightGpuEventQueries.begin() + finishedCount);
1725
Jamie Madill7c985f52018-11-29 18:16:17 -05001726 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001727}
1728
1729void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1730{
1731 if (mGpuEvents.size() == 0)
1732 {
1733 return;
1734 }
1735
1736 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1737 ASSERT(platform);
1738
1739 // Find the slope of the clock drift for adjustment
1740 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1741 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1742 double gpuSyncDriftSlope = 0;
1743
1744 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1745 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1746
1747 // No gpu trace events should have been generated before the clock sync, so if there is no
1748 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1749 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1750 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1751
1752 gpuSyncDriftSlope =
1753 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1754
1755 for (const GpuEvent &event : mGpuEvents)
1756 {
1757 double gpuTimestampS =
1758 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1759 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1760
1761 // Account for clock drift.
1762 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1763
1764 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1765 // for.
1766 static long long eventId = 1;
1767 static const unsigned char *categoryEnabled =
1768 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1769 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1770 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1771 }
1772
1773 mGpuEvents.clear();
1774}
1775
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001776template <VkFormatFeatureFlags VkFormatProperties::*features>
1777bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1778{
1779 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
1780 VkFormatProperties &deviceProperties = mFormatProperties[format];
1781
1782 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
1783 {
1784 // If we don't have the actual device features, see if the requested features are mandatory.
1785 // If so, there's no need to query the device.
1786 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
1787 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
1788 {
1789 return true;
1790 }
1791
1792 // Otherwise query the format features and cache it.
1793 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
1794 }
1795
1796 return IsMaskFlagSet(deviceProperties.*features, featureBits);
1797}
1798
Jamie Madillaaca96e2018-06-12 10:19:48 -04001799uint32_t GetUniformBufferDescriptorCount()
1800{
1801 return kUniformBufferDescriptorsPerDescriptorSet;
1802}
1803
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001804} // namespace rx