blob: 4bea3526f89055bf2557af0676264223d086fbaa [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050018#include "common/system_utils.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040019#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050020#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050021#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050022#include "libANGLE/renderer/vulkan/CompilerVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040023#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050025#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050026#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050028#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050029#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040031
Shahbaz Youssefi61656022018-10-24 15:00:50 -040032#include "third_party/trace_event/trace_event.h"
33
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070034// Consts
35namespace
36{
Jamie Madill7c985f52018-11-29 18:16:17 -050037const uint32_t kMockVendorID = 0xba5eba11;
38const uint32_t kMockDeviceID = 0xf005ba11;
39constexpr char kMockDeviceName[] = "Vulkan Mock Device";
40constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050041constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070042} // anonymous namespace
43
Jamie Madill9e54b5a2016-05-25 12:57:39 -040044namespace rx
45{
46
Jamie Madille09bd5d2016-11-29 16:20:35 -050047namespace
48{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040049// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
50// one for the vertex shader.
51constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040052// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
53static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040054// Wait a maximum of 10s. If that times out, we declare it a failure.
55static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050056
Omar El Sheikh26c61b22018-06-29 12:50:59 -060057bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
58{
59#if !defined(ANGLE_PLATFORM_ANDROID)
60 // Mock ICD does not currently run on Android
61 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
62 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
63 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
64#else
65 return false;
66#endif // !defined(ANGLE_PLATFORM_ANDROID)
67}
68
Jamie Madille09bd5d2016-11-29 16:20:35 -050069VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
70 const std::vector<const char *> &enabledExtensionNames)
71{
72 // Compile the extensions names into a set.
73 std::set<std::string> extensionNames;
74 for (const auto &extensionProp : extensionProps)
75 {
76 extensionNames.insert(extensionProp.extensionName);
77 }
78
Jamie Madillacf2f3a2017-11-21 19:22:44 -050079 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050080 {
81 if (extensionNames.count(extensionName) == 0)
82 {
83 return VK_ERROR_EXTENSION_NOT_PRESENT;
84 }
85 }
86
87 return VK_SUCCESS;
88}
89
Tobin Ehlis3a181e32018-08-29 15:17:05 -060090// Array of Validation error/warning messages that will be ignored, should include bugID
91constexpr std::array<const char *, 1> kSkippedMessages = {
92 // http://anglebug.com/2796
93 " [ UNASSIGNED-CoreValidation-Shader-PointSizeMissing ] Object: VK_NULL_HANDLE (Type = 19) "
94 "| Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader "
95 "corresponding to VK_SHADER_STAGE_VERTEX_BIT."};
96
97// Suppress validation errors that are known
98// return "true" if given code/prefix/message is known, else return "false"
99bool IsIgnoredDebugMessage(const char *message)
100{
101 for (const auto &msg : kSkippedMessages)
102 {
103 if (strcmp(msg, message) == 0)
104 {
105 return true;
106 }
107 }
108 return false;
109}
110
Yuly Novikov199f4292018-01-19 19:04:05 -0500111VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
112 VkDebugReportObjectTypeEXT objectType,
113 uint64_t object,
114 size_t location,
115 int32_t messageCode,
116 const char *layerPrefix,
117 const char *message,
118 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500119{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600120 if (IsIgnoredDebugMessage(message))
121 {
122 return VK_FALSE;
123 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500124 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
125 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500126 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500127#if !defined(NDEBUG)
128 // Abort the call in Debug builds.
129 return VK_TRUE;
130#endif
131 }
132 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
133 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500134 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500135 }
136 else
137 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500138 // Uncomment this if you want Vulkan spam.
139 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500140 }
141
142 return VK_FALSE;
143}
144
Yuly Novikov199f4292018-01-19 19:04:05 -0500145// If we're loading the validation layers, we could be running from any random directory.
146// Change to the executable directory so we can find the layers, then change back to the
147// previous directory to be safe we don't disrupt the application.
148class ScopedVkLoaderEnvironment : angle::NonCopyable
149{
150 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600151 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
152 : mEnableValidationLayers(enableValidationLayers),
153 mEnableMockICD(enableMockICD),
154 mChangedCWD(false),
155 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500156 {
157// Changing CWD and setting environment variables makes no sense on Android,
158// since this code is a part of Java application there.
159// Android Vulkan loader doesn't need this either.
160#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600161 if (enableMockICD)
162 {
163 // Override environment variable to use built Mock ICD
164 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
165 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
166 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
167 if (!mChangedICDPath)
168 {
169 ERR() << "Error setting Path for Mock/Null Driver.";
170 mEnableMockICD = false;
171 }
172 }
Jamie Madill46848422018-08-09 10:46:06 -0400173 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500174 {
175 const auto &cwd = angle::GetCWD();
176 if (!cwd.valid())
177 {
178 ERR() << "Error getting CWD for Vulkan layers init.";
179 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400180 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500181 }
182 else
183 {
184 mPreviousCWD = cwd.value();
185 const char *exeDir = angle::GetExecutableDirectory();
186 mChangedCWD = angle::SetCWD(exeDir);
187 if (!mChangedCWD)
188 {
189 ERR() << "Error setting CWD for Vulkan layers init.";
190 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400191 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500192 }
193 }
194 }
195
196 // Override environment variable to use the ANGLE layers.
197 if (mEnableValidationLayers)
198 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700199 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500200 {
201 ERR() << "Error setting environment for Vulkan layers init.";
202 mEnableValidationLayers = false;
203 }
204 }
205#endif // !defined(ANGLE_PLATFORM_ANDROID)
206 }
207
208 ~ScopedVkLoaderEnvironment()
209 {
210 if (mChangedCWD)
211 {
212#if !defined(ANGLE_PLATFORM_ANDROID)
213 ASSERT(mPreviousCWD.valid());
214 angle::SetCWD(mPreviousCWD.value().c_str());
215#endif // !defined(ANGLE_PLATFORM_ANDROID)
216 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600217 if (mChangedICDPath)
218 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600219 if (mPreviousICDPath.value().empty())
220 {
221 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
222 }
223 else
224 {
225 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
226 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600227 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500228 }
229
Jamie Madillaaca96e2018-06-12 10:19:48 -0400230 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500231
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600232 bool canEnableMockICD() const { return mEnableMockICD; }
233
Yuly Novikov199f4292018-01-19 19:04:05 -0500234 private:
235 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600236 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500237 bool mChangedCWD;
238 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600239 bool mChangedICDPath;
240 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500241};
242
Jamie Madill21061022018-07-12 23:56:30 -0400243void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
244 bool preferMockICD,
245 VkPhysicalDevice *physicalDeviceOut,
246 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
247{
248 ASSERT(!physicalDevices.empty());
249 if (preferMockICD)
250 {
251 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
252 {
253 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
254 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
255 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
256 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
257 {
258 *physicalDeviceOut = physicalDevice;
259 return;
260 }
261 }
262 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
263 "physicalDevice instead.";
264 }
265
266 // Fall back to first device.
267 *physicalDeviceOut = physicalDevices[0];
268 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
269}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400270
271// Initially dumping the command graphs is disabled.
272constexpr bool kEnableCommandGraphDiagnostics = false;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500273} // anonymous namespace
274
Jamie Madill49ac74b2017-12-21 14:42:33 -0500275// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400276RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500277
Jamie Madillaaca96e2018-06-12 10:19:48 -0400278RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500279
280RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
281 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500282{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500283
284RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
285{
286 std::swap(commandPool, other.commandPool);
287 std::swap(fence, other.fence);
288 std::swap(serial, other.serial);
289 return *this;
290}
291
Jamie Madillbea35a62018-07-05 11:54:10 -0400292void RendererVk::CommandBatch::destroy(VkDevice device)
293{
294 commandPool.destroy(device);
295 fence.destroy(device);
296}
297
Jamie Madill9f2a8612017-11-30 12:43:09 -0500298// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500299RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400300 : mDisplay(nullptr),
301 mCapsInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500302 mInstance(VK_NULL_HANDLE),
303 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400304 mEnableMockICD(false),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500305 mDebugReportCallback(VK_NULL_HANDLE),
306 mPhysicalDevice(VK_NULL_HANDLE),
307 mQueue(VK_NULL_HANDLE),
308 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
309 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400310 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400311 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400312 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400313 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400314 mCommandGraph(kEnableCommandGraphDiagnostics),
315 mGpuEventsEnabled(false),
316 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
317 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500318{
319 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
320 mFormatProperties.fill(invalid);
321}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400322
Jamie Madillb980c562018-11-27 11:34:27 -0500323RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400324
325void RendererVk::onDestroy(vk::Context *context)
326{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500327 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500328 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500329 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400330 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500331 }
332
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500333 mDispatchUtils.destroy(mDevice);
334
Jamie Madillc7918ce2018-06-13 13:25:31 -0400335 mPipelineLayoutCache.destroy(mDevice);
336 mDescriptorSetLayoutCache.destroy(mDevice);
337
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500338 mFullScreenClearShaderProgram.destroy(mDevice);
339
Jamie Madill9f2a8612017-11-30 12:43:09 -0500340 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500341 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400342 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400343 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400344 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500345
Jamie Madill06ca6342018-07-12 15:56:53 -0400346 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500347
Jamie Madill5deea722017-02-16 10:44:46 -0500348 if (mCommandPool.valid())
349 {
350 mCommandPool.destroy(mDevice);
351 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500352
353 if (mDevice)
354 {
355 vkDestroyDevice(mDevice, nullptr);
356 mDevice = VK_NULL_HANDLE;
357 }
358
Jamie Madill0448ec82016-12-23 13:41:47 -0500359 if (mDebugReportCallback)
360 {
361 ASSERT(mInstance);
362 auto destroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
363 vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT"));
364 ASSERT(destroyDebugReportCallback);
365 destroyDebugReportCallback(mInstance, mDebugReportCallback, nullptr);
366 }
367
Jamie Madill4d0bf552016-12-28 15:45:24 -0500368 if (mInstance)
369 {
370 vkDestroyInstance(mInstance, nullptr);
371 mInstance = VK_NULL_HANDLE;
372 }
373
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600374 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500375 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500376}
377
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400378void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400379{
380 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400381
382 mCommandGraph.clear();
383 mLastSubmittedQueueSerial = mCurrentQueueSerial;
384 mCurrentQueueSerial = mQueueSerialFactory.generate();
385 freeAllInFlightResources();
386
387 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400388}
389
390bool RendererVk::isDeviceLost() const
391{
392 return mDeviceLost;
393}
394
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400395angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400396 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400397 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500398{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400399 mDisplay = display;
400 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600401 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
402 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500403 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400404 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500405
Jamie Madill0448ec82016-12-23 13:41:47 -0500406 // Gather global layer properties.
407 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400408 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500409
410 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
411 if (instanceLayerCount > 0)
412 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400413 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
414 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500415 }
416
Jamie Madille09bd5d2016-11-29 16:20:35 -0500417 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400418 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400419 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500420
421 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
422 if (instanceExtensionCount > 0)
423 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400424 ANGLE_VK_TRY(displayVk,
425 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
426 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500427 }
428
Yuly Novikov199f4292018-01-19 19:04:05 -0500429 const char *const *enabledLayerNames = nullptr;
430 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500431 if (mEnableValidationLayers)
432 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500433 bool layersRequested =
434 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
435 mEnableValidationLayers = GetAvailableValidationLayers(
436 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500437 }
438
Jamie Madille09bd5d2016-11-29 16:20:35 -0500439 std::vector<const char *> enabledInstanceExtensions;
440 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500441 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500442
Jamie Madill0448ec82016-12-23 13:41:47 -0500443 // TODO(jmadill): Should be able to continue initialization if debug report ext missing.
444 if (mEnableValidationLayers)
445 {
446 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
447 }
448
Jamie Madille09bd5d2016-11-29 16:20:35 -0500449 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400450 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400451 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500452
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400453 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500454 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500455 applicationInfo.pApplicationName = "ANGLE";
456 applicationInfo.applicationVersion = 1;
457 applicationInfo.pEngineName = "ANGLE";
458 applicationInfo.engineVersion = 1;
459 applicationInfo.apiVersion = VK_API_VERSION_1_0;
460
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400461 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500462 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
463 instanceInfo.flags = 0;
464 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500465
Jamie Madille09bd5d2016-11-29 16:20:35 -0500466 // Enable requested layers and extensions.
467 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
468 instanceInfo.ppEnabledExtensionNames =
469 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500470 instanceInfo.enabledLayerCount = enabledLayerCount;
471 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500472
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400473 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500474
Jamie Madill0448ec82016-12-23 13:41:47 -0500475 if (mEnableValidationLayers)
476 {
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400477 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500478
479 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500480 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
481 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
482 VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
483 debugReportInfo.pfnCallback = &DebugReportCallback;
484 debugReportInfo.pUserData = this;
485
486 auto createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
487 vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT"));
488 ASSERT(createDebugReportCallback);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400489 ANGLE_VK_TRY(displayVk, createDebugReportCallback(mInstance, &debugReportInfo, nullptr,
490 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500491 }
492
Jamie Madill4d0bf552016-12-28 15:45:24 -0500493 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400494 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
495 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500496
497 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700498 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400499 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
500 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400501 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700502 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500503
Jamie Madill30b5d842018-08-31 17:19:12 -0400504 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
505
Jamie Madill4d0bf552016-12-28 15:45:24 -0500506 // Ensure we can find a graphics queue family.
507 uint32_t queueCount = 0;
508 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
509
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400510 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500511
512 mQueueFamilyProperties.resize(queueCount);
513 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
514 mQueueFamilyProperties.data());
515
Jamie Madillb980c562018-11-27 11:34:27 -0500516 size_t graphicsQueueFamilyCount = false;
517 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500518 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500519 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
520 {
521 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500522 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500523 {
524 ASSERT(queueInfo.queueCount > 0);
525 graphicsQueueFamilyCount++;
526 if (firstGraphicsQueueFamily == 0)
527 {
528 firstGraphicsQueueFamily = familyIndex;
529 }
530 break;
531 }
532 }
533
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400534 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500535
Jamie Madill12222072018-07-11 14:59:48 -0400536 initFeatures();
537
Jamie Madill4d0bf552016-12-28 15:45:24 -0500538 // If only one queue family, go ahead and initialize the device. If there is more than one
539 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
540 if (graphicsQueueFamilyCount == 1)
541 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400542 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500543 }
544
Jamie Madill035fd6b2017-10-03 15:43:22 -0400545 // Store the physical device memory properties so we can find the right memory pools.
546 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500547
Jamie Madill06ca6342018-07-12 15:56:53 -0400548 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500549
Jamie Madill6a89d222017-11-02 11:59:51 -0400550 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500551 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400552
Jamie Madill7c985f52018-11-29 18:16:17 -0500553 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400554}
555
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400556angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500557{
558 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400559 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400560 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500561
562 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
563 if (deviceLayerCount > 0)
564 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400565 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
566 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 }
568
569 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400570 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
571 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500572
573 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
574 if (deviceExtensionCount > 0)
575 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400576 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
577 &deviceExtensionCount,
578 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500579 }
580
Yuly Novikov199f4292018-01-19 19:04:05 -0500581 const char *const *enabledLayerNames = nullptr;
582 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500583 if (mEnableValidationLayers)
584 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500585 mEnableValidationLayers = GetAvailableValidationLayers(
586 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500587 }
588
589 std::vector<const char *> enabledDeviceExtensions;
590 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
591
Luc Ferronbf6dc372018-06-28 15:24:19 -0400592 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
593 if (getFeatures().flipViewportY)
594 {
595 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
596 }
597
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400598 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500599
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400600 // Select additional features to be enabled
601 VkPhysicalDeviceFeatures enabledFeatures = {};
602 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
603
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400604 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500605
606 float zeroPriority = 0.0f;
607
608 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500609 queueCreateInfo.flags = 0;
610 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
611 queueCreateInfo.queueCount = 1;
612 queueCreateInfo.pQueuePriorities = &zeroPriority;
613
614 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400615 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500616
Jamie Madill50cf2be2018-06-15 09:46:57 -0400617 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400618 createInfo.flags = 0;
619 createInfo.queueCreateInfoCount = 1;
620 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500621 createInfo.enabledLayerCount = enabledLayerCount;
622 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500623 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
624 createInfo.ppEnabledExtensionNames =
625 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400626 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500627
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400628 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500629
630 mCurrentQueueFamilyIndex = queueFamilyIndex;
631
632 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
633
634 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400635 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500636 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
637 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
638 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500639
Yuly Novikov27780292018-11-09 11:19:49 -0500640 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400641
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400642 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500643 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500644
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400645 // Initialize the submission semaphore pool.
646 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
647
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400648#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
649 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
650 ASSERT(platform);
651
652 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
653 // platform discovery.
654 const unsigned char *gpuEventsEnabled =
655 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
656 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
657#endif
658
659 if (mGpuEventsEnabled)
660 {
661 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
662 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
663 vk::kDefaultTimestampQueryPoolSize));
664 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
665 }
666
Jamie Madill7c985f52018-11-29 18:16:17 -0500667 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500668}
669
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400670angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400671 VkSurfaceKHR surface,
672 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500673{
674 // We've already initialized a device, and can't re-create it unless it's never been used.
675 // TODO(jmadill): Handle the re-creation case if necessary.
676 if (mDevice != VK_NULL_HANDLE)
677 {
678 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
679
680 // Check if the current device supports present on this surface.
681 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400682 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400683 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500684 surface, &supportsPresent));
685
Jamie Madill6cad7732018-07-11 09:01:17 -0400686 if (supportsPresent == VK_TRUE)
687 {
688 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500689 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400690 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500691 }
692
693 // Find a graphics and present queue.
694 Optional<uint32_t> newPresentQueue;
695 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500696 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500697 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
698 {
699 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500700 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500701 {
702 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400703 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
704 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500705
706 if (supportsPresent == VK_TRUE)
707 {
708 newPresentQueue = queueIndex;
709 break;
710 }
711 }
712 }
713
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400714 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
715 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500716
Jamie Madill6cad7732018-07-11 09:01:17 -0400717 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500718 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500719}
720
721std::string RendererVk::getVendorString() const
722{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300723 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500724}
725
Jamie Madille09bd5d2016-11-29 16:20:35 -0500726std::string RendererVk::getRendererDescription() const
727{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500728 std::stringstream strstr;
729
730 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
731
732 strstr << "Vulkan ";
733 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
734 strstr << VK_VERSION_MINOR(apiVersion) << ".";
735 strstr << VK_VERSION_PATCH(apiVersion);
736
Olli Etuahoc6a06182018-04-13 14:11:46 +0300737 strstr << "(";
738
739 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
740 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
741 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
742 // driver detection.
743 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
744 {
745 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
746 }
747
748 strstr << mPhysicalDeviceProperties.deviceName << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500749
750 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500751}
752
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500753gl::Version RendererVk::getMaxSupportedESVersion() const
754{
755 // Declare GLES2 support if necessary features for GLES3 are missing
756 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
757
758 if (!necessaryFeaturesForES3)
759 {
760 return gl::Version(2, 0);
761 }
762
763 return gl::Version(3, 0);
764}
765
Jamie Madill12222072018-07-11 14:59:48 -0400766void RendererVk::initFeatures()
767{
Jamie Madillb36a4812018-09-25 10:15:11 -0400768// Use OpenGL line rasterization rules by default.
769// TODO(jmadill): Fix Android support. http://anglebug.com/2830
770#if defined(ANGLE_PLATFORM_ANDROID)
771 mFeatures.basicGLLineRasterization = false;
772#else
Jamie Madill12222072018-07-11 14:59:48 -0400773 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400774#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400775
Luc Ferronf786b702018-07-10 11:01:43 -0400776 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
777 // investigation. http://anglebug.com/2728
778 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400779
780#ifdef ANGLE_PLATFORM_WINDOWS
781 // http://anglebug.com/2838
782 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
783#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400784
785 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
786 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -0500787
788 // Work around incorrect NVIDIA point size range clamping.
789 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
790 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
791 {
792 mFeatures.clampPointSize = true;
793 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +0100794
795#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -0500796 // Work around ineffective compute-graphics barriers on Nexus 5X.
797 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
798 // http://anglebug.com/3019
799 mFeatures.flushAfterVertexConversion =
800 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +0100801#endif
Jamie Madill12222072018-07-11 14:59:48 -0400802}
803
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400804void RendererVk::initPipelineCacheVkKey()
805{
806 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
807 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
808 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
809 // there is no '\0' in the result.
810 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
811 {
812 hashStream << std::hex << c;
813 }
814 // Add the vendor and device id too for good measure.
815 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
816 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
817
818 const std::string &hashString = hashStream.str();
819 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
820 hashString.length(), mPipelineCacheVkBlobKey.data());
821}
822
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500823angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400824{
825 initPipelineCacheVkKey();
826
827 egl::BlobCache::Value initialData;
828 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
829 mPipelineCacheVkBlobKey, &initialData);
830
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400831 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400832
833 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400834 pipelineCacheCreateInfo.flags = 0;
835 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
836 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
837
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500838 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -0500839 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400840}
841
Jamie Madillacccc6c2016-05-03 17:22:10 -0400842void RendererVk::ensureCapsInitialized() const
843{
844 if (!mCapsInitialized)
845 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400846 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
847 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
848 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400849 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400850 mCapsInitialized = true;
851 }
852}
853
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400854void RendererVk::getSubmitWaitSemaphores(
855 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400856 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
857 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400858{
859 if (mSubmitLastSignaledSemaphore.getSemaphore())
860 {
861 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400862 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400863
864 // Return the semaphore to the pool (which will remain valid and unused until the
865 // queue it's about to be waited on has finished execution).
866 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
867 }
868
869 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
870 {
871 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400872 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
873
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400874 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
875 }
876 mSubmitWaitSemaphores.clear();
877}
878
Jamie Madillacccc6c2016-05-03 17:22:10 -0400879const gl::Caps &RendererVk::getNativeCaps() const
880{
881 ensureCapsInitialized();
882 return mNativeCaps;
883}
884
885const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
886{
887 ensureCapsInitialized();
888 return mNativeTextureCaps;
889}
890
891const gl::Extensions &RendererVk::getNativeExtensions() const
892{
893 ensureCapsInitialized();
894 return mNativeExtensions;
895}
896
897const gl::Limitations &RendererVk::getNativeLimitations() const
898{
899 ensureCapsInitialized();
900 return mNativeLimitations;
901}
902
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400903uint32_t RendererVk::getMaxActiveTextures()
904{
905 // TODO(lucferron): expose this limitation to GL in Context Caps
906 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
907 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
908}
909
Jamie Madill49ac74b2017-12-21 14:42:33 -0500910const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500911{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500912 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500913}
914
Jamie Madill21061022018-07-12 23:56:30 -0400915angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500916{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500917 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500918 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400919 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
920
Luc Ferron1617e692018-07-11 11:08:19 -0400921 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
922 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400923
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400924 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400925 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
926 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400927
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400928 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500929 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400930 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
931 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400932 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500933 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400934 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500935 submitInfo.signalSemaphoreCount = 0;
936 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500937
Jamie Madill21061022018-07-12 23:56:30 -0400938 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500939 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500940
Jamie Madill4c26fc22017-02-24 11:04:10 -0500941 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400942 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400943 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400944
945 if (mGpuEventsEnabled)
946 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400947 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400948 while (mInFlightGpuEventQueries.size() > 0)
949 {
950 ANGLE_TRY(checkCompletedGpuEvents(context));
951 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400952 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
953 // synchronization if there is no event to be adjusted (happens when finish() gets called
954 // multiple times towards the end of the application).
955 if (mGpuEvents.size() > 0)
956 {
957 ANGLE_TRY(synchronizeCpuGpuTime(context));
958 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400959 }
960
Jamie Madill7c985f52018-11-29 18:16:17 -0500961 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500962}
963
Jamie Madill0c0dc342017-03-24 14:18:51 -0400964void RendererVk::freeAllInFlightResources()
965{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500966 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400967 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400968 // On device loss we need to wait for fence to be signaled before destroying it
969 if (mDeviceLost)
970 {
971 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
972 // If wait times out, it is probably not possible to recover from lost device
973 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
974 }
Jamie Madill49ac74b2017-12-21 14:42:33 -0500975 batch.fence.destroy(mDevice);
976 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400977 }
978 mInFlightCommands.clear();
979
980 for (auto &garbage : mGarbage)
981 {
Jamie Madille88ec8e2017-10-31 17:18:14 -0400982 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400983 }
984 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400985
986 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400987}
988
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -0400989angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500990{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500991 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -0500992
Jamie Madill49ac74b2017-12-21 14:42:33 -0500993 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500994 {
Yuly Novikov27780292018-11-09 11:19:49 -0500995 VkResult result = batch.fence.getStatus(mDevice);
996 if (result == VK_NOT_READY)
997 {
Jamie Madill0c0dc342017-03-24 14:18:51 -0400998 break;
Yuly Novikov27780292018-11-09 11:19:49 -0500999 }
1000 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001001
Jamie Madill49ac74b2017-12-21 14:42:33 -05001002 ASSERT(batch.serial > mLastCompletedQueueSerial);
1003 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001004
Jamie Madill49ac74b2017-12-21 14:42:33 -05001005 batch.fence.destroy(mDevice);
1006 batch.commandPool.destroy(mDevice);
1007 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001008 }
1009
Jamie Madill49ac74b2017-12-21 14:42:33 -05001010 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001011
1012 size_t freeIndex = 0;
1013 for (; freeIndex < mGarbage.size(); ++freeIndex)
1014 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001015 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001016 break;
1017 }
1018
1019 // Remove the entries from the garbage list - they should be ready to go.
1020 if (freeIndex > 0)
1021 {
1022 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001023 }
1024
Jamie Madill7c985f52018-11-29 18:16:17 -05001025 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001026}
1027
Jamie Madill21061022018-07-12 23:56:30 -04001028angle::Result RendererVk::submitFrame(vk::Context *context,
1029 const VkSubmitInfo &submitInfo,
1030 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001031{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001032 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001033 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001034 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1035 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001036
Jamie Madillbea35a62018-07-05 11:54:10 -04001037 vk::Scoped<CommandBatch> scopedBatch(mDevice);
1038 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001039 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001040
Jamie Madill21061022018-07-12 23:56:30 -04001041 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001042
1043 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001044 batch.commandPool = std::move(mCommandPool);
1045 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001046
Jamie Madillbea35a62018-07-05 11:54:10 -04001047 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001048
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001049 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1050 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001051 // so the limit is larger than the expected number of images. The
1052 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001053 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001054
1055 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001056 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001057 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillb980c562018-11-27 11:34:27 -05001058 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001059
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001060 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001061
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001062 if (mGpuEventsEnabled)
1063 {
1064 ANGLE_TRY(checkCompletedGpuEvents(context));
1065 }
1066
Jamie Madill49ac74b2017-12-21 14:42:33 -05001067 // Simply null out the command buffer here - it was allocated using the command pool.
1068 commandBuffer.releaseHandle();
1069
1070 // Reallocate the command pool for next frame.
1071 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001072 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001073 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001074 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001075 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001076
Yuly Novikov27780292018-11-09 11:19:49 -05001077 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001078 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001079}
1080
Jamie Madillaaca96e2018-06-12 10:19:48 -04001081bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001082{
1083 return serial > mLastCompletedQueueSerial;
1084}
1085
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001086angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1087{
1088 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1089 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001090 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001091 }
1092
1093 // Find the first batch with serial equal to or bigger than given serial (note that
1094 // the batch serials are unique, otherwise upper-bound would have been necessary).
1095 size_t batchIndex = mInFlightCommands.size() - 1;
1096 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1097 {
1098 if (mInFlightCommands[i].serial >= serial)
1099 {
1100 batchIndex = i;
1101 break;
1102 }
1103 }
1104 const CommandBatch &batch = mInFlightCommands[batchIndex];
1105
1106 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001107 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001108
1109 // Clean up finished batches.
1110 return checkCompletedCommands(context);
1111}
1112
Jamie Madill21061022018-07-12 23:56:30 -04001113angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1114 const vk::RenderPassDesc &desc,
1115 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001116{
Jamie Madill21061022018-07-12 23:56:30 -04001117 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001118 renderPassOut);
1119}
1120
Jamie Madill21061022018-07-12 23:56:30 -04001121angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1122 const vk::RenderPassDesc &desc,
1123 const vk::AttachmentOpsArray &ops,
1124 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001125{
Jamie Madill21061022018-07-12 23:56:30 -04001126 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001127 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001128}
1129
Jamie Madilla5e06072018-05-18 14:36:05 -04001130vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001131{
Jamie Madilla5e06072018-05-18 14:36:05 -04001132 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001133}
1134
Jamie Madill21061022018-07-12 23:56:30 -04001135angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001136{
Jamie Madill21061022018-07-12 23:56:30 -04001137 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001138 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001139}
1140
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001141angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001142{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001143 if (mCommandGraph.empty())
1144 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001145 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001146 }
1147
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001148 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1149
Jamie Madillbea35a62018-07-05 11:54:10 -04001150 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1151 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001152
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001153 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001154 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1155 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001156
1157 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1158 // will be waited on.
1159 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001160
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001161 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001162 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001163 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1164 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001165 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001166 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001167 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001168 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001169 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001170
Jamie Madill21061022018-07-12 23:56:30 -04001171 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001172
Jamie Madill7c985f52018-11-29 18:16:17 -05001173 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001174}
1175
Jamie Madill78feddc2018-04-27 11:45:05 -04001176Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001177{
Jamie Madill78feddc2018-04-27 11:45:05 -04001178 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001179}
1180
Jamie Madill21061022018-07-12 23:56:30 -04001181angle::Result RendererVk::getDescriptorSetLayout(
1182 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001183 const vk::DescriptorSetLayoutDesc &desc,
1184 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1185{
Jamie Madill21061022018-07-12 23:56:30 -04001186 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001187}
1188
Jamie Madill21061022018-07-12 23:56:30 -04001189angle::Result RendererVk::getPipelineLayout(
1190 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001191 const vk::PipelineLayoutDesc &desc,
1192 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1193 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1194{
Jamie Madill21061022018-07-12 23:56:30 -04001195 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001196 pipelineLayoutOut);
1197}
1198
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001199angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1200{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001201 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001202
1203 if (--mPipelineCacheVkUpdateTimeout > 0)
1204 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001205 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001206 }
1207
1208 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1209
1210 // Get the size of the cache.
1211 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001212 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001213 if (result != VK_INCOMPLETE)
1214 {
1215 ANGLE_VK_TRY(displayVk, result);
1216 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001217
1218 angle::MemoryBuffer *pipelineCacheData = nullptr;
1219 ANGLE_VK_CHECK_ALLOC(displayVk,
1220 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1221
1222 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001223 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001224 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1225 // was determined just above), so receiving it hints at an implementation bug we would want
1226 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001227 ASSERT(result != VK_INCOMPLETE);
1228 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001229
1230 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1231 // the buffer to avoid leaking garbage memory.
1232 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1233 if (pipelineCacheSize < originalPipelineCacheSize)
1234 {
1235 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1236 originalPipelineCacheSize - pipelineCacheSize);
1237 }
1238
1239 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1240
Jamie Madill7c985f52018-11-29 18:16:17 -05001241 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001242}
1243
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001244angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1245 const vk::Semaphore **outSemaphore)
1246{
1247 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1248
1249 vk::SemaphoreHelper semaphore;
1250 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1251
1252 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1253 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1254
Jamie Madill7c985f52018-11-29 18:16:17 -05001255 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001256}
1257
1258const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1259{
1260 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1261
1262 // Return the semaphore to the pool (which will remain valid and unused until the
1263 // queue it's about to be waited on has finished execution). The caller is about
1264 // to wait on it.
1265 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1266
1267 return semaphore;
1268}
1269
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001270angle::Result RendererVk::getFullScreenClearShaderProgram(vk::Context *context,
1271 vk::ShaderProgramHelper **programOut)
Jamie Madilld47044a2018-04-27 11:45:03 -04001272{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001273 if (!mFullScreenClearShaderProgram.valid())
1274 {
1275 vk::RefCounted<vk::ShaderAndSerial> *fullScreenQuad = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001276 ANGLE_TRY(mShaderLibrary.getFullScreenQuad_vert(context, 0, &fullScreenQuad));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001277
1278 vk::RefCounted<vk::ShaderAndSerial> *pushConstantColor = nullptr;
Shahbaz Youssefia1442ec2018-11-26 12:48:10 -05001279 ANGLE_TRY(mShaderLibrary.getPushConstantColor_frag(context, 0, &pushConstantColor));
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001280
1281 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Vertex, fullScreenQuad);
1282 mFullScreenClearShaderProgram.setShader(gl::ShaderType::Fragment, pushConstantColor);
1283 }
1284
1285 *programOut = &mFullScreenClearShaderProgram;
Jamie Madill7c985f52018-11-29 18:16:17 -05001286 return angle::Result::Continue;
Jamie Madilld47044a2018-04-27 11:45:03 -04001287}
Luc Ferron90968362018-05-04 08:47:22 -04001288
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001289angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1290{
1291 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1292 // that seems impossible, so instead, we are going to make a small submission with just a
1293 // timestamp query. First, the disjoint timer query extension says:
1294 //
1295 // > This will return the GL time after all previous commands have reached the GL server but
1296 // have not yet necessarily executed.
1297 //
1298 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1299 // The wording allows us to make a submission to get the timestamp without performing a flush.
1300 //
1301 // Second:
1302 //
1303 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1304 // object target, applications can measure the latency between when commands reach the GL server
1305 // and when they are realized in the framebuffer.
1306 //
1307 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1308 // GPU bubble. This function directly generates a command buffer and submits it instead of
1309 // using the other member functions. This is to avoid changing any state, such as the queue
1310 // serial.
1311
1312 // Create a query used to receive the GPU timestamp
1313 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1314 vk::QueryHelper timestampQuery;
1315 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1316 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1317
1318 // Record the command buffer
1319 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1320 vk::CommandBuffer &commandBuffer = commandBatch.get();
1321
1322 VkCommandBufferAllocateInfo commandBufferInfo = {};
1323 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1324 commandBufferInfo.commandPool = mCommandPool.getHandle();
1325 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1326 commandBufferInfo.commandBufferCount = 1;
1327
Yuly Novikov27780292018-11-09 11:19:49 -05001328 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001329
1330 VkCommandBufferBeginInfo beginInfo = {};
1331 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1332 beginInfo.flags = 0;
1333 beginInfo.pInheritanceInfo = nullptr;
1334
Yuly Novikov27780292018-11-09 11:19:49 -05001335 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001336
1337 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1338 timestampQuery.getQuery(), 1);
1339 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1340 timestampQuery.getQueryPool()->getHandle(),
1341 timestampQuery.getQuery());
1342
Yuly Novikov27780292018-11-09 11:19:49 -05001343 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001344
1345 // Create fence for the submission
1346 VkFenceCreateInfo fenceInfo = {};
1347 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1348 fenceInfo.flags = 0;
1349
1350 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001351 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001352
1353 // Submit the command buffer
1354 VkSubmitInfo submitInfo = {};
1355 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1356 submitInfo.waitSemaphoreCount = 0;
1357 submitInfo.pWaitSemaphores = nullptr;
1358 submitInfo.pWaitDstStageMask = nullptr;
1359 submitInfo.commandBufferCount = 1;
1360 submitInfo.pCommandBuffers = commandBuffer.ptr();
1361 submitInfo.signalSemaphoreCount = 0;
1362 submitInfo.pSignalSemaphores = nullptr;
1363
1364 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1365
1366 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1367 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001368 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001369
1370 // Get the query results
1371 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1372
Yuly Novikov27780292018-11-09 11:19:49 -05001373 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1374 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1375 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001376
1377 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1378
Jamie Madill7c985f52018-11-29 18:16:17 -05001379 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001380}
1381
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001382// These functions look at the mandatory format for support, and fallback to querying the device (if
1383// necessary) to test the availability of the bits.
1384bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1385 const VkFormatFeatureFlags featureBits)
1386{
1387 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1388}
1389
1390bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1391 const VkFormatFeatureFlags featureBits)
1392{
1393 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1394}
1395
1396bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1397{
1398 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1399}
1400
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001401angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1402{
1403 ASSERT(mGpuEventsEnabled);
1404
1405 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1406 ASSERT(platform);
1407
1408 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1409 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1410 //
1411 // CPU GPU
1412 //
1413 // Record command buffer
1414 // with timestamp query
1415 //
1416 // Submit command buffer
1417 //
1418 // Post-submission work Begin execution
1419 //
1420 // ???? Write timstamp Tgpu
1421 //
1422 // ???? End execution
1423 //
1424 // ???? Return query results
1425 //
1426 // ????
1427 //
1428 // Get query results
1429 //
1430 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1431 // finished post-submission work while the GPU is executing in parallel. With no further work,
1432 // querying CPU timestamps before submission and after getting query results give the bounds to
1433 // Tgpu, which could be quite large.
1434 //
1435 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1436 // reduce this range. This function implements the following procedure:
1437 //
1438 // CPU GPU
1439 //
1440 // Record command buffer
1441 // with timestamp query
1442 //
1443 // Submit command buffer
1444 //
1445 // Post-submission work Begin execution
1446 //
1447 // ???? Set Event GPUReady
1448 //
1449 // Wait on Event GPUReady Wait on Event CPUReady
1450 //
1451 // Get CPU Time Ts Wait on Event CPUReady
1452 //
1453 // Set Event CPUReady Wait on Event CPUReady
1454 //
1455 // Get CPU Time Tcpu Get GPU Time Tgpu
1456 //
1457 // Wait on Event GPUDone Set Event GPUDone
1458 //
1459 // Get CPU Time Te End Execution
1460 //
1461 // Idle Return query results
1462 //
1463 // Get query results
1464 //
1465 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1466 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1467 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1468 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1469 // calibration.
1470 //
1471 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1472
1473 // Make sure nothing is running
1474 ASSERT(mCommandGraph.empty());
1475
1476 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1477
1478 // Create a query used to receive the GPU timestamp
1479 vk::QueryHelper timestampQuery;
1480 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1481
1482 // Create the three events
1483 VkEventCreateInfo eventCreateInfo = {};
1484 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1485 eventCreateInfo.flags = 0;
1486
1487 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001488 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1489 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1490 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001491
1492 constexpr uint32_t kRetries = 10;
1493
1494 // Time suffixes used are S for seconds and Cycles for cycles
1495 double tightestRangeS = 1e6f;
1496 double TcpuS = 0;
1497 uint64_t TgpuCycles = 0;
1498 for (uint32_t i = 0; i < kRetries; ++i)
1499 {
1500 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001501 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1502 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1503 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001504
1505 // Record the command buffer
1506 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1507 vk::CommandBuffer &commandBuffer = commandBatch.get();
1508
1509 VkCommandBufferAllocateInfo commandBufferInfo = {};
1510 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1511 commandBufferInfo.commandPool = mCommandPool.getHandle();
1512 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1513 commandBufferInfo.commandBufferCount = 1;
1514
Yuly Novikov27780292018-11-09 11:19:49 -05001515 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001516
1517 VkCommandBufferBeginInfo beginInfo = {};
1518 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1519 beginInfo.flags = 0;
1520 beginInfo.pInheritanceInfo = nullptr;
1521
Yuly Novikov27780292018-11-09 11:19:49 -05001522 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001523
1524 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1525 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1526 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1527 nullptr);
1528
1529 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1530 timestampQuery.getQuery(), 1);
1531 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1532 timestampQuery.getQueryPool()->getHandle(),
1533 timestampQuery.getQuery());
1534
1535 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1536
Yuly Novikov27780292018-11-09 11:19:49 -05001537 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001538
1539 // Submit the command buffer
1540 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1541 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1542 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1543
1544 VkSubmitInfo submitInfo = {};
1545 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1546 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1547 submitInfo.pWaitSemaphores = waitSemaphores.data();
1548 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1549 submitInfo.commandBufferCount = 1;
1550 submitInfo.pCommandBuffers = commandBuffer.ptr();
1551 submitInfo.signalSemaphoreCount = 0;
1552 submitInfo.pSignalSemaphores = nullptr;
1553
1554 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1555
1556 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001557 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001558 do
1559 {
Yuly Novikov27780292018-11-09 11:19:49 -05001560 result = gpuReady.get().getStatus(mDevice);
1561 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1562 {
1563 ANGLE_VK_TRY(context, result);
1564 }
1565 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001566
1567 double TsS = platform->monotonicallyIncreasingTime(platform);
1568
1569 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001570 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001571 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1572
1573 // Wait for GPU to be done. Another short busy wait.
1574 do
1575 {
Yuly Novikov27780292018-11-09 11:19:49 -05001576 result = gpuDone.get().getStatus(mDevice);
1577 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1578 {
1579 ANGLE_VK_TRY(context, result);
1580 }
1581 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001582
1583 double TeS = platform->monotonicallyIncreasingTime(platform);
1584
1585 // Get the query results
1586 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1587
1588 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1589
1590 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001591 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1592 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1593 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001594
1595 // Use the first timestamp queried as origin.
1596 if (mGpuEventTimestampOrigin == 0)
1597 {
1598 mGpuEventTimestampOrigin = gpuTimestampCycles;
1599 }
1600
1601 // Take these CPU and GPU timestamps if there is better confidence.
1602 double confidenceRangeS = TeS - TsS;
1603 if (confidenceRangeS < tightestRangeS)
1604 {
1605 tightestRangeS = confidenceRangeS;
1606 TcpuS = cpuTimestampS;
1607 TgpuCycles = gpuTimestampCycles;
1608 }
1609 }
1610
1611 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1612
1613 // timestampPeriod gives nanoseconds/cycle.
1614 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1615 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1616 1'000'000'000.0;
1617
1618 flushGpuEvents(TgpuS, TcpuS);
1619
1620 mGpuClockSync.gpuTimestampS = TgpuS;
1621 mGpuClockSync.cpuTimestampS = TcpuS;
1622
Jamie Madill7c985f52018-11-29 18:16:17 -05001623 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001624}
1625
1626angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1627 vk::CommandBuffer *commandBuffer,
1628 char phase,
1629 const char *name)
1630{
1631 ASSERT(mGpuEventsEnabled);
1632
1633 GpuEventQuery event;
1634
1635 event.name = name;
1636 event.phase = phase;
1637 event.serial = mCurrentQueueSerial;
1638
1639 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1640
1641 commandBuffer->resetQueryPool(
1642 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1643 commandBuffer->writeTimestamp(
1644 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1645 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1646
1647 mInFlightGpuEventQueries.push_back(std::move(event));
1648
Jamie Madill7c985f52018-11-29 18:16:17 -05001649 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001650}
1651
1652angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1653{
1654 ASSERT(mGpuEventsEnabled);
1655
1656 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1657 ASSERT(platform);
1658
1659 int finishedCount = 0;
1660
1661 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1662 {
1663 // Only check the timestamp query if the submission has finished.
1664 if (eventQuery.serial > mLastCompletedQueueSerial)
1665 {
1666 break;
1667 }
1668
1669 // See if the results are available.
1670 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001671 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1672 ->getResults(mDevice, eventQuery.queryIndex, 1,
1673 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1674 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1675 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001676 {
1677 break;
1678 }
Yuly Novikov27780292018-11-09 11:19:49 -05001679 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001680
1681 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1682
1683 GpuEvent event;
1684 event.gpuTimestampCycles = gpuTimestampCycles;
1685 event.name = eventQuery.name;
1686 event.phase = eventQuery.phase;
1687
1688 mGpuEvents.emplace_back(event);
1689
1690 ++finishedCount;
1691 }
1692
1693 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1694 mInFlightGpuEventQueries.begin() + finishedCount);
1695
Jamie Madill7c985f52018-11-29 18:16:17 -05001696 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001697}
1698
1699void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1700{
1701 if (mGpuEvents.size() == 0)
1702 {
1703 return;
1704 }
1705
1706 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1707 ASSERT(platform);
1708
1709 // Find the slope of the clock drift for adjustment
1710 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1711 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1712 double gpuSyncDriftSlope = 0;
1713
1714 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1715 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1716
1717 // No gpu trace events should have been generated before the clock sync, so if there is no
1718 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1719 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1720 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1721
1722 gpuSyncDriftSlope =
1723 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1724
1725 for (const GpuEvent &event : mGpuEvents)
1726 {
1727 double gpuTimestampS =
1728 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1729 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1730
1731 // Account for clock drift.
1732 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1733
1734 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1735 // for.
1736 static long long eventId = 1;
1737 static const unsigned char *categoryEnabled =
1738 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1739 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1740 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1741 }
1742
1743 mGpuEvents.clear();
1744}
1745
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001746template <VkFormatFeatureFlags VkFormatProperties::*features>
1747bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1748{
1749 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
1750 VkFormatProperties &deviceProperties = mFormatProperties[format];
1751
1752 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
1753 {
1754 // If we don't have the actual device features, see if the requested features are mandatory.
1755 // If so, there's no need to query the device.
1756 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
1757 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
1758 {
1759 return true;
1760 }
1761
1762 // Otherwise query the format features and cache it.
1763 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
1764 }
1765
1766 return IsMaskFlagSet(deviceProperties.*features, featureBits);
1767}
1768
Jamie Madillaaca96e2018-06-12 10:19:48 -04001769uint32_t GetUniformBufferDescriptorCount()
1770{
1771 return kUniformBufferDescriptorsPerDescriptorSet;
1772}
1773
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001774} // namespace rx