blob: b2a7e48552a4f9ffb1069065a09dd1f63ea933dc [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050018#include "common/system_utils.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040019#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050020#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050021#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050022#include "libANGLE/renderer/vulkan/CompilerVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040023#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050025#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050026#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050028#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050029#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040031
Shahbaz Youssefi61656022018-10-24 15:00:50 -040032#include "third_party/trace_event/trace_event.h"
33
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070034// Consts
35namespace
36{
Jamie Madillb980c562018-11-27 11:34:27 -050037const uint32_t kMockVendorID = 0xba5eba11;
38const uint32_t kMockDeviceID = 0xf005ba11;
39constexpr char kMockDeviceName[] = "Vulkan Mock Device";
Shahbaz Youssefi61656022018-10-24 15:00:50 -040040constexpr size_t kInFlightCommandsLimit = 100u;
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
Jamie Madillc7918ce2018-06-13 13:25:31 -0400333 mPipelineLayoutCache.destroy(mDevice);
334 mDescriptorSetLayoutCache.destroy(mDevice);
335
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500336 mFullScreenClearShaderProgram.destroy(mDevice);
337
Jamie Madill9f2a8612017-11-30 12:43:09 -0500338 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500339 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400340 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400341 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400342 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500343
Jamie Madill06ca6342018-07-12 15:56:53 -0400344 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500345
Jamie Madill5deea722017-02-16 10:44:46 -0500346 if (mCommandPool.valid())
347 {
348 mCommandPool.destroy(mDevice);
349 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500350
351 if (mDevice)
352 {
353 vkDestroyDevice(mDevice, nullptr);
354 mDevice = VK_NULL_HANDLE;
355 }
356
Jamie Madill0448ec82016-12-23 13:41:47 -0500357 if (mDebugReportCallback)
358 {
359 ASSERT(mInstance);
360 auto destroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
361 vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT"));
362 ASSERT(destroyDebugReportCallback);
363 destroyDebugReportCallback(mInstance, mDebugReportCallback, nullptr);
364 }
365
Jamie Madill4d0bf552016-12-28 15:45:24 -0500366 if (mInstance)
367 {
368 vkDestroyInstance(mInstance, nullptr);
369 mInstance = VK_NULL_HANDLE;
370 }
371
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600372 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500373 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500374}
375
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400376void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400377{
378 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400379
380 mCommandGraph.clear();
381 mLastSubmittedQueueSerial = mCurrentQueueSerial;
382 mCurrentQueueSerial = mQueueSerialFactory.generate();
383 freeAllInFlightResources();
384
385 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400386}
387
388bool RendererVk::isDeviceLost() const
389{
390 return mDeviceLost;
391}
392
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400393angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400394 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400395 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500396{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400397 mDisplay = display;
398 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600399 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
400 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500401 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400402 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500403
Jamie Madill0448ec82016-12-23 13:41:47 -0500404 // Gather global layer properties.
405 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400406 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500407
408 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
409 if (instanceLayerCount > 0)
410 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400411 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
412 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500413 }
414
Jamie Madille09bd5d2016-11-29 16:20:35 -0500415 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400416 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400417 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500418
419 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
420 if (instanceExtensionCount > 0)
421 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400422 ANGLE_VK_TRY(displayVk,
423 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
424 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500425 }
426
Yuly Novikov199f4292018-01-19 19:04:05 -0500427 const char *const *enabledLayerNames = nullptr;
428 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500429 if (mEnableValidationLayers)
430 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500431 bool layersRequested =
432 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
433 mEnableValidationLayers = GetAvailableValidationLayers(
434 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500435 }
436
Jamie Madille09bd5d2016-11-29 16:20:35 -0500437 std::vector<const char *> enabledInstanceExtensions;
438 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500439 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500440
Jamie Madill0448ec82016-12-23 13:41:47 -0500441 // TODO(jmadill): Should be able to continue initialization if debug report ext missing.
442 if (mEnableValidationLayers)
443 {
444 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
445 }
446
Jamie Madille09bd5d2016-11-29 16:20:35 -0500447 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400448 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400449 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500450
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400451 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500452 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500453 applicationInfo.pApplicationName = "ANGLE";
454 applicationInfo.applicationVersion = 1;
455 applicationInfo.pEngineName = "ANGLE";
456 applicationInfo.engineVersion = 1;
457 applicationInfo.apiVersion = VK_API_VERSION_1_0;
458
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400459 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500460 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
461 instanceInfo.flags = 0;
462 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500463
Jamie Madille09bd5d2016-11-29 16:20:35 -0500464 // Enable requested layers and extensions.
465 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
466 instanceInfo.ppEnabledExtensionNames =
467 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500468 instanceInfo.enabledLayerCount = enabledLayerCount;
469 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500470
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400471 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500472
Jamie Madill0448ec82016-12-23 13:41:47 -0500473 if (mEnableValidationLayers)
474 {
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400475 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500476
477 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500478 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
479 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
480 VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
481 debugReportInfo.pfnCallback = &DebugReportCallback;
482 debugReportInfo.pUserData = this;
483
484 auto createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
485 vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT"));
486 ASSERT(createDebugReportCallback);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400487 ANGLE_VK_TRY(displayVk, createDebugReportCallback(mInstance, &debugReportInfo, nullptr,
488 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500489 }
490
Jamie Madill4d0bf552016-12-28 15:45:24 -0500491 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400492 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
493 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500494
495 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700496 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400497 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
498 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400499 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700500 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500501
Jamie Madill30b5d842018-08-31 17:19:12 -0400502 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
503
Jamie Madill4d0bf552016-12-28 15:45:24 -0500504 // Ensure we can find a graphics queue family.
505 uint32_t queueCount = 0;
506 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
507
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400508 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500509
510 mQueueFamilyProperties.resize(queueCount);
511 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
512 mQueueFamilyProperties.data());
513
Jamie Madillb980c562018-11-27 11:34:27 -0500514 size_t graphicsQueueFamilyCount = false;
515 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500516 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500517 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
518 {
519 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500520 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500521 {
522 ASSERT(queueInfo.queueCount > 0);
523 graphicsQueueFamilyCount++;
524 if (firstGraphicsQueueFamily == 0)
525 {
526 firstGraphicsQueueFamily = familyIndex;
527 }
528 break;
529 }
530 }
531
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400532 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500533
Jamie Madill12222072018-07-11 14:59:48 -0400534 initFeatures();
535
Jamie Madill4d0bf552016-12-28 15:45:24 -0500536 // If only one queue family, go ahead and initialize the device. If there is more than one
537 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
538 if (graphicsQueueFamilyCount == 1)
539 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400540 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500541 }
542
Jamie Madill035fd6b2017-10-03 15:43:22 -0400543 // Store the physical device memory properties so we can find the right memory pools.
544 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500545
Jamie Madill06ca6342018-07-12 15:56:53 -0400546 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500547
Jamie Madill6a89d222017-11-02 11:59:51 -0400548 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500549 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400550
Jamie Madill21061022018-07-12 23:56:30 -0400551 return angle::Result::Continue();
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400552}
553
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400554angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500555{
556 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400557 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400558 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500559
560 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
561 if (deviceLayerCount > 0)
562 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400563 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
564 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500565 }
566
567 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400568 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
569 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500570
571 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
572 if (deviceExtensionCount > 0)
573 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400574 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
575 &deviceExtensionCount,
576 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500577 }
578
Yuly Novikov199f4292018-01-19 19:04:05 -0500579 const char *const *enabledLayerNames = nullptr;
580 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500581 if (mEnableValidationLayers)
582 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500583 mEnableValidationLayers = GetAvailableValidationLayers(
584 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500585 }
586
587 std::vector<const char *> enabledDeviceExtensions;
588 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
589
Luc Ferronbf6dc372018-06-28 15:24:19 -0400590 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
591 if (getFeatures().flipViewportY)
592 {
593 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
594 }
595
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400596 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500597
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400598 // Select additional features to be enabled
599 VkPhysicalDeviceFeatures enabledFeatures = {};
600 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
601
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400602 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500603
604 float zeroPriority = 0.0f;
605
606 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500607 queueCreateInfo.flags = 0;
608 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
609 queueCreateInfo.queueCount = 1;
610 queueCreateInfo.pQueuePriorities = &zeroPriority;
611
612 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400613 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500614
Jamie Madill50cf2be2018-06-15 09:46:57 -0400615 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400616 createInfo.flags = 0;
617 createInfo.queueCreateInfoCount = 1;
618 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500619 createInfo.enabledLayerCount = enabledLayerCount;
620 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500621 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
622 createInfo.ppEnabledExtensionNames =
623 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400624 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500625
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400626 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500627
628 mCurrentQueueFamilyIndex = queueFamilyIndex;
629
630 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
631
632 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400633 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500634 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
635 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
636 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500637
Yuly Novikov27780292018-11-09 11:19:49 -0500638 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400639
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400640 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500641 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500642
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400643 // Initialize the submission semaphore pool.
644 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
645
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400646#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
647 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
648 ASSERT(platform);
649
650 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
651 // platform discovery.
652 const unsigned char *gpuEventsEnabled =
653 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
654 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
655#endif
656
657 if (mGpuEventsEnabled)
658 {
659 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
660 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
661 vk::kDefaultTimestampQueryPoolSize));
662 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
663 }
664
Jamie Madill21061022018-07-12 23:56:30 -0400665 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500666}
667
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400668angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400669 VkSurfaceKHR surface,
670 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500671{
672 // We've already initialized a device, and can't re-create it unless it's never been used.
673 // TODO(jmadill): Handle the re-creation case if necessary.
674 if (mDevice != VK_NULL_HANDLE)
675 {
676 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
677
678 // Check if the current device supports present on this surface.
679 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400680 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400681 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500682 surface, &supportsPresent));
683
Jamie Madill6cad7732018-07-11 09:01:17 -0400684 if (supportsPresent == VK_TRUE)
685 {
686 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill21061022018-07-12 23:56:30 -0400687 return angle::Result::Continue();
Jamie Madill6cad7732018-07-11 09:01:17 -0400688 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500689 }
690
691 // Find a graphics and present queue.
692 Optional<uint32_t> newPresentQueue;
693 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500694 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500695 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
696 {
697 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500698 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500699 {
700 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400701 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
702 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500703
704 if (supportsPresent == VK_TRUE)
705 {
706 newPresentQueue = queueIndex;
707 break;
708 }
709 }
710 }
711
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400712 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
713 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500714
Jamie Madill6cad7732018-07-11 09:01:17 -0400715 *presentQueueOut = newPresentQueue.value();
Jamie Madill21061022018-07-12 23:56:30 -0400716 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500717}
718
719std::string RendererVk::getVendorString() const
720{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300721 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500722}
723
Jamie Madille09bd5d2016-11-29 16:20:35 -0500724std::string RendererVk::getRendererDescription() const
725{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500726 std::stringstream strstr;
727
728 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
729
730 strstr << "Vulkan ";
731 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
732 strstr << VK_VERSION_MINOR(apiVersion) << ".";
733 strstr << VK_VERSION_PATCH(apiVersion);
734
Olli Etuahoc6a06182018-04-13 14:11:46 +0300735 strstr << "(";
736
737 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
738 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
739 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
740 // driver detection.
741 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
742 {
743 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
744 }
745
746 strstr << mPhysicalDeviceProperties.deviceName << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500747
748 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500749}
750
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500751gl::Version RendererVk::getMaxSupportedESVersion() const
752{
753 // Declare GLES2 support if necessary features for GLES3 are missing
754 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
755
756 if (!necessaryFeaturesForES3)
757 {
758 return gl::Version(2, 0);
759 }
760
761 return gl::Version(3, 0);
762}
763
Jamie Madill12222072018-07-11 14:59:48 -0400764void RendererVk::initFeatures()
765{
Jamie Madillb36a4812018-09-25 10:15:11 -0400766// Use OpenGL line rasterization rules by default.
767// TODO(jmadill): Fix Android support. http://anglebug.com/2830
768#if defined(ANGLE_PLATFORM_ANDROID)
769 mFeatures.basicGLLineRasterization = false;
770#else
Jamie Madill12222072018-07-11 14:59:48 -0400771 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400772#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400773
Luc Ferronf786b702018-07-10 11:01:43 -0400774 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
775 // investigation. http://anglebug.com/2728
776 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400777
778#ifdef ANGLE_PLATFORM_WINDOWS
779 // http://anglebug.com/2838
780 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
781#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400782
783 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
784 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -0500785
786 // Work around incorrect NVIDIA point size range clamping.
787 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
788 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
789 {
790 mFeatures.clampPointSize = true;
791 }
Jamie Madill12222072018-07-11 14:59:48 -0400792}
793
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400794void RendererVk::initPipelineCacheVkKey()
795{
796 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
797 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
798 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
799 // there is no '\0' in the result.
800 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
801 {
802 hashStream << std::hex << c;
803 }
804 // Add the vendor and device id too for good measure.
805 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
806 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
807
808 const std::string &hashString = hashStream.str();
809 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
810 hashString.length(), mPipelineCacheVkBlobKey.data());
811}
812
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500813angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400814{
815 initPipelineCacheVkKey();
816
817 egl::BlobCache::Value initialData;
818 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
819 mPipelineCacheVkBlobKey, &initialData);
820
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400821 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400822
823 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400824 pipelineCacheCreateInfo.flags = 0;
825 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
826 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
827
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500828 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400829 return angle::Result::Continue();
830}
831
Jamie Madillacccc6c2016-05-03 17:22:10 -0400832void RendererVk::ensureCapsInitialized() const
833{
834 if (!mCapsInitialized)
835 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400836 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
837 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
838 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400839 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400840 mCapsInitialized = true;
841 }
842}
843
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400844void RendererVk::getSubmitWaitSemaphores(
845 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400846 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
847 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400848{
849 if (mSubmitLastSignaledSemaphore.getSemaphore())
850 {
851 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400852 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400853
854 // Return the semaphore to the pool (which will remain valid and unused until the
855 // queue it's about to be waited on has finished execution).
856 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
857 }
858
859 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
860 {
861 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400862 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
863
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400864 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
865 }
866 mSubmitWaitSemaphores.clear();
867}
868
Jamie Madillacccc6c2016-05-03 17:22:10 -0400869const gl::Caps &RendererVk::getNativeCaps() const
870{
871 ensureCapsInitialized();
872 return mNativeCaps;
873}
874
875const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
876{
877 ensureCapsInitialized();
878 return mNativeTextureCaps;
879}
880
881const gl::Extensions &RendererVk::getNativeExtensions() const
882{
883 ensureCapsInitialized();
884 return mNativeExtensions;
885}
886
887const gl::Limitations &RendererVk::getNativeLimitations() const
888{
889 ensureCapsInitialized();
890 return mNativeLimitations;
891}
892
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400893uint32_t RendererVk::getMaxActiveTextures()
894{
895 // TODO(lucferron): expose this limitation to GL in Context Caps
896 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
897 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
898}
899
Jamie Madill49ac74b2017-12-21 14:42:33 -0500900const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500901{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500902 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500903}
904
Jamie Madill21061022018-07-12 23:56:30 -0400905angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500906{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500907 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500908 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400909 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
910
Luc Ferron1617e692018-07-11 11:08:19 -0400911 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
912 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400913
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400914 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400915 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
916 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400917
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400918 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500919 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400920 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
921 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400922 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500923 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400924 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500925 submitInfo.signalSemaphoreCount = 0;
926 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500927
Jamie Madill21061022018-07-12 23:56:30 -0400928 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500929 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500930
Jamie Madill4c26fc22017-02-24 11:04:10 -0500931 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400932 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400933 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400934
935 if (mGpuEventsEnabled)
936 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400937 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400938 while (mInFlightGpuEventQueries.size() > 0)
939 {
940 ANGLE_TRY(checkCompletedGpuEvents(context));
941 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400942 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
943 // synchronization if there is no event to be adjusted (happens when finish() gets called
944 // multiple times towards the end of the application).
945 if (mGpuEvents.size() > 0)
946 {
947 ANGLE_TRY(synchronizeCpuGpuTime(context));
948 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400949 }
950
Jamie Madill21061022018-07-12 23:56:30 -0400951 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -0500952}
953
Jamie Madill0c0dc342017-03-24 14:18:51 -0400954void RendererVk::freeAllInFlightResources()
955{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500956 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400957 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400958 // On device loss we need to wait for fence to be signaled before destroying it
959 if (mDeviceLost)
960 {
961 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
962 // If wait times out, it is probably not possible to recover from lost device
963 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
964 }
Jamie Madill49ac74b2017-12-21 14:42:33 -0500965 batch.fence.destroy(mDevice);
966 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400967 }
968 mInFlightCommands.clear();
969
970 for (auto &garbage : mGarbage)
971 {
Jamie Madille88ec8e2017-10-31 17:18:14 -0400972 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400973 }
974 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400975
976 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400977}
978
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -0400979angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500980{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500981 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -0500982
Jamie Madill49ac74b2017-12-21 14:42:33 -0500983 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500984 {
Yuly Novikov27780292018-11-09 11:19:49 -0500985 VkResult result = batch.fence.getStatus(mDevice);
986 if (result == VK_NOT_READY)
987 {
Jamie Madill0c0dc342017-03-24 14:18:51 -0400988 break;
Yuly Novikov27780292018-11-09 11:19:49 -0500989 }
990 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -0500991
Jamie Madill49ac74b2017-12-21 14:42:33 -0500992 ASSERT(batch.serial > mLastCompletedQueueSerial);
993 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400994
Jamie Madill49ac74b2017-12-21 14:42:33 -0500995 batch.fence.destroy(mDevice);
996 batch.commandPool.destroy(mDevice);
997 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500998 }
999
Jamie Madill49ac74b2017-12-21 14:42:33 -05001000 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001001
1002 size_t freeIndex = 0;
1003 for (; freeIndex < mGarbage.size(); ++freeIndex)
1004 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001005 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001006 break;
1007 }
1008
1009 // Remove the entries from the garbage list - they should be ready to go.
1010 if (freeIndex > 0)
1011 {
1012 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001013 }
1014
Jamie Madill21061022018-07-12 23:56:30 -04001015 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001016}
1017
Jamie Madill21061022018-07-12 23:56:30 -04001018angle::Result RendererVk::submitFrame(vk::Context *context,
1019 const VkSubmitInfo &submitInfo,
1020 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001021{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001022 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001023 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001024 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1025 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001026
Jamie Madillbea35a62018-07-05 11:54:10 -04001027 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1028 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001029 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001030
Jamie Madill21061022018-07-12 23:56:30 -04001031 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001032
1033 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001034 batch.commandPool = std::move(mCommandPool);
1035 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001036
Jamie Madillbea35a62018-07-05 11:54:10 -04001037 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001038
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001039 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1040 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
1041 // so the limit is larger than the expected number of images.
1042 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001043
1044 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001045 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001046 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001047 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001048
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001049 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001050
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001051 if (mGpuEventsEnabled)
1052 {
1053 ANGLE_TRY(checkCompletedGpuEvents(context));
1054 }
1055
Jamie Madill49ac74b2017-12-21 14:42:33 -05001056 // Simply null out the command buffer here - it was allocated using the command pool.
1057 commandBuffer.releaseHandle();
1058
1059 // Reallocate the command pool for next frame.
1060 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001061 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001062 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001063 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001064 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001065
Yuly Novikov27780292018-11-09 11:19:49 -05001066 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
1067 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001068}
1069
Jamie Madillaaca96e2018-06-12 10:19:48 -04001070bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001071{
1072 return serial > mLastCompletedQueueSerial;
1073}
1074
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001075angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1076{
1077 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1078 {
1079 return angle::Result::Continue();
1080 }
1081
1082 // Find the first batch with serial equal to or bigger than given serial (note that
1083 // the batch serials are unique, otherwise upper-bound would have been necessary).
1084 size_t batchIndex = mInFlightCommands.size() - 1;
1085 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1086 {
1087 if (mInFlightCommands[i].serial >= serial)
1088 {
1089 batchIndex = i;
1090 break;
1091 }
1092 }
1093 const CommandBatch &batch = mInFlightCommands[batchIndex];
1094
1095 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001096 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001097
1098 // Clean up finished batches.
1099 return checkCompletedCommands(context);
1100}
1101
Jamie Madill21061022018-07-12 23:56:30 -04001102angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1103 const vk::RenderPassDesc &desc,
1104 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001105{
Jamie Madill21061022018-07-12 23:56:30 -04001106 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001107 renderPassOut);
1108}
1109
Jamie Madill21061022018-07-12 23:56:30 -04001110angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1111 const vk::RenderPassDesc &desc,
1112 const vk::AttachmentOpsArray &ops,
1113 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001114{
Jamie Madill21061022018-07-12 23:56:30 -04001115 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001116 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001117}
1118
Jamie Madilla5e06072018-05-18 14:36:05 -04001119vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001120{
Jamie Madilla5e06072018-05-18 14:36:05 -04001121 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001122}
1123
Jamie Madill21061022018-07-12 23:56:30 -04001124angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001125{
Jamie Madill21061022018-07-12 23:56:30 -04001126 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001127 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001128}
1129
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001130angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001131{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001132 if (mCommandGraph.empty())
1133 {
1134 return angle::Result::Continue();
1135 }
1136
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001137 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1138
Jamie Madillbea35a62018-07-05 11:54:10 -04001139 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1140 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001141
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001142 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001143 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1144 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001145
1146 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1147 // will be waited on.
1148 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001149
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001150 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001151 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001152 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1153 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001154 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001155 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001156 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001157 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001158 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001159
Jamie Madill21061022018-07-12 23:56:30 -04001160 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001161
Jamie Madill21061022018-07-12 23:56:30 -04001162 return angle::Result::Continue();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001163}
1164
Jamie Madill78feddc2018-04-27 11:45:05 -04001165Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001166{
Jamie Madill78feddc2018-04-27 11:45:05 -04001167 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001168}
1169
Jamie Madill21061022018-07-12 23:56:30 -04001170angle::Result RendererVk::getDescriptorSetLayout(
1171 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001172 const vk::DescriptorSetLayoutDesc &desc,
1173 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1174{
Jamie Madill21061022018-07-12 23:56:30 -04001175 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001176}
1177
Jamie Madill21061022018-07-12 23:56:30 -04001178angle::Result RendererVk::getPipelineLayout(
1179 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001180 const vk::PipelineLayoutDesc &desc,
1181 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1182 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1183{
Jamie Madill21061022018-07-12 23:56:30 -04001184 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001185 pipelineLayoutOut);
1186}
1187
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001188angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1189{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001190 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001191
1192 if (--mPipelineCacheVkUpdateTimeout > 0)
1193 {
1194 return angle::Result::Continue();
1195 }
1196
1197 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1198
1199 // Get the size of the cache.
1200 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001201 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001202 if (result != VK_INCOMPLETE)
1203 {
1204 ANGLE_VK_TRY(displayVk, result);
1205 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001206
1207 angle::MemoryBuffer *pipelineCacheData = nullptr;
1208 ANGLE_VK_CHECK_ALLOC(displayVk,
1209 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1210
1211 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001212 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001213 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1214 // was determined just above), so receiving it hints at an implementation bug we would want
1215 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001216 ASSERT(result != VK_INCOMPLETE);
1217 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001218
1219 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1220 // the buffer to avoid leaking garbage memory.
1221 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1222 if (pipelineCacheSize < originalPipelineCacheSize)
1223 {
1224 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1225 originalPipelineCacheSize - pipelineCacheSize);
1226 }
1227
1228 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1229
1230 return angle::Result::Continue();
1231}
1232
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001233angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1234 const vk::Semaphore **outSemaphore)
1235{
1236 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1237
1238 vk::SemaphoreHelper semaphore;
1239 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1240
1241 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1242 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1243
1244 return angle::Result::Continue();
1245}
1246
1247const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1248{
1249 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1250
1251 // Return the semaphore to the pool (which will remain valid and unused until the
1252 // queue it's about to be waited on has finished execution). The caller is about
1253 // to wait on it.
1254 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1255
1256 return semaphore;
1257}
1258
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001259angle::Result RendererVk::getFullScreenClearShaderProgram(vk::Context *context,
1260 vk::ShaderProgramHelper **programOut)
Jamie Madilld47044a2018-04-27 11:45:03 -04001261{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001262 if (!mFullScreenClearShaderProgram.valid())
1263 {
1264 vk::RefCounted<vk::ShaderAndSerial> *fullScreenQuad = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001265 ANGLE_TRY(mShaderLibrary.getFullScreenQuad_vert(context, 0, &fullScreenQuad));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001266
1267 vk::RefCounted<vk::ShaderAndSerial> *pushConstantColor = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001268 ANGLE_TRY(mShaderLibrary.getPushConstantColor_frag(context, 0, &pushConstantColor));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001269
1270 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Vertex, fullScreenQuad);
1271 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Fragment, pushConstantColor);
1272 }
1273
1274 *programOut = &mFullScreenClearShaderProgram;
1275 return angle::Result::Continue();
Jamie Madilld47044a2018-04-27 11:45:03 -04001276}
Luc Ferron90968362018-05-04 08:47:22 -04001277
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001278angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1279{
1280 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1281 // that seems impossible, so instead, we are going to make a small submission with just a
1282 // timestamp query. First, the disjoint timer query extension says:
1283 //
1284 // > This will return the GL time after all previous commands have reached the GL server but
1285 // have not yet necessarily executed.
1286 //
1287 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1288 // The wording allows us to make a submission to get the timestamp without performing a flush.
1289 //
1290 // Second:
1291 //
1292 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1293 // object target, applications can measure the latency between when commands reach the GL server
1294 // and when they are realized in the framebuffer.
1295 //
1296 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1297 // GPU bubble. This function directly generates a command buffer and submits it instead of
1298 // using the other member functions. This is to avoid changing any state, such as the queue
1299 // serial.
1300
1301 // Create a query used to receive the GPU timestamp
1302 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1303 vk::QueryHelper timestampQuery;
1304 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1305 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1306
1307 // Record the command buffer
1308 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1309 vk::CommandBuffer &commandBuffer = commandBatch.get();
1310
1311 VkCommandBufferAllocateInfo commandBufferInfo = {};
1312 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1313 commandBufferInfo.commandPool = mCommandPool.getHandle();
1314 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1315 commandBufferInfo.commandBufferCount = 1;
1316
Yuly Novikov27780292018-11-09 11:19:49 -05001317 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001318
1319 VkCommandBufferBeginInfo beginInfo = {};
1320 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1321 beginInfo.flags = 0;
1322 beginInfo.pInheritanceInfo = nullptr;
1323
Yuly Novikov27780292018-11-09 11:19:49 -05001324 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001325
1326 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1327 timestampQuery.getQuery(), 1);
1328 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1329 timestampQuery.getQueryPool()->getHandle(),
1330 timestampQuery.getQuery());
1331
Yuly Novikov27780292018-11-09 11:19:49 -05001332 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001333
1334 // Create fence for the submission
1335 VkFenceCreateInfo fenceInfo = {};
1336 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1337 fenceInfo.flags = 0;
1338
1339 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001340 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001341
1342 // Submit the command buffer
1343 VkSubmitInfo submitInfo = {};
1344 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1345 submitInfo.waitSemaphoreCount = 0;
1346 submitInfo.pWaitSemaphores = nullptr;
1347 submitInfo.pWaitDstStageMask = nullptr;
1348 submitInfo.commandBufferCount = 1;
1349 submitInfo.pCommandBuffers = commandBuffer.ptr();
1350 submitInfo.signalSemaphoreCount = 0;
1351 submitInfo.pSignalSemaphores = nullptr;
1352
1353 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1354
1355 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1356 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001357 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001358
1359 // Get the query results
1360 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1361
Yuly Novikov27780292018-11-09 11:19:49 -05001362 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1363 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1364 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001365
1366 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1367
1368 return angle::Result::Continue();
1369}
1370
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001371// These functions look at the mandatory format for support, and fallback to querying the device (if
1372// necessary) to test the availability of the bits.
1373bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1374 const VkFormatFeatureFlags featureBits)
1375{
1376 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1377}
1378
1379bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1380 const VkFormatFeatureFlags featureBits)
1381{
1382 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1383}
1384
1385bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1386{
1387 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1388}
1389
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001390angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1391{
1392 ASSERT(mGpuEventsEnabled);
1393
1394 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1395 ASSERT(platform);
1396
1397 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1398 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1399 //
1400 // CPU GPU
1401 //
1402 // Record command buffer
1403 // with timestamp query
1404 //
1405 // Submit command buffer
1406 //
1407 // Post-submission work Begin execution
1408 //
1409 // ???? Write timstamp Tgpu
1410 //
1411 // ???? End execution
1412 //
1413 // ???? Return query results
1414 //
1415 // ????
1416 //
1417 // Get query results
1418 //
1419 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1420 // finished post-submission work while the GPU is executing in parallel. With no further work,
1421 // querying CPU timestamps before submission and after getting query results give the bounds to
1422 // Tgpu, which could be quite large.
1423 //
1424 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1425 // reduce this range. This function implements the following procedure:
1426 //
1427 // CPU GPU
1428 //
1429 // Record command buffer
1430 // with timestamp query
1431 //
1432 // Submit command buffer
1433 //
1434 // Post-submission work Begin execution
1435 //
1436 // ???? Set Event GPUReady
1437 //
1438 // Wait on Event GPUReady Wait on Event CPUReady
1439 //
1440 // Get CPU Time Ts Wait on Event CPUReady
1441 //
1442 // Set Event CPUReady Wait on Event CPUReady
1443 //
1444 // Get CPU Time Tcpu Get GPU Time Tgpu
1445 //
1446 // Wait on Event GPUDone Set Event GPUDone
1447 //
1448 // Get CPU Time Te End Execution
1449 //
1450 // Idle Return query results
1451 //
1452 // Get query results
1453 //
1454 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1455 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1456 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1457 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1458 // calibration.
1459 //
1460 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1461
1462 // Make sure nothing is running
1463 ASSERT(mCommandGraph.empty());
1464
1465 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1466
1467 // Create a query used to receive the GPU timestamp
1468 vk::QueryHelper timestampQuery;
1469 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1470
1471 // Create the three events
1472 VkEventCreateInfo eventCreateInfo = {};
1473 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1474 eventCreateInfo.flags = 0;
1475
1476 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001477 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1478 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1479 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001480
1481 constexpr uint32_t kRetries = 10;
1482
1483 // Time suffixes used are S for seconds and Cycles for cycles
1484 double tightestRangeS = 1e6f;
1485 double TcpuS = 0;
1486 uint64_t TgpuCycles = 0;
1487 for (uint32_t i = 0; i < kRetries; ++i)
1488 {
1489 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001490 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1491 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1492 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001493
1494 // Record the command buffer
1495 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1496 vk::CommandBuffer &commandBuffer = commandBatch.get();
1497
1498 VkCommandBufferAllocateInfo commandBufferInfo = {};
1499 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1500 commandBufferInfo.commandPool = mCommandPool.getHandle();
1501 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1502 commandBufferInfo.commandBufferCount = 1;
1503
Yuly Novikov27780292018-11-09 11:19:49 -05001504 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001505
1506 VkCommandBufferBeginInfo beginInfo = {};
1507 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1508 beginInfo.flags = 0;
1509 beginInfo.pInheritanceInfo = nullptr;
1510
Yuly Novikov27780292018-11-09 11:19:49 -05001511 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001512
1513 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1514 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1515 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1516 nullptr);
1517
1518 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1519 timestampQuery.getQuery(), 1);
1520 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1521 timestampQuery.getQueryPool()->getHandle(),
1522 timestampQuery.getQuery());
1523
1524 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1525
Yuly Novikov27780292018-11-09 11:19:49 -05001526 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001527
1528 // Submit the command buffer
1529 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1530 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1531 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1532
1533 VkSubmitInfo submitInfo = {};
1534 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1535 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1536 submitInfo.pWaitSemaphores = waitSemaphores.data();
1537 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1538 submitInfo.commandBufferCount = 1;
1539 submitInfo.pCommandBuffers = commandBuffer.ptr();
1540 submitInfo.signalSemaphoreCount = 0;
1541 submitInfo.pSignalSemaphores = nullptr;
1542
1543 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1544
1545 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001546 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001547 do
1548 {
Yuly Novikov27780292018-11-09 11:19:49 -05001549 result = gpuReady.get().getStatus(mDevice);
1550 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1551 {
1552 ANGLE_VK_TRY(context, result);
1553 }
1554 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001555
1556 double TsS = platform->monotonicallyIncreasingTime(platform);
1557
1558 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001559 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001560 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1561
1562 // Wait for GPU to be done. Another short busy wait.
1563 do
1564 {
Yuly Novikov27780292018-11-09 11:19:49 -05001565 result = gpuDone.get().getStatus(mDevice);
1566 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1567 {
1568 ANGLE_VK_TRY(context, result);
1569 }
1570 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001571
1572 double TeS = platform->monotonicallyIncreasingTime(platform);
1573
1574 // Get the query results
1575 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1576
1577 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1578
1579 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001580 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1581 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1582 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001583
1584 // Use the first timestamp queried as origin.
1585 if (mGpuEventTimestampOrigin == 0)
1586 {
1587 mGpuEventTimestampOrigin = gpuTimestampCycles;
1588 }
1589
1590 // Take these CPU and GPU timestamps if there is better confidence.
1591 double confidenceRangeS = TeS - TsS;
1592 if (confidenceRangeS < tightestRangeS)
1593 {
1594 tightestRangeS = confidenceRangeS;
1595 TcpuS = cpuTimestampS;
1596 TgpuCycles = gpuTimestampCycles;
1597 }
1598 }
1599
1600 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1601
1602 // timestampPeriod gives nanoseconds/cycle.
1603 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1604 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1605 1'000'000'000.0;
1606
1607 flushGpuEvents(TgpuS, TcpuS);
1608
1609 mGpuClockSync.gpuTimestampS = TgpuS;
1610 mGpuClockSync.cpuTimestampS = TcpuS;
1611
1612 return angle::Result::Continue();
1613}
1614
1615angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1616 vk::CommandBuffer *commandBuffer,
1617 char phase,
1618 const char *name)
1619{
1620 ASSERT(mGpuEventsEnabled);
1621
1622 GpuEventQuery event;
1623
1624 event.name = name;
1625 event.phase = phase;
1626 event.serial = mCurrentQueueSerial;
1627
1628 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1629
1630 commandBuffer->resetQueryPool(
1631 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1632 commandBuffer->writeTimestamp(
1633 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1634 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1635
1636 mInFlightGpuEventQueries.push_back(std::move(event));
1637
1638 return angle::Result::Continue();
1639}
1640
1641angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1642{
1643 ASSERT(mGpuEventsEnabled);
1644
1645 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1646 ASSERT(platform);
1647
1648 int finishedCount = 0;
1649
1650 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1651 {
1652 // Only check the timestamp query if the submission has finished.
1653 if (eventQuery.serial > mLastCompletedQueueSerial)
1654 {
1655 break;
1656 }
1657
1658 // See if the results are available.
1659 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001660 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1661 ->getResults(mDevice, eventQuery.queryIndex, 1,
1662 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1663 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1664 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001665 {
1666 break;
1667 }
Yuly Novikov27780292018-11-09 11:19:49 -05001668 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001669
1670 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1671
1672 GpuEvent event;
1673 event.gpuTimestampCycles = gpuTimestampCycles;
1674 event.name = eventQuery.name;
1675 event.phase = eventQuery.phase;
1676
1677 mGpuEvents.emplace_back(event);
1678
1679 ++finishedCount;
1680 }
1681
1682 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1683 mInFlightGpuEventQueries.begin() + finishedCount);
1684
1685 return angle::Result::Continue();
1686}
1687
1688void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1689{
1690 if (mGpuEvents.size() == 0)
1691 {
1692 return;
1693 }
1694
1695 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1696 ASSERT(platform);
1697
1698 // Find the slope of the clock drift for adjustment
1699 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1700 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1701 double gpuSyncDriftSlope = 0;
1702
1703 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1704 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1705
1706 // No gpu trace events should have been generated before the clock sync, so if there is no
1707 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1708 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1709 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1710
1711 gpuSyncDriftSlope =
1712 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1713
1714 for (const GpuEvent &event : mGpuEvents)
1715 {
1716 double gpuTimestampS =
1717 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1718 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1719
1720 // Account for clock drift.
1721 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1722
1723 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1724 // for.
1725 static long long eventId = 1;
1726 static const unsigned char *categoryEnabled =
1727 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1728 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1729 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1730 }
1731
1732 mGpuEvents.clear();
1733}
1734
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001735template <VkFormatFeatureFlags VkFormatProperties::*features>
1736bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1737{
1738 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
1739 VkFormatProperties &deviceProperties = mFormatProperties[format];
1740
1741 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
1742 {
1743 // If we don't have the actual device features, see if the requested features are mandatory.
1744 // If so, there's no need to query the device.
1745 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
1746 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
1747 {
1748 return true;
1749 }
1750
1751 // Otherwise query the format features and cache it.
1752 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
1753 }
1754
1755 return IsMaskFlagSet(deviceProperties.*features, featureBits);
1756}
1757
Jamie Madillaaca96e2018-06-12 10:19:48 -04001758uint32_t GetUniformBufferDescriptorCount()
1759{
1760 return kUniformBufferDescriptorsPerDescriptorSet;
1761}
1762
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001763} // namespace rx