blob: 47b01e53dff2422569e0c28fd31951dbb38a7d89 [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"
Jamie Madill4d0bf552016-12-28 15:45:24 -050019#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050020#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050021#include "libANGLE/renderer/vulkan/CompilerVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040022#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050023#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050024#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050025#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050026#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050027#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050028#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050029#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040030
Shahbaz Youssefi61656022018-10-24 15:00:50 -040031#include "third_party/trace_event/trace_event.h"
32
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070033// Consts
34namespace
35{
36const uint32_t kMockVendorID = 0xba5eba11;
37const uint32_t kMockDeviceID = 0xf005ba11;
38constexpr char kMockDeviceName[] = "Vulkan Mock Device";
Shahbaz Youssefi61656022018-10-24 15:00:50 -040039constexpr size_t kInFlightCommandsLimit = 100u;
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070040} // anonymous namespace
41
Jamie Madill9e54b5a2016-05-25 12:57:39 -040042namespace rx
43{
44
Jamie Madille09bd5d2016-11-29 16:20:35 -050045namespace
46{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040047// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
48// one for the vertex shader.
49constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040050// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
51static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Jamie Madille09bd5d2016-11-29 16:20:35 -050052
Omar El Sheikh26c61b22018-06-29 12:50:59 -060053bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
54{
55#if !defined(ANGLE_PLATFORM_ANDROID)
56 // Mock ICD does not currently run on Android
57 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
58 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
59 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
60#else
61 return false;
62#endif // !defined(ANGLE_PLATFORM_ANDROID)
63}
64
Jamie Madille09bd5d2016-11-29 16:20:35 -050065VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
66 const std::vector<const char *> &enabledExtensionNames)
67{
68 // Compile the extensions names into a set.
69 std::set<std::string> extensionNames;
70 for (const auto &extensionProp : extensionProps)
71 {
72 extensionNames.insert(extensionProp.extensionName);
73 }
74
Jamie Madillacf2f3a2017-11-21 19:22:44 -050075 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050076 {
77 if (extensionNames.count(extensionName) == 0)
78 {
79 return VK_ERROR_EXTENSION_NOT_PRESENT;
80 }
81 }
82
83 return VK_SUCCESS;
84}
85
Tobin Ehlis3a181e32018-08-29 15:17:05 -060086// Array of Validation error/warning messages that will be ignored, should include bugID
87constexpr std::array<const char *, 1> kSkippedMessages = {
88 // http://anglebug.com/2796
89 " [ UNASSIGNED-CoreValidation-Shader-PointSizeMissing ] Object: VK_NULL_HANDLE (Type = 19) "
90 "| Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader "
91 "corresponding to VK_SHADER_STAGE_VERTEX_BIT."};
92
93// Suppress validation errors that are known
94// return "true" if given code/prefix/message is known, else return "false"
95bool IsIgnoredDebugMessage(const char *message)
96{
97 for (const auto &msg : kSkippedMessages)
98 {
99 if (strcmp(msg, message) == 0)
100 {
101 return true;
102 }
103 }
104 return false;
105}
106
Yuly Novikov199f4292018-01-19 19:04:05 -0500107VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
108 VkDebugReportObjectTypeEXT objectType,
109 uint64_t object,
110 size_t location,
111 int32_t messageCode,
112 const char *layerPrefix,
113 const char *message,
114 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500115{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600116 if (IsIgnoredDebugMessage(message))
117 {
118 return VK_FALSE;
119 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500120 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
121 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500122 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500123#if !defined(NDEBUG)
124 // Abort the call in Debug builds.
125 return VK_TRUE;
126#endif
127 }
128 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
129 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500130 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500131 }
132 else
133 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500134 // Uncomment this if you want Vulkan spam.
135 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500136 }
137
138 return VK_FALSE;
139}
140
Yuly Novikov199f4292018-01-19 19:04:05 -0500141// If we're loading the validation layers, we could be running from any random directory.
142// Change to the executable directory so we can find the layers, then change back to the
143// previous directory to be safe we don't disrupt the application.
144class ScopedVkLoaderEnvironment : angle::NonCopyable
145{
146 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600147 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
148 : mEnableValidationLayers(enableValidationLayers),
149 mEnableMockICD(enableMockICD),
150 mChangedCWD(false),
151 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500152 {
153// Changing CWD and setting environment variables makes no sense on Android,
154// since this code is a part of Java application there.
155// Android Vulkan loader doesn't need this either.
156#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600157 if (enableMockICD)
158 {
159 // Override environment variable to use built Mock ICD
160 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
161 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
162 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
163 if (!mChangedICDPath)
164 {
165 ERR() << "Error setting Path for Mock/Null Driver.";
166 mEnableMockICD = false;
167 }
168 }
Jamie Madill46848422018-08-09 10:46:06 -0400169 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500170 {
171 const auto &cwd = angle::GetCWD();
172 if (!cwd.valid())
173 {
174 ERR() << "Error getting CWD for Vulkan layers init.";
175 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400176 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500177 }
178 else
179 {
180 mPreviousCWD = cwd.value();
181 const char *exeDir = angle::GetExecutableDirectory();
182 mChangedCWD = angle::SetCWD(exeDir);
183 if (!mChangedCWD)
184 {
185 ERR() << "Error setting CWD for Vulkan layers init.";
186 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400187 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500188 }
189 }
190 }
191
192 // Override environment variable to use the ANGLE layers.
193 if (mEnableValidationLayers)
194 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700195 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500196 {
197 ERR() << "Error setting environment for Vulkan layers init.";
198 mEnableValidationLayers = false;
199 }
200 }
201#endif // !defined(ANGLE_PLATFORM_ANDROID)
202 }
203
204 ~ScopedVkLoaderEnvironment()
205 {
206 if (mChangedCWD)
207 {
208#if !defined(ANGLE_PLATFORM_ANDROID)
209 ASSERT(mPreviousCWD.valid());
210 angle::SetCWD(mPreviousCWD.value().c_str());
211#endif // !defined(ANGLE_PLATFORM_ANDROID)
212 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600213 if (mChangedICDPath)
214 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600215 if (mPreviousICDPath.value().empty())
216 {
217 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
218 }
219 else
220 {
221 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
222 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600223 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500224 }
225
Jamie Madillaaca96e2018-06-12 10:19:48 -0400226 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500227
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600228 bool canEnableMockICD() const { return mEnableMockICD; }
229
Yuly Novikov199f4292018-01-19 19:04:05 -0500230 private:
231 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600232 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500233 bool mChangedCWD;
234 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600235 bool mChangedICDPath;
236 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500237};
238
Jamie Madill21061022018-07-12 23:56:30 -0400239void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
240 bool preferMockICD,
241 VkPhysicalDevice *physicalDeviceOut,
242 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
243{
244 ASSERT(!physicalDevices.empty());
245 if (preferMockICD)
246 {
247 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
248 {
249 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
250 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
251 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
252 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
253 {
254 *physicalDeviceOut = physicalDevice;
255 return;
256 }
257 }
258 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
259 "physicalDevice instead.";
260 }
261
262 // Fall back to first device.
263 *physicalDeviceOut = physicalDevices[0];
264 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
265}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400266
267// Initially dumping the command graphs is disabled.
268constexpr bool kEnableCommandGraphDiagnostics = false;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500269} // anonymous namespace
270
Jamie Madill49ac74b2017-12-21 14:42:33 -0500271// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400272RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500273
Jamie Madillaaca96e2018-06-12 10:19:48 -0400274RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500275
276RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
277 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
278{
279}
280
281RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
282{
283 std::swap(commandPool, other.commandPool);
284 std::swap(fence, other.fence);
285 std::swap(serial, other.serial);
286 return *this;
287}
288
Jamie Madillbea35a62018-07-05 11:54:10 -0400289void RendererVk::CommandBatch::destroy(VkDevice device)
290{
291 commandPool.destroy(device);
292 fence.destroy(device);
293}
294
Jamie Madill9f2a8612017-11-30 12:43:09 -0500295// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500296RendererVk::RendererVk()
297 : mCapsInitialized(false),
298 mInstance(VK_NULL_HANDLE),
299 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400300 mEnableMockICD(false),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500301 mDebugReportCallback(VK_NULL_HANDLE),
302 mPhysicalDevice(VK_NULL_HANDLE),
303 mQueue(VK_NULL_HANDLE),
304 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
305 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400306 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400307 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400308 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400309 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400310 mCommandGraph(kEnableCommandGraphDiagnostics),
311 mGpuEventsEnabled(false),
312 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
313 mGpuEventTimestampOrigin(0)
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400314{
315}
316
317RendererVk::~RendererVk()
318{
Jamie Madill21061022018-07-12 23:56:30 -0400319}
320
321void RendererVk::onDestroy(vk::Context *context)
322{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500323 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500324 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500325 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400326 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500327 }
328
Jamie Madillc7918ce2018-06-13 13:25:31 -0400329 mPipelineLayoutCache.destroy(mDevice);
330 mDescriptorSetLayoutCache.destroy(mDevice);
331
Jamie Madill9f2a8612017-11-30 12:43:09 -0500332 mRenderPassCache.destroy(mDevice);
Jamie Madillffa4cbb2018-01-23 13:04:07 -0500333 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400334 mPipelineCacheVk.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400335 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400336 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400337 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500338
Jamie Madill06ca6342018-07-12 15:56:53 -0400339 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500340
Jamie Madill5deea722017-02-16 10:44:46 -0500341 if (mCommandPool.valid())
342 {
343 mCommandPool.destroy(mDevice);
344 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500345
346 if (mDevice)
347 {
348 vkDestroyDevice(mDevice, nullptr);
349 mDevice = VK_NULL_HANDLE;
350 }
351
Jamie Madill0448ec82016-12-23 13:41:47 -0500352 if (mDebugReportCallback)
353 {
354 ASSERT(mInstance);
355 auto destroyDebugReportCallback = reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>(
356 vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT"));
357 ASSERT(destroyDebugReportCallback);
358 destroyDebugReportCallback(mInstance, mDebugReportCallback, nullptr);
359 }
360
Jamie Madill4d0bf552016-12-28 15:45:24 -0500361 if (mInstance)
362 {
363 vkDestroyInstance(mInstance, nullptr);
364 mInstance = VK_NULL_HANDLE;
365 }
366
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600367 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500368 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500369}
370
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400371void RendererVk::markDeviceLost()
372{
373 mDeviceLost = true;
374}
375
376bool RendererVk::isDeviceLost() const
377{
378 return mDeviceLost;
379}
380
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400381angle::Result RendererVk::initialize(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400382 const egl::AttributeMap &attribs,
383 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500384{
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600385 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
386 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500387 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400388 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500389
Jamie Madill0448ec82016-12-23 13:41:47 -0500390 // Gather global layer properties.
391 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400392 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500393
394 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
395 if (instanceLayerCount > 0)
396 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400397 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
398 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500399 }
400
Jamie Madille09bd5d2016-11-29 16:20:35 -0500401 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400402 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400403 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500404
405 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
406 if (instanceExtensionCount > 0)
407 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400408 ANGLE_VK_TRY(displayVk,
409 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
410 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500411 }
412
Yuly Novikov199f4292018-01-19 19:04:05 -0500413 const char *const *enabledLayerNames = nullptr;
414 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500415 if (mEnableValidationLayers)
416 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500417 bool layersRequested =
418 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
419 mEnableValidationLayers = GetAvailableValidationLayers(
420 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500421 }
422
Jamie Madille09bd5d2016-11-29 16:20:35 -0500423 std::vector<const char *> enabledInstanceExtensions;
424 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500425 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500426
Jamie Madill0448ec82016-12-23 13:41:47 -0500427 // TODO(jmadill): Should be able to continue initialization if debug report ext missing.
428 if (mEnableValidationLayers)
429 {
430 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
431 }
432
Jamie Madille09bd5d2016-11-29 16:20:35 -0500433 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400434 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400435 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500436
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400437 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500438 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500439 applicationInfo.pApplicationName = "ANGLE";
440 applicationInfo.applicationVersion = 1;
441 applicationInfo.pEngineName = "ANGLE";
442 applicationInfo.engineVersion = 1;
443 applicationInfo.apiVersion = VK_API_VERSION_1_0;
444
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400445 VkInstanceCreateInfo instanceInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500446 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500447 instanceInfo.flags = 0;
448 instanceInfo.pApplicationInfo = &applicationInfo;
449
Jamie Madille09bd5d2016-11-29 16:20:35 -0500450 // Enable requested layers and extensions.
451 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
452 instanceInfo.ppEnabledExtensionNames =
453 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500454 instanceInfo.enabledLayerCount = enabledLayerCount;
455 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500456
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400457 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500458
Jamie Madill0448ec82016-12-23 13:41:47 -0500459 if (mEnableValidationLayers)
460 {
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400461 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500462
463 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500464 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
465 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT |
466 VK_DEBUG_REPORT_INFORMATION_BIT_EXT | VK_DEBUG_REPORT_DEBUG_BIT_EXT;
467 debugReportInfo.pfnCallback = &DebugReportCallback;
468 debugReportInfo.pUserData = this;
469
470 auto createDebugReportCallback = reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>(
471 vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT"));
472 ASSERT(createDebugReportCallback);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400473 ANGLE_VK_TRY(displayVk, createDebugReportCallback(mInstance, &debugReportInfo, nullptr,
474 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500475 }
476
Jamie Madill4d0bf552016-12-28 15:45:24 -0500477 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400478 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
479 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500480
481 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700482 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400483 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
484 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400485 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700486 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500487
Jamie Madill30b5d842018-08-31 17:19:12 -0400488 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
489
Jamie Madill4d0bf552016-12-28 15:45:24 -0500490 // Ensure we can find a graphics queue family.
491 uint32_t queueCount = 0;
492 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
493
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400494 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500495
496 mQueueFamilyProperties.resize(queueCount);
497 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
498 mQueueFamilyProperties.data());
499
500 size_t graphicsQueueFamilyCount = false;
501 uint32_t firstGraphicsQueueFamily = 0;
502 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
503 {
504 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
505 if ((queueInfo.queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0)
506 {
507 ASSERT(queueInfo.queueCount > 0);
508 graphicsQueueFamilyCount++;
509 if (firstGraphicsQueueFamily == 0)
510 {
511 firstGraphicsQueueFamily = familyIndex;
512 }
513 break;
514 }
515 }
516
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400517 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500518
Jamie Madill12222072018-07-11 14:59:48 -0400519 initFeatures();
520
Jamie Madill4d0bf552016-12-28 15:45:24 -0500521 // If only one queue family, go ahead and initialize the device. If there is more than one
522 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
523 if (graphicsQueueFamilyCount == 1)
524 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400525 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500526 }
527
Jamie Madill035fd6b2017-10-03 15:43:22 -0400528 // Store the physical device memory properties so we can find the right memory pools.
529 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500530
Jamie Madill06ca6342018-07-12 15:56:53 -0400531 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500532
Jamie Madill6a89d222017-11-02 11:59:51 -0400533 // Initialize the format table.
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400534 mFormatTable.initialize(mPhysicalDevice, mFeatures, &mNativeTextureCaps,
Luc Ferrond50537a2018-02-07 17:02:08 -0500535 &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400536
Jamie Madill21061022018-07-12 23:56:30 -0400537 return angle::Result::Continue();
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400538}
539
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400540angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500541{
542 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400543 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400544 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500545
546 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
547 if (deviceLayerCount > 0)
548 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400549 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
550 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500551 }
552
553 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400554 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
555 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500556
557 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
558 if (deviceExtensionCount > 0)
559 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400560 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
561 &deviceExtensionCount,
562 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500563 }
564
Yuly Novikov199f4292018-01-19 19:04:05 -0500565 const char *const *enabledLayerNames = nullptr;
566 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 if (mEnableValidationLayers)
568 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500569 mEnableValidationLayers = GetAvailableValidationLayers(
570 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500571 }
572
573 std::vector<const char *> enabledDeviceExtensions;
574 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
575
Luc Ferronbf6dc372018-06-28 15:24:19 -0400576 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
577 if (getFeatures().flipViewportY)
578 {
579 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
580 }
581
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400582 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500583
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400584 // Select additional features to be enabled
585 VkPhysicalDeviceFeatures enabledFeatures = {};
586 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
587
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400588 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500589
590 float zeroPriority = 0.0f;
591
592 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500593 queueCreateInfo.flags = 0;
594 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
595 queueCreateInfo.queueCount = 1;
596 queueCreateInfo.pQueuePriorities = &zeroPriority;
597
598 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400599 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500600
Jamie Madill50cf2be2018-06-15 09:46:57 -0400601 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400602 createInfo.flags = 0;
603 createInfo.queueCreateInfoCount = 1;
604 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500605 createInfo.enabledLayerCount = enabledLayerCount;
606 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500607 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
608 createInfo.ppEnabledExtensionNames =
609 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400610 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500611
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400612 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500613
614 mCurrentQueueFamilyIndex = queueFamilyIndex;
615
616 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
617
618 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400619 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500620 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500621 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500622 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
623
Yuly Novikov27780292018-11-09 11:19:49 -0500624 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400625
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400626 // Initialize the vulkan pipeline cache.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400627 ANGLE_TRY(initPipelineCacheVk(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500628
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400629 // Initialize the submission semaphore pool.
630 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
631
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400632#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
633 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
634 ASSERT(platform);
635
636 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
637 // platform discovery.
638 const unsigned char *gpuEventsEnabled =
639 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
640 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
641#endif
642
643 if (mGpuEventsEnabled)
644 {
645 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
646 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
647 vk::kDefaultTimestampQueryPoolSize));
648 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
649 }
650
Jamie Madill21061022018-07-12 23:56:30 -0400651 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500652}
653
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400654angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400655 VkSurfaceKHR surface,
656 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500657{
658 // We've already initialized a device, and can't re-create it unless it's never been used.
659 // TODO(jmadill): Handle the re-creation case if necessary.
660 if (mDevice != VK_NULL_HANDLE)
661 {
662 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
663
664 // Check if the current device supports present on this surface.
665 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400666 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400667 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500668 surface, &supportsPresent));
669
Jamie Madill6cad7732018-07-11 09:01:17 -0400670 if (supportsPresent == VK_TRUE)
671 {
672 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill21061022018-07-12 23:56:30 -0400673 return angle::Result::Continue();
Jamie Madill6cad7732018-07-11 09:01:17 -0400674 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500675 }
676
677 // Find a graphics and present queue.
678 Optional<uint32_t> newPresentQueue;
679 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
680 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
681 {
682 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
683 if ((queueInfo.queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0)
684 {
685 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400686 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
687 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500688
689 if (supportsPresent == VK_TRUE)
690 {
691 newPresentQueue = queueIndex;
692 break;
693 }
694 }
695 }
696
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400697 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
698 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500699
Jamie Madill6cad7732018-07-11 09:01:17 -0400700 *presentQueueOut = newPresentQueue.value();
Jamie Madill21061022018-07-12 23:56:30 -0400701 return angle::Result::Continue();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500702}
703
704std::string RendererVk::getVendorString() const
705{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300706 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500707}
708
Jamie Madille09bd5d2016-11-29 16:20:35 -0500709std::string RendererVk::getRendererDescription() const
710{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500711 std::stringstream strstr;
712
713 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
714
715 strstr << "Vulkan ";
716 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
717 strstr << VK_VERSION_MINOR(apiVersion) << ".";
718 strstr << VK_VERSION_PATCH(apiVersion);
719
Olli Etuahoc6a06182018-04-13 14:11:46 +0300720 strstr << "(";
721
722 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
723 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
724 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
725 // driver detection.
726 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
727 {
728 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
729 }
730
731 strstr << mPhysicalDeviceProperties.deviceName << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500732
733 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -0500734}
735
Jamie Madill12222072018-07-11 14:59:48 -0400736void RendererVk::initFeatures()
737{
Jamie Madillb36a4812018-09-25 10:15:11 -0400738// Use OpenGL line rasterization rules by default.
739// TODO(jmadill): Fix Android support. http://anglebug.com/2830
740#if defined(ANGLE_PLATFORM_ANDROID)
741 mFeatures.basicGLLineRasterization = false;
742#else
Jamie Madill12222072018-07-11 14:59:48 -0400743 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400744#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400745
Luc Ferronf786b702018-07-10 11:01:43 -0400746 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
747 // investigation. http://anglebug.com/2728
748 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400749
750#ifdef ANGLE_PLATFORM_WINDOWS
751 // http://anglebug.com/2838
752 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
753#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400754
755 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
756 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madill12222072018-07-11 14:59:48 -0400757}
758
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400759void RendererVk::initPipelineCacheVkKey()
760{
761 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
762 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
763 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
764 // there is no '\0' in the result.
765 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
766 {
767 hashStream << std::hex << c;
768 }
769 // Add the vendor and device id too for good measure.
770 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
771 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
772
773 const std::string &hashString = hashStream.str();
774 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
775 hashString.length(), mPipelineCacheVkBlobKey.data());
776}
777
778angle::Result RendererVk::initPipelineCacheVk(DisplayVk *display)
779{
780 initPipelineCacheVkKey();
781
782 egl::BlobCache::Value initialData;
783 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
784 mPipelineCacheVkBlobKey, &initialData);
785
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400786 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400787
788 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400789 pipelineCacheCreateInfo.flags = 0;
790 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
791 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
792
Yuly Novikov27780292018-11-09 11:19:49 -0500793 ANGLE_VK_TRY(display, mPipelineCacheVk.init(mDevice, pipelineCacheCreateInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400794 return angle::Result::Continue();
795}
796
Jamie Madillacccc6c2016-05-03 17:22:10 -0400797void RendererVk::ensureCapsInitialized() const
798{
799 if (!mCapsInitialized)
800 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400801 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
802 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
803 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400804 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400805 mCapsInitialized = true;
806 }
807}
808
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400809void RendererVk::getSubmitWaitSemaphores(
810 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400811 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
812 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400813{
814 if (mSubmitLastSignaledSemaphore.getSemaphore())
815 {
816 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400817 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400818
819 // Return the semaphore to the pool (which will remain valid and unused until the
820 // queue it's about to be waited on has finished execution).
821 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
822 }
823
824 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
825 {
826 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400827 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
828
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400829 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
830 }
831 mSubmitWaitSemaphores.clear();
832}
833
Jamie Madillacccc6c2016-05-03 17:22:10 -0400834const gl::Caps &RendererVk::getNativeCaps() const
835{
836 ensureCapsInitialized();
837 return mNativeCaps;
838}
839
840const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
841{
842 ensureCapsInitialized();
843 return mNativeTextureCaps;
844}
845
846const gl::Extensions &RendererVk::getNativeExtensions() const
847{
848 ensureCapsInitialized();
849 return mNativeExtensions;
850}
851
852const gl::Limitations &RendererVk::getNativeLimitations() const
853{
854 ensureCapsInitialized();
855 return mNativeLimitations;
856}
857
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400858uint32_t RendererVk::getMaxActiveTextures()
859{
860 // TODO(lucferron): expose this limitation to GL in Context Caps
861 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
862 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
863}
864
Jamie Madill49ac74b2017-12-21 14:42:33 -0500865const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500866{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500867 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500868}
869
Jamie Madill21061022018-07-12 23:56:30 -0400870angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500871{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500872 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500873 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400874 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
875
Luc Ferron1617e692018-07-11 11:08:19 -0400876 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
877 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400878
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400879 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400880 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
881 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400882
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400883 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500884 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400885 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
886 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400887 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500888 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400889 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500890 submitInfo.signalSemaphoreCount = 0;
891 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500892
Jamie Madill21061022018-07-12 23:56:30 -0400893 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500894 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500895
Jamie Madill4c26fc22017-02-24 11:04:10 -0500896 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400897 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400898 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400899
900 if (mGpuEventsEnabled)
901 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400902 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400903 while (mInFlightGpuEventQueries.size() > 0)
904 {
905 ANGLE_TRY(checkCompletedGpuEvents(context));
906 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400907 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
908 // synchronization if there is no event to be adjusted (happens when finish() gets called
909 // multiple times towards the end of the application).
910 if (mGpuEvents.size() > 0)
911 {
912 ANGLE_TRY(synchronizeCpuGpuTime(context));
913 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400914 }
915
Jamie Madill21061022018-07-12 23:56:30 -0400916 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -0500917}
918
Jamie Madill0c0dc342017-03-24 14:18:51 -0400919void RendererVk::freeAllInFlightResources()
920{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500921 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400922 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500923 batch.fence.destroy(mDevice);
924 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400925 }
926 mInFlightCommands.clear();
927
928 for (auto &garbage : mGarbage)
929 {
Jamie Madille88ec8e2017-10-31 17:18:14 -0400930 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400931 }
932 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400933
934 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400935}
936
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -0400937angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500938{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500939 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -0500940
Jamie Madill49ac74b2017-12-21 14:42:33 -0500941 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500942 {
Yuly Novikov27780292018-11-09 11:19:49 -0500943 VkResult result = batch.fence.getStatus(mDevice);
944 if (result == VK_NOT_READY)
945 {
Jamie Madill0c0dc342017-03-24 14:18:51 -0400946 break;
Yuly Novikov27780292018-11-09 11:19:49 -0500947 }
948 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -0500949
Jamie Madill49ac74b2017-12-21 14:42:33 -0500950 ASSERT(batch.serial > mLastCompletedQueueSerial);
951 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400952
Jamie Madill49ac74b2017-12-21 14:42:33 -0500953 batch.fence.destroy(mDevice);
954 batch.commandPool.destroy(mDevice);
955 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500956 }
957
Jamie Madill49ac74b2017-12-21 14:42:33 -0500958 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400959
960 size_t freeIndex = 0;
961 for (; freeIndex < mGarbage.size(); ++freeIndex)
962 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500963 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -0400964 break;
965 }
966
967 // Remove the entries from the garbage list - they should be ready to go.
968 if (freeIndex > 0)
969 {
970 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -0500971 }
972
Jamie Madill21061022018-07-12 23:56:30 -0400973 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -0500974}
975
Jamie Madill21061022018-07-12 23:56:30 -0400976angle::Result RendererVk::submitFrame(vk::Context *context,
977 const VkSubmitInfo &submitInfo,
978 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500979{
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400980 VkFenceCreateInfo fenceInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500981 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500982 fenceInfo.flags = 0;
983
Jamie Madillbea35a62018-07-05 11:54:10 -0400984 vk::Scoped<CommandBatch> scopedBatch(mDevice);
985 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -0500986 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500987
Jamie Madill21061022018-07-12 23:56:30 -0400988 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -0500989
990 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -0500991 batch.commandPool = std::move(mCommandPool);
992 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500993
Jamie Madillbea35a62018-07-05 11:54:10 -0400994 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -0400995
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400996 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
997 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
998 // so the limit is larger than the expected number of images.
999 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001000
1001 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001002 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001003 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001004 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001005
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001006 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001007
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001008 if (mGpuEventsEnabled)
1009 {
1010 ANGLE_TRY(checkCompletedGpuEvents(context));
1011 }
1012
Jamie Madill49ac74b2017-12-21 14:42:33 -05001013 // Simply null out the command buffer here - it was allocated using the command pool.
1014 commandBuffer.releaseHandle();
1015
1016 // Reallocate the command pool for next frame.
1017 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001018 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001019 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001020 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001021 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001022
Yuly Novikov27780292018-11-09 11:19:49 -05001023 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
1024 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001025}
1026
Jamie Madillaaca96e2018-06-12 10:19:48 -04001027bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001028{
1029 return serial > mLastCompletedQueueSerial;
1030}
1031
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001032angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1033{
1034 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1035 {
1036 return angle::Result::Continue();
1037 }
1038
1039 // Find the first batch with serial equal to or bigger than given serial (note that
1040 // the batch serials are unique, otherwise upper-bound would have been necessary).
1041 size_t batchIndex = mInFlightCommands.size() - 1;
1042 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1043 {
1044 if (mInFlightCommands[i].serial >= serial)
1045 {
1046 batchIndex = i;
1047 break;
1048 }
1049 }
1050 const CommandBatch &batch = mInFlightCommands[batchIndex];
1051
1052 // Wait for it finish
1053 constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Yuly Novikov27780292018-11-09 11:19:49 -05001054 // Wait a maximum of 10s. If that times out, we declare it a failure.
1055 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001056
1057 // Clean up finished batches.
1058 return checkCompletedCommands(context);
1059}
1060
Jamie Madill21061022018-07-12 23:56:30 -04001061angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1062 const vk::RenderPassDesc &desc,
1063 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001064{
Jamie Madill21061022018-07-12 23:56:30 -04001065 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001066 renderPassOut);
1067}
1068
Jamie Madill21061022018-07-12 23:56:30 -04001069angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1070 const vk::RenderPassDesc &desc,
1071 const vk::AttachmentOpsArray &ops,
1072 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001073{
Jamie Madill21061022018-07-12 23:56:30 -04001074 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001075 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001076}
1077
Jamie Madilla5e06072018-05-18 14:36:05 -04001078vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001079{
Jamie Madilla5e06072018-05-18 14:36:05 -04001080 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001081}
1082
Jamie Madill21061022018-07-12 23:56:30 -04001083angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001084{
Jamie Madill21061022018-07-12 23:56:30 -04001085 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001086 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001087}
1088
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001089angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001090{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001091 if (mCommandGraph.empty())
1092 {
1093 return angle::Result::Continue();
1094 }
1095
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001096 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1097
Jamie Madillbea35a62018-07-05 11:54:10 -04001098 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1099 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001100
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001101 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001102 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1103 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001104
1105 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1106 // will be waited on.
1107 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001108
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001109 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001110 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001111 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1112 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001113 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001114 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001115 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001116 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001117 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001118
Jamie Madill21061022018-07-12 23:56:30 -04001119 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001120
Jamie Madill21061022018-07-12 23:56:30 -04001121 return angle::Result::Continue();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001122}
1123
Jamie Madill78feddc2018-04-27 11:45:05 -04001124Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001125{
Jamie Madill78feddc2018-04-27 11:45:05 -04001126 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001127}
1128
Jamie Madill06ca6342018-07-12 15:56:53 -04001129angle::Result RendererVk::getPipeline(vk::Context *context,
1130 const vk::ShaderAndSerial &vertexShader,
1131 const vk::ShaderAndSerial &fragmentShader,
1132 const vk::PipelineLayout &pipelineLayout,
1133 const vk::PipelineDesc &pipelineDesc,
1134 const gl::AttributesMask &activeAttribLocationsMask,
1135 vk::PipelineAndSerial **pipelineOut)
Jamie Madillffa4cbb2018-01-23 13:04:07 -05001136{
Jamie Madill06ca6342018-07-12 15:56:53 -04001137 ASSERT(vertexShader.getSerial() ==
Jamie Madill9aef3672018-04-27 11:45:06 -04001138 pipelineDesc.getShaderStageInfo()[vk::ShaderType::VertexShader].moduleSerial);
Jamie Madill06ca6342018-07-12 15:56:53 -04001139 ASSERT(fragmentShader.getSerial() ==
Jamie Madill9aef3672018-04-27 11:45:06 -04001140 pipelineDesc.getShaderStageInfo()[vk::ShaderType::FragmentShader].moduleSerial);
1141
1142 // Pull in a compatible RenderPass.
1143 vk::RenderPass *compatibleRenderPass = nullptr;
Jamie Madill21061022018-07-12 23:56:30 -04001144 ANGLE_TRY(
1145 getCompatibleRenderPass(context, pipelineDesc.getRenderPassDesc(), &compatibleRenderPass));
Jamie Madill9aef3672018-04-27 11:45:06 -04001146
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001147 return mPipelineCache.getPipeline(context, mPipelineCacheVk, *compatibleRenderPass,
1148 pipelineLayout, activeAttribLocationsMask, vertexShader.get(),
Jamie Madill9aef3672018-04-27 11:45:06 -04001149 fragmentShader.get(), pipelineDesc, pipelineOut);
1150}
1151
Jamie Madill21061022018-07-12 23:56:30 -04001152angle::Result RendererVk::getDescriptorSetLayout(
1153 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001154 const vk::DescriptorSetLayoutDesc &desc,
1155 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1156{
Jamie Madill21061022018-07-12 23:56:30 -04001157 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001158}
1159
Jamie Madill21061022018-07-12 23:56:30 -04001160angle::Result RendererVk::getPipelineLayout(
1161 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001162 const vk::PipelineLayoutDesc &desc,
1163 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1164 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1165{
Jamie Madill21061022018-07-12 23:56:30 -04001166 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001167 pipelineLayoutOut);
1168}
1169
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001170angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1171{
1172 ASSERT(mPipelineCacheVk.valid());
1173
1174 if (--mPipelineCacheVkUpdateTimeout > 0)
1175 {
1176 return angle::Result::Continue();
1177 }
1178
1179 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1180
1181 // Get the size of the cache.
1182 size_t pipelineCacheSize = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001183 VkResult result = mPipelineCacheVk.getCacheData(mDevice, &pipelineCacheSize, nullptr);
1184 if (result != VK_INCOMPLETE)
1185 {
1186 ANGLE_VK_TRY(displayVk, result);
1187 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001188
1189 angle::MemoryBuffer *pipelineCacheData = nullptr;
1190 ANGLE_VK_CHECK_ALLOC(displayVk,
1191 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1192
1193 size_t originalPipelineCacheSize = pipelineCacheSize;
Yuly Novikov27780292018-11-09 11:19:49 -05001194 result = mPipelineCacheVk.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001195 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1196 // was determined just above), so receiving it hints at an implementation bug we would want
1197 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001198 ASSERT(result != VK_INCOMPLETE);
1199 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001200
1201 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1202 // the buffer to avoid leaking garbage memory.
1203 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1204 if (pipelineCacheSize < originalPipelineCacheSize)
1205 {
1206 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1207 originalPipelineCacheSize - pipelineCacheSize);
1208 }
1209
1210 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1211
1212 return angle::Result::Continue();
1213}
1214
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001215angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1216 const vk::Semaphore **outSemaphore)
1217{
1218 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1219
1220 vk::SemaphoreHelper semaphore;
1221 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1222
1223 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1224 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1225
1226 return angle::Result::Continue();
1227}
1228
1229const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1230{
1231 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1232
1233 // Return the semaphore to the pool (which will remain valid and unused until the
1234 // queue it's about to be waited on has finished execution). The caller is about
1235 // to wait on it.
1236 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1237
1238 return semaphore;
1239}
1240
Jamie Madilld47044a2018-04-27 11:45:03 -04001241vk::ShaderLibrary *RendererVk::getShaderLibrary()
1242{
1243 return &mShaderLibrary;
1244}
Luc Ferron90968362018-05-04 08:47:22 -04001245
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001246angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1247{
1248 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1249 // that seems impossible, so instead, we are going to make a small submission with just a
1250 // timestamp query. First, the disjoint timer query extension says:
1251 //
1252 // > This will return the GL time after all previous commands have reached the GL server but
1253 // have not yet necessarily executed.
1254 //
1255 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1256 // The wording allows us to make a submission to get the timestamp without performing a flush.
1257 //
1258 // Second:
1259 //
1260 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1261 // object target, applications can measure the latency between when commands reach the GL server
1262 // and when they are realized in the framebuffer.
1263 //
1264 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1265 // GPU bubble. This function directly generates a command buffer and submits it instead of
1266 // using the other member functions. This is to avoid changing any state, such as the queue
1267 // serial.
1268
1269 // Create a query used to receive the GPU timestamp
1270 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1271 vk::QueryHelper timestampQuery;
1272 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1273 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1274
1275 // Record the command buffer
1276 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1277 vk::CommandBuffer &commandBuffer = commandBatch.get();
1278
1279 VkCommandBufferAllocateInfo commandBufferInfo = {};
1280 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1281 commandBufferInfo.commandPool = mCommandPool.getHandle();
1282 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1283 commandBufferInfo.commandBufferCount = 1;
1284
Yuly Novikov27780292018-11-09 11:19:49 -05001285 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001286
1287 VkCommandBufferBeginInfo beginInfo = {};
1288 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1289 beginInfo.flags = 0;
1290 beginInfo.pInheritanceInfo = nullptr;
1291
Yuly Novikov27780292018-11-09 11:19:49 -05001292 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001293
1294 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1295 timestampQuery.getQuery(), 1);
1296 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1297 timestampQuery.getQueryPool()->getHandle(),
1298 timestampQuery.getQuery());
1299
Yuly Novikov27780292018-11-09 11:19:49 -05001300 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001301
1302 // Create fence for the submission
1303 VkFenceCreateInfo fenceInfo = {};
1304 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1305 fenceInfo.flags = 0;
1306
1307 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001308 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001309
1310 // Submit the command buffer
1311 VkSubmitInfo submitInfo = {};
1312 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1313 submitInfo.waitSemaphoreCount = 0;
1314 submitInfo.pWaitSemaphores = nullptr;
1315 submitInfo.pWaitDstStageMask = nullptr;
1316 submitInfo.commandBufferCount = 1;
1317 submitInfo.pCommandBuffers = commandBuffer.ptr();
1318 submitInfo.signalSemaphoreCount = 0;
1319 submitInfo.pSignalSemaphores = nullptr;
1320
1321 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1322
1323 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1324 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001325 // Declare it a failure if it times out.
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001326 constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Yuly Novikov27780292018-11-09 11:19:49 -05001327 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001328
1329 // Get the query results
1330 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1331
Yuly Novikov27780292018-11-09 11:19:49 -05001332 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1333 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1334 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001335
1336 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1337
1338 return angle::Result::Continue();
1339}
1340
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001341angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1342{
1343 ASSERT(mGpuEventsEnabled);
1344
1345 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1346 ASSERT(platform);
1347
1348 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1349 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1350 //
1351 // CPU GPU
1352 //
1353 // Record command buffer
1354 // with timestamp query
1355 //
1356 // Submit command buffer
1357 //
1358 // Post-submission work Begin execution
1359 //
1360 // ???? Write timstamp Tgpu
1361 //
1362 // ???? End execution
1363 //
1364 // ???? Return query results
1365 //
1366 // ????
1367 //
1368 // Get query results
1369 //
1370 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1371 // finished post-submission work while the GPU is executing in parallel. With no further work,
1372 // querying CPU timestamps before submission and after getting query results give the bounds to
1373 // Tgpu, which could be quite large.
1374 //
1375 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1376 // reduce this range. This function implements the following procedure:
1377 //
1378 // CPU GPU
1379 //
1380 // Record command buffer
1381 // with timestamp query
1382 //
1383 // Submit command buffer
1384 //
1385 // Post-submission work Begin execution
1386 //
1387 // ???? Set Event GPUReady
1388 //
1389 // Wait on Event GPUReady Wait on Event CPUReady
1390 //
1391 // Get CPU Time Ts Wait on Event CPUReady
1392 //
1393 // Set Event CPUReady Wait on Event CPUReady
1394 //
1395 // Get CPU Time Tcpu Get GPU Time Tgpu
1396 //
1397 // Wait on Event GPUDone Set Event GPUDone
1398 //
1399 // Get CPU Time Te End Execution
1400 //
1401 // Idle Return query results
1402 //
1403 // Get query results
1404 //
1405 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1406 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1407 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1408 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1409 // calibration.
1410 //
1411 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1412
1413 // Make sure nothing is running
1414 ASSERT(mCommandGraph.empty());
1415
1416 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1417
1418 // Create a query used to receive the GPU timestamp
1419 vk::QueryHelper timestampQuery;
1420 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1421
1422 // Create the three events
1423 VkEventCreateInfo eventCreateInfo = {};
1424 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1425 eventCreateInfo.flags = 0;
1426
1427 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001428 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1429 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1430 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001431
1432 constexpr uint32_t kRetries = 10;
1433
1434 // Time suffixes used are S for seconds and Cycles for cycles
1435 double tightestRangeS = 1e6f;
1436 double TcpuS = 0;
1437 uint64_t TgpuCycles = 0;
1438 for (uint32_t i = 0; i < kRetries; ++i)
1439 {
1440 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001441 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1442 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1443 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001444
1445 // Record the command buffer
1446 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1447 vk::CommandBuffer &commandBuffer = commandBatch.get();
1448
1449 VkCommandBufferAllocateInfo commandBufferInfo = {};
1450 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1451 commandBufferInfo.commandPool = mCommandPool.getHandle();
1452 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1453 commandBufferInfo.commandBufferCount = 1;
1454
Yuly Novikov27780292018-11-09 11:19:49 -05001455 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001456
1457 VkCommandBufferBeginInfo beginInfo = {};
1458 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1459 beginInfo.flags = 0;
1460 beginInfo.pInheritanceInfo = nullptr;
1461
Yuly Novikov27780292018-11-09 11:19:49 -05001462 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001463
1464 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1465 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1466 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1467 nullptr);
1468
1469 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1470 timestampQuery.getQuery(), 1);
1471 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1472 timestampQuery.getQueryPool()->getHandle(),
1473 timestampQuery.getQuery());
1474
1475 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1476
Yuly Novikov27780292018-11-09 11:19:49 -05001477 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001478
1479 // Submit the command buffer
1480 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1481 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1482 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1483
1484 VkSubmitInfo submitInfo = {};
1485 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1486 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1487 submitInfo.pWaitSemaphores = waitSemaphores.data();
1488 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1489 submitInfo.commandBufferCount = 1;
1490 submitInfo.pCommandBuffers = commandBuffer.ptr();
1491 submitInfo.signalSemaphoreCount = 0;
1492 submitInfo.pSignalSemaphores = nullptr;
1493
1494 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1495
1496 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001497 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001498 do
1499 {
Yuly Novikov27780292018-11-09 11:19:49 -05001500 result = gpuReady.get().getStatus(mDevice);
1501 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1502 {
1503 ANGLE_VK_TRY(context, result);
1504 }
1505 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001506
1507 double TsS = platform->monotonicallyIncreasingTime(platform);
1508
1509 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001510 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001511 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1512
1513 // Wait for GPU to be done. Another short busy wait.
1514 do
1515 {
Yuly Novikov27780292018-11-09 11:19:49 -05001516 result = gpuDone.get().getStatus(mDevice);
1517 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1518 {
1519 ANGLE_VK_TRY(context, result);
1520 }
1521 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001522
1523 double TeS = platform->monotonicallyIncreasingTime(platform);
1524
1525 // Get the query results
1526 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1527
1528 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1529
1530 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001531 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1532 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1533 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001534
1535 // Use the first timestamp queried as origin.
1536 if (mGpuEventTimestampOrigin == 0)
1537 {
1538 mGpuEventTimestampOrigin = gpuTimestampCycles;
1539 }
1540
1541 // Take these CPU and GPU timestamps if there is better confidence.
1542 double confidenceRangeS = TeS - TsS;
1543 if (confidenceRangeS < tightestRangeS)
1544 {
1545 tightestRangeS = confidenceRangeS;
1546 TcpuS = cpuTimestampS;
1547 TgpuCycles = gpuTimestampCycles;
1548 }
1549 }
1550
1551 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1552
1553 // timestampPeriod gives nanoseconds/cycle.
1554 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1555 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1556 1'000'000'000.0;
1557
1558 flushGpuEvents(TgpuS, TcpuS);
1559
1560 mGpuClockSync.gpuTimestampS = TgpuS;
1561 mGpuClockSync.cpuTimestampS = TcpuS;
1562
1563 return angle::Result::Continue();
1564}
1565
1566angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1567 vk::CommandBuffer *commandBuffer,
1568 char phase,
1569 const char *name)
1570{
1571 ASSERT(mGpuEventsEnabled);
1572
1573 GpuEventQuery event;
1574
1575 event.name = name;
1576 event.phase = phase;
1577 event.serial = mCurrentQueueSerial;
1578
1579 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1580
1581 commandBuffer->resetQueryPool(
1582 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1583 commandBuffer->writeTimestamp(
1584 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1585 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1586
1587 mInFlightGpuEventQueries.push_back(std::move(event));
1588
1589 return angle::Result::Continue();
1590}
1591
1592angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1593{
1594 ASSERT(mGpuEventsEnabled);
1595
1596 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1597 ASSERT(platform);
1598
1599 int finishedCount = 0;
1600
1601 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1602 {
1603 // Only check the timestamp query if the submission has finished.
1604 if (eventQuery.serial > mLastCompletedQueueSerial)
1605 {
1606 break;
1607 }
1608
1609 // See if the results are available.
1610 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001611 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1612 ->getResults(mDevice, eventQuery.queryIndex, 1,
1613 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1614 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1615 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001616 {
1617 break;
1618 }
Yuly Novikov27780292018-11-09 11:19:49 -05001619 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001620
1621 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1622
1623 GpuEvent event;
1624 event.gpuTimestampCycles = gpuTimestampCycles;
1625 event.name = eventQuery.name;
1626 event.phase = eventQuery.phase;
1627
1628 mGpuEvents.emplace_back(event);
1629
1630 ++finishedCount;
1631 }
1632
1633 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1634 mInFlightGpuEventQueries.begin() + finishedCount);
1635
1636 return angle::Result::Continue();
1637}
1638
1639void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1640{
1641 if (mGpuEvents.size() == 0)
1642 {
1643 return;
1644 }
1645
1646 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1647 ASSERT(platform);
1648
1649 // Find the slope of the clock drift for adjustment
1650 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1651 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1652 double gpuSyncDriftSlope = 0;
1653
1654 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1655 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1656
1657 // No gpu trace events should have been generated before the clock sync, so if there is no
1658 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1659 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1660 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1661
1662 gpuSyncDriftSlope =
1663 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1664
1665 for (const GpuEvent &event : mGpuEvents)
1666 {
1667 double gpuTimestampS =
1668 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1669 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1670
1671 // Account for clock drift.
1672 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1673
1674 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1675 // for.
1676 static long long eventId = 1;
1677 static const unsigned char *categoryEnabled =
1678 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1679 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1680 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1681 }
1682
1683 mGpuEvents.clear();
1684}
1685
Jamie Madillaaca96e2018-06-12 10:19:48 -04001686uint32_t GetUniformBufferDescriptorCount()
1687{
1688 return kUniformBufferDescriptorsPerDescriptorSet;
1689}
1690
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001691} // namespace rx