blob: dba99da1155c0c8e69ad2a6e446501ac1892a0e5 [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 Youssefi092481a2018-11-08 00:25:50 -0500534 mFormatTable.initialize(mPhysicalDevice, mPhysicalDeviceProperties, mFeatures,
535 &mNativeTextureCaps, &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
Shahbaz Youssefi092481a2018-11-08 00:25:50 -0500736gl::Version RendererVk::getMaxSupportedESVersion() const
737{
738 // Declare GLES2 support if necessary features for GLES3 are missing
739 bool necessaryFeaturesForES3 = mPhysicalDeviceFeatures.inheritedQueries;
740
741 if (!necessaryFeaturesForES3)
742 {
743 return gl::Version(2, 0);
744 }
745
746 return gl::Version(3, 0);
747}
748
Jamie Madill12222072018-07-11 14:59:48 -0400749void RendererVk::initFeatures()
750{
Jamie Madillb36a4812018-09-25 10:15:11 -0400751// Use OpenGL line rasterization rules by default.
752// TODO(jmadill): Fix Android support. http://anglebug.com/2830
753#if defined(ANGLE_PLATFORM_ANDROID)
754 mFeatures.basicGLLineRasterization = false;
755#else
Jamie Madill12222072018-07-11 14:59:48 -0400756 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -0400757#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -0400758
Luc Ferronf786b702018-07-10 11:01:43 -0400759 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
760 // investigation. http://anglebug.com/2728
761 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -0400762
763#ifdef ANGLE_PLATFORM_WINDOWS
764 // http://anglebug.com/2838
765 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
766#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -0400767
768 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
769 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madill12222072018-07-11 14:59:48 -0400770}
771
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400772void RendererVk::initPipelineCacheVkKey()
773{
774 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
775 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
776 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
777 // there is no '\0' in the result.
778 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
779 {
780 hashStream << std::hex << c;
781 }
782 // Add the vendor and device id too for good measure.
783 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
784 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
785
786 const std::string &hashString = hashStream.str();
787 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
788 hashString.length(), mPipelineCacheVkBlobKey.data());
789}
790
791angle::Result RendererVk::initPipelineCacheVk(DisplayVk *display)
792{
793 initPipelineCacheVkKey();
794
795 egl::BlobCache::Value initialData;
796 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
797 mPipelineCacheVkBlobKey, &initialData);
798
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400799 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400800
801 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400802 pipelineCacheCreateInfo.flags = 0;
803 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
804 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
805
Yuly Novikov27780292018-11-09 11:19:49 -0500806 ANGLE_VK_TRY(display, mPipelineCacheVk.init(mDevice, pipelineCacheCreateInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400807 return angle::Result::Continue();
808}
809
Jamie Madillacccc6c2016-05-03 17:22:10 -0400810void RendererVk::ensureCapsInitialized() const
811{
812 if (!mCapsInitialized)
813 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -0400814 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
815 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
816 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -0400817 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -0400818 mCapsInitialized = true;
819 }
820}
821
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400822void RendererVk::getSubmitWaitSemaphores(
823 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400824 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
825 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400826{
827 if (mSubmitLastSignaledSemaphore.getSemaphore())
828 {
829 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400830 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400831
832 // Return the semaphore to the pool (which will remain valid and unused until the
833 // queue it's about to be waited on has finished execution).
834 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
835 }
836
837 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
838 {
839 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400840 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
841
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400842 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
843 }
844 mSubmitWaitSemaphores.clear();
845}
846
Jamie Madillacccc6c2016-05-03 17:22:10 -0400847const gl::Caps &RendererVk::getNativeCaps() const
848{
849 ensureCapsInitialized();
850 return mNativeCaps;
851}
852
853const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
854{
855 ensureCapsInitialized();
856 return mNativeTextureCaps;
857}
858
859const gl::Extensions &RendererVk::getNativeExtensions() const
860{
861 ensureCapsInitialized();
862 return mNativeExtensions;
863}
864
865const gl::Limitations &RendererVk::getNativeLimitations() const
866{
867 ensureCapsInitialized();
868 return mNativeLimitations;
869}
870
Luc Ferrondaedf4d2018-03-16 09:28:53 -0400871uint32_t RendererVk::getMaxActiveTextures()
872{
873 // TODO(lucferron): expose this limitation to GL in Context Caps
874 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
875 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
876}
877
Jamie Madill49ac74b2017-12-21 14:42:33 -0500878const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -0500879{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500880 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500881}
882
Jamie Madill21061022018-07-12 23:56:30 -0400883angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500884{
Jamie Madill1f46bc12018-02-20 16:09:43 -0500885 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -0500886 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400887 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
888
Luc Ferron1617e692018-07-11 11:08:19 -0400889 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
890 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400891
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400892 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400893 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
894 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400895
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400896 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500897 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400898 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
899 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400900 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500901 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -0400902 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -0500903 submitInfo.signalSemaphoreCount = 0;
904 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500905
Jamie Madill21061022018-07-12 23:56:30 -0400906 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -0500907 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500908
Jamie Madill4c26fc22017-02-24 11:04:10 -0500909 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -0400910 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -0400911 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400912
913 if (mGpuEventsEnabled)
914 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400915 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400916 while (mInFlightGpuEventQueries.size() > 0)
917 {
918 ANGLE_TRY(checkCompletedGpuEvents(context));
919 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -0400920 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
921 // synchronization if there is no event to be adjusted (happens when finish() gets called
922 // multiple times towards the end of the application).
923 if (mGpuEvents.size() > 0)
924 {
925 ANGLE_TRY(synchronizeCpuGpuTime(context));
926 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400927 }
928
Jamie Madill21061022018-07-12 23:56:30 -0400929 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -0500930}
931
Jamie Madill0c0dc342017-03-24 14:18:51 -0400932void RendererVk::freeAllInFlightResources()
933{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500934 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -0400935 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500936 batch.fence.destroy(mDevice);
937 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400938 }
939 mInFlightCommands.clear();
940
941 for (auto &garbage : mGarbage)
942 {
Jamie Madille88ec8e2017-10-31 17:18:14 -0400943 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400944 }
945 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -0400946
947 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400948}
949
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -0400950angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500951{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500952 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -0500953
Jamie Madill49ac74b2017-12-21 14:42:33 -0500954 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500955 {
Yuly Novikov27780292018-11-09 11:19:49 -0500956 VkResult result = batch.fence.getStatus(mDevice);
957 if (result == VK_NOT_READY)
958 {
Jamie Madill0c0dc342017-03-24 14:18:51 -0400959 break;
Yuly Novikov27780292018-11-09 11:19:49 -0500960 }
961 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -0500962
Jamie Madill49ac74b2017-12-21 14:42:33 -0500963 ASSERT(batch.serial > mLastCompletedQueueSerial);
964 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -0400965
Jamie Madill49ac74b2017-12-21 14:42:33 -0500966 batch.fence.destroy(mDevice);
967 batch.commandPool.destroy(mDevice);
968 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -0500969 }
970
Jamie Madill49ac74b2017-12-21 14:42:33 -0500971 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -0400972
973 size_t freeIndex = 0;
974 for (; freeIndex < mGarbage.size(); ++freeIndex)
975 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500976 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -0400977 break;
978 }
979
980 // Remove the entries from the garbage list - they should be ready to go.
981 if (freeIndex > 0)
982 {
983 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -0500984 }
985
Jamie Madill21061022018-07-12 23:56:30 -0400986 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -0500987}
988
Jamie Madill21061022018-07-12 23:56:30 -0400989angle::Result RendererVk::submitFrame(vk::Context *context,
990 const VkSubmitInfo &submitInfo,
991 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -0500992{
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400993 VkFenceCreateInfo fenceInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -0500994 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500995 fenceInfo.flags = 0;
996
Jamie Madillbea35a62018-07-05 11:54:10 -0400997 vk::Scoped<CommandBatch> scopedBatch(mDevice);
998 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -0500999 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001000
Jamie Madill21061022018-07-12 23:56:30 -04001001 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001002
1003 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001004 batch.commandPool = std::move(mCommandPool);
1005 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001006
Jamie Madillbea35a62018-07-05 11:54:10 -04001007 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001008
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001009 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1010 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
1011 // so the limit is larger than the expected number of images.
1012 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001013
1014 // Increment the queue serial. If this fails, we should restart ANGLE.
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001015 // TODO(jmadill): Overflow check.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001016 mLastSubmittedQueueSerial = mCurrentQueueSerial;
Jamie Madillfb05bcb2017-06-07 15:43:18 -04001017 mCurrentQueueSerial = mQueueSerialFactory.generate();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001018
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001019 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001020
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001021 if (mGpuEventsEnabled)
1022 {
1023 ANGLE_TRY(checkCompletedGpuEvents(context));
1024 }
1025
Jamie Madill49ac74b2017-12-21 14:42:33 -05001026 // Simply null out the command buffer here - it was allocated using the command pool.
1027 commandBuffer.releaseHandle();
1028
1029 // Reallocate the command pool for next frame.
1030 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001031 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001032 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001033 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001034 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001035
Yuly Novikov27780292018-11-09 11:19:49 -05001036 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
1037 return angle::Result::Continue();
Jamie Madill4c26fc22017-02-24 11:04:10 -05001038}
1039
Jamie Madillaaca96e2018-06-12 10:19:48 -04001040bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001041{
1042 return serial > mLastCompletedQueueSerial;
1043}
1044
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001045angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1046{
1047 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1048 {
1049 return angle::Result::Continue();
1050 }
1051
1052 // Find the first batch with serial equal to or bigger than given serial (note that
1053 // the batch serials are unique, otherwise upper-bound would have been necessary).
1054 size_t batchIndex = mInFlightCommands.size() - 1;
1055 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1056 {
1057 if (mInFlightCommands[i].serial >= serial)
1058 {
1059 batchIndex = i;
1060 break;
1061 }
1062 }
1063 const CommandBatch &batch = mInFlightCommands[batchIndex];
1064
1065 // Wait for it finish
1066 constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Yuly Novikov27780292018-11-09 11:19:49 -05001067 // Wait a maximum of 10s. If that times out, we declare it a failure.
1068 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001069
1070 // Clean up finished batches.
1071 return checkCompletedCommands(context);
1072}
1073
Jamie Madill21061022018-07-12 23:56:30 -04001074angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1075 const vk::RenderPassDesc &desc,
1076 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001077{
Jamie Madill21061022018-07-12 23:56:30 -04001078 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001079 renderPassOut);
1080}
1081
Jamie Madill21061022018-07-12 23:56:30 -04001082angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1083 const vk::RenderPassDesc &desc,
1084 const vk::AttachmentOpsArray &ops,
1085 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001086{
Jamie Madill21061022018-07-12 23:56:30 -04001087 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001088 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001089}
1090
Jamie Madilla5e06072018-05-18 14:36:05 -04001091vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001092{
Jamie Madilla5e06072018-05-18 14:36:05 -04001093 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001094}
1095
Jamie Madill21061022018-07-12 23:56:30 -04001096angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001097{
Jamie Madill21061022018-07-12 23:56:30 -04001098 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001099 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001100}
1101
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001102angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001103{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001104 if (mCommandGraph.empty())
1105 {
1106 return angle::Result::Continue();
1107 }
1108
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001109 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1110
Jamie Madillbea35a62018-07-05 11:54:10 -04001111 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1112 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001113
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001114 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001115 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1116 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001117
1118 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1119 // will be waited on.
1120 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001121
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001122 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001123 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001124 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1125 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001126 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001127 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001128 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001129 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001130 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001131
Jamie Madill21061022018-07-12 23:56:30 -04001132 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001133
Jamie Madill21061022018-07-12 23:56:30 -04001134 return angle::Result::Continue();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001135}
1136
Jamie Madill78feddc2018-04-27 11:45:05 -04001137Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001138{
Jamie Madill78feddc2018-04-27 11:45:05 -04001139 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001140}
1141
Jamie Madill06ca6342018-07-12 15:56:53 -04001142angle::Result RendererVk::getPipeline(vk::Context *context,
1143 const vk::ShaderAndSerial &vertexShader,
1144 const vk::ShaderAndSerial &fragmentShader,
1145 const vk::PipelineLayout &pipelineLayout,
1146 const vk::PipelineDesc &pipelineDesc,
1147 const gl::AttributesMask &activeAttribLocationsMask,
1148 vk::PipelineAndSerial **pipelineOut)
Jamie Madillffa4cbb2018-01-23 13:04:07 -05001149{
Jamie Madill06ca6342018-07-12 15:56:53 -04001150 ASSERT(vertexShader.getSerial() ==
Jamie Madill9aef3672018-04-27 11:45:06 -04001151 pipelineDesc.getShaderStageInfo()[vk::ShaderType::VertexShader].moduleSerial);
Jamie Madill06ca6342018-07-12 15:56:53 -04001152 ASSERT(fragmentShader.getSerial() ==
Jamie Madill9aef3672018-04-27 11:45:06 -04001153 pipelineDesc.getShaderStageInfo()[vk::ShaderType::FragmentShader].moduleSerial);
1154
1155 // Pull in a compatible RenderPass.
1156 vk::RenderPass *compatibleRenderPass = nullptr;
Jamie Madill21061022018-07-12 23:56:30 -04001157 ANGLE_TRY(
1158 getCompatibleRenderPass(context, pipelineDesc.getRenderPassDesc(), &compatibleRenderPass));
Jamie Madill9aef3672018-04-27 11:45:06 -04001159
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001160 return mPipelineCache.getPipeline(context, mPipelineCacheVk, *compatibleRenderPass,
1161 pipelineLayout, activeAttribLocationsMask, vertexShader.get(),
Jamie Madill9aef3672018-04-27 11:45:06 -04001162 fragmentShader.get(), pipelineDesc, pipelineOut);
1163}
1164
Jamie Madill21061022018-07-12 23:56:30 -04001165angle::Result RendererVk::getDescriptorSetLayout(
1166 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001167 const vk::DescriptorSetLayoutDesc &desc,
1168 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1169{
Jamie Madill21061022018-07-12 23:56:30 -04001170 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001171}
1172
Jamie Madill21061022018-07-12 23:56:30 -04001173angle::Result RendererVk::getPipelineLayout(
1174 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001175 const vk::PipelineLayoutDesc &desc,
1176 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1177 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1178{
Jamie Madill21061022018-07-12 23:56:30 -04001179 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001180 pipelineLayoutOut);
1181}
1182
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001183angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1184{
1185 ASSERT(mPipelineCacheVk.valid());
1186
1187 if (--mPipelineCacheVkUpdateTimeout > 0)
1188 {
1189 return angle::Result::Continue();
1190 }
1191
1192 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1193
1194 // Get the size of the cache.
1195 size_t pipelineCacheSize = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001196 VkResult result = mPipelineCacheVk.getCacheData(mDevice, &pipelineCacheSize, nullptr);
1197 if (result != VK_INCOMPLETE)
1198 {
1199 ANGLE_VK_TRY(displayVk, result);
1200 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001201
1202 angle::MemoryBuffer *pipelineCacheData = nullptr;
1203 ANGLE_VK_CHECK_ALLOC(displayVk,
1204 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1205
1206 size_t originalPipelineCacheSize = pipelineCacheSize;
Yuly Novikov27780292018-11-09 11:19:49 -05001207 result = mPipelineCacheVk.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001208 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1209 // was determined just above), so receiving it hints at an implementation bug we would want
1210 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001211 ASSERT(result != VK_INCOMPLETE);
1212 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001213
1214 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1215 // the buffer to avoid leaking garbage memory.
1216 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1217 if (pipelineCacheSize < originalPipelineCacheSize)
1218 {
1219 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1220 originalPipelineCacheSize - pipelineCacheSize);
1221 }
1222
1223 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1224
1225 return angle::Result::Continue();
1226}
1227
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001228angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1229 const vk::Semaphore **outSemaphore)
1230{
1231 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1232
1233 vk::SemaphoreHelper semaphore;
1234 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1235
1236 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1237 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1238
1239 return angle::Result::Continue();
1240}
1241
1242const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1243{
1244 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1245
1246 // Return the semaphore to the pool (which will remain valid and unused until the
1247 // queue it's about to be waited on has finished execution). The caller is about
1248 // to wait on it.
1249 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1250
1251 return semaphore;
1252}
1253
Jamie Madilld47044a2018-04-27 11:45:03 -04001254vk::ShaderLibrary *RendererVk::getShaderLibrary()
1255{
1256 return &mShaderLibrary;
1257}
Luc Ferron90968362018-05-04 08:47:22 -04001258
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001259angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1260{
1261 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1262 // that seems impossible, so instead, we are going to make a small submission with just a
1263 // timestamp query. First, the disjoint timer query extension says:
1264 //
1265 // > This will return the GL time after all previous commands have reached the GL server but
1266 // have not yet necessarily executed.
1267 //
1268 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1269 // The wording allows us to make a submission to get the timestamp without performing a flush.
1270 //
1271 // Second:
1272 //
1273 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1274 // object target, applications can measure the latency between when commands reach the GL server
1275 // and when they are realized in the framebuffer.
1276 //
1277 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1278 // GPU bubble. This function directly generates a command buffer and submits it instead of
1279 // using the other member functions. This is to avoid changing any state, such as the queue
1280 // serial.
1281
1282 // Create a query used to receive the GPU timestamp
1283 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1284 vk::QueryHelper timestampQuery;
1285 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1286 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1287
1288 // Record the command buffer
1289 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1290 vk::CommandBuffer &commandBuffer = commandBatch.get();
1291
1292 VkCommandBufferAllocateInfo commandBufferInfo = {};
1293 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1294 commandBufferInfo.commandPool = mCommandPool.getHandle();
1295 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1296 commandBufferInfo.commandBufferCount = 1;
1297
Yuly Novikov27780292018-11-09 11:19:49 -05001298 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001299
1300 VkCommandBufferBeginInfo beginInfo = {};
1301 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1302 beginInfo.flags = 0;
1303 beginInfo.pInheritanceInfo = nullptr;
1304
Yuly Novikov27780292018-11-09 11:19:49 -05001305 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001306
1307 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1308 timestampQuery.getQuery(), 1);
1309 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1310 timestampQuery.getQueryPool()->getHandle(),
1311 timestampQuery.getQuery());
1312
Yuly Novikov27780292018-11-09 11:19:49 -05001313 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001314
1315 // Create fence for the submission
1316 VkFenceCreateInfo fenceInfo = {};
1317 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1318 fenceInfo.flags = 0;
1319
1320 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001321 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001322
1323 // Submit the command buffer
1324 VkSubmitInfo submitInfo = {};
1325 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1326 submitInfo.waitSemaphoreCount = 0;
1327 submitInfo.pWaitSemaphores = nullptr;
1328 submitInfo.pWaitDstStageMask = nullptr;
1329 submitInfo.commandBufferCount = 1;
1330 submitInfo.pCommandBuffers = commandBuffer.ptr();
1331 submitInfo.signalSemaphoreCount = 0;
1332 submitInfo.pSignalSemaphores = nullptr;
1333
1334 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1335
1336 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1337 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001338 // Declare it a failure if it times out.
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001339 constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Yuly Novikov27780292018-11-09 11:19:49 -05001340 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001341
1342 // Get the query results
1343 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1344
Yuly Novikov27780292018-11-09 11:19:49 -05001345 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1346 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1347 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001348
1349 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1350
1351 return angle::Result::Continue();
1352}
1353
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001354angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1355{
1356 ASSERT(mGpuEventsEnabled);
1357
1358 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1359 ASSERT(platform);
1360
1361 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1362 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1363 //
1364 // CPU GPU
1365 //
1366 // Record command buffer
1367 // with timestamp query
1368 //
1369 // Submit command buffer
1370 //
1371 // Post-submission work Begin execution
1372 //
1373 // ???? Write timstamp Tgpu
1374 //
1375 // ???? End execution
1376 //
1377 // ???? Return query results
1378 //
1379 // ????
1380 //
1381 // Get query results
1382 //
1383 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1384 // finished post-submission work while the GPU is executing in parallel. With no further work,
1385 // querying CPU timestamps before submission and after getting query results give the bounds to
1386 // Tgpu, which could be quite large.
1387 //
1388 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1389 // reduce this range. This function implements the following procedure:
1390 //
1391 // CPU GPU
1392 //
1393 // Record command buffer
1394 // with timestamp query
1395 //
1396 // Submit command buffer
1397 //
1398 // Post-submission work Begin execution
1399 //
1400 // ???? Set Event GPUReady
1401 //
1402 // Wait on Event GPUReady Wait on Event CPUReady
1403 //
1404 // Get CPU Time Ts Wait on Event CPUReady
1405 //
1406 // Set Event CPUReady Wait on Event CPUReady
1407 //
1408 // Get CPU Time Tcpu Get GPU Time Tgpu
1409 //
1410 // Wait on Event GPUDone Set Event GPUDone
1411 //
1412 // Get CPU Time Te End Execution
1413 //
1414 // Idle Return query results
1415 //
1416 // Get query results
1417 //
1418 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1419 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1420 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1421 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1422 // calibration.
1423 //
1424 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1425
1426 // Make sure nothing is running
1427 ASSERT(mCommandGraph.empty());
1428
1429 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1430
1431 // Create a query used to receive the GPU timestamp
1432 vk::QueryHelper timestampQuery;
1433 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1434
1435 // Create the three events
1436 VkEventCreateInfo eventCreateInfo = {};
1437 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1438 eventCreateInfo.flags = 0;
1439
1440 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001441 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1442 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1443 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001444
1445 constexpr uint32_t kRetries = 10;
1446
1447 // Time suffixes used are S for seconds and Cycles for cycles
1448 double tightestRangeS = 1e6f;
1449 double TcpuS = 0;
1450 uint64_t TgpuCycles = 0;
1451 for (uint32_t i = 0; i < kRetries; ++i)
1452 {
1453 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001454 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1455 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1456 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001457
1458 // Record the command buffer
1459 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1460 vk::CommandBuffer &commandBuffer = commandBatch.get();
1461
1462 VkCommandBufferAllocateInfo commandBufferInfo = {};
1463 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1464 commandBufferInfo.commandPool = mCommandPool.getHandle();
1465 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1466 commandBufferInfo.commandBufferCount = 1;
1467
Yuly Novikov27780292018-11-09 11:19:49 -05001468 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001469
1470 VkCommandBufferBeginInfo beginInfo = {};
1471 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1472 beginInfo.flags = 0;
1473 beginInfo.pInheritanceInfo = nullptr;
1474
Yuly Novikov27780292018-11-09 11:19:49 -05001475 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001476
1477 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1478 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1479 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1480 nullptr);
1481
1482 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1483 timestampQuery.getQuery(), 1);
1484 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1485 timestampQuery.getQueryPool()->getHandle(),
1486 timestampQuery.getQuery());
1487
1488 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1489
Yuly Novikov27780292018-11-09 11:19:49 -05001490 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001491
1492 // Submit the command buffer
1493 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1494 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1495 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1496
1497 VkSubmitInfo submitInfo = {};
1498 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1499 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1500 submitInfo.pWaitSemaphores = waitSemaphores.data();
1501 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1502 submitInfo.commandBufferCount = 1;
1503 submitInfo.pCommandBuffers = commandBuffer.ptr();
1504 submitInfo.signalSemaphoreCount = 0;
1505 submitInfo.pSignalSemaphores = nullptr;
1506
1507 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1508
1509 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001510 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001511 do
1512 {
Yuly Novikov27780292018-11-09 11:19:49 -05001513 result = gpuReady.get().getStatus(mDevice);
1514 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1515 {
1516 ANGLE_VK_TRY(context, result);
1517 }
1518 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001519
1520 double TsS = platform->monotonicallyIncreasingTime(platform);
1521
1522 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001523 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001524 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1525
1526 // Wait for GPU to be done. Another short busy wait.
1527 do
1528 {
Yuly Novikov27780292018-11-09 11:19:49 -05001529 result = gpuDone.get().getStatus(mDevice);
1530 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1531 {
1532 ANGLE_VK_TRY(context, result);
1533 }
1534 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001535
1536 double TeS = platform->monotonicallyIncreasingTime(platform);
1537
1538 // Get the query results
1539 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1540
1541 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1542
1543 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001544 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1545 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1546 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001547
1548 // Use the first timestamp queried as origin.
1549 if (mGpuEventTimestampOrigin == 0)
1550 {
1551 mGpuEventTimestampOrigin = gpuTimestampCycles;
1552 }
1553
1554 // Take these CPU and GPU timestamps if there is better confidence.
1555 double confidenceRangeS = TeS - TsS;
1556 if (confidenceRangeS < tightestRangeS)
1557 {
1558 tightestRangeS = confidenceRangeS;
1559 TcpuS = cpuTimestampS;
1560 TgpuCycles = gpuTimestampCycles;
1561 }
1562 }
1563
1564 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1565
1566 // timestampPeriod gives nanoseconds/cycle.
1567 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1568 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1569 1'000'000'000.0;
1570
1571 flushGpuEvents(TgpuS, TcpuS);
1572
1573 mGpuClockSync.gpuTimestampS = TgpuS;
1574 mGpuClockSync.cpuTimestampS = TcpuS;
1575
1576 return angle::Result::Continue();
1577}
1578
1579angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1580 vk::CommandBuffer *commandBuffer,
1581 char phase,
1582 const char *name)
1583{
1584 ASSERT(mGpuEventsEnabled);
1585
1586 GpuEventQuery event;
1587
1588 event.name = name;
1589 event.phase = phase;
1590 event.serial = mCurrentQueueSerial;
1591
1592 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1593
1594 commandBuffer->resetQueryPool(
1595 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1596 commandBuffer->writeTimestamp(
1597 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1598 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1599
1600 mInFlightGpuEventQueries.push_back(std::move(event));
1601
1602 return angle::Result::Continue();
1603}
1604
1605angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1606{
1607 ASSERT(mGpuEventsEnabled);
1608
1609 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1610 ASSERT(platform);
1611
1612 int finishedCount = 0;
1613
1614 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1615 {
1616 // Only check the timestamp query if the submission has finished.
1617 if (eventQuery.serial > mLastCompletedQueueSerial)
1618 {
1619 break;
1620 }
1621
1622 // See if the results are available.
1623 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001624 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1625 ->getResults(mDevice, eventQuery.queryIndex, 1,
1626 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1627 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1628 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001629 {
1630 break;
1631 }
Yuly Novikov27780292018-11-09 11:19:49 -05001632 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001633
1634 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1635
1636 GpuEvent event;
1637 event.gpuTimestampCycles = gpuTimestampCycles;
1638 event.name = eventQuery.name;
1639 event.phase = eventQuery.phase;
1640
1641 mGpuEvents.emplace_back(event);
1642
1643 ++finishedCount;
1644 }
1645
1646 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1647 mInFlightGpuEventQueries.begin() + finishedCount);
1648
1649 return angle::Result::Continue();
1650}
1651
1652void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1653{
1654 if (mGpuEvents.size() == 0)
1655 {
1656 return;
1657 }
1658
1659 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1660 ASSERT(platform);
1661
1662 // Find the slope of the clock drift for adjustment
1663 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1664 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1665 double gpuSyncDriftSlope = 0;
1666
1667 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1668 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1669
1670 // No gpu trace events should have been generated before the clock sync, so if there is no
1671 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1672 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1673 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1674
1675 gpuSyncDriftSlope =
1676 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1677
1678 for (const GpuEvent &event : mGpuEvents)
1679 {
1680 double gpuTimestampS =
1681 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1682 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1683
1684 // Account for clock drift.
1685 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1686
1687 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1688 // for.
1689 static long long eventId = 1;
1690 static const unsigned char *categoryEnabled =
1691 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1692 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
1693 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
1694 }
1695
1696 mGpuEvents.clear();
1697}
1698
Jamie Madillaaca96e2018-06-12 10:19:48 -04001699uint32_t GetUniformBufferDescriptorCount()
1700{
1701 return kUniformBufferDescriptorsPerDescriptorSet;
1702}
1703
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001704} // namespace rx