blob: 912a0dd74edba03650caff9acdc66b1c80fca98f [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"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040034
Shahbaz Youssefi61656022018-10-24 15:00:50 -040035#include "third_party/trace_event/trace_event.h"
36
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070037// Consts
38namespace
39{
Jamie Madill7c985f52018-11-29 18:16:17 -050040const uint32_t kMockVendorID = 0xba5eba11;
41const uint32_t kMockDeviceID = 0xf005ba11;
42constexpr char kMockDeviceName[] = "Vulkan Mock Device";
43constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050044constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070045} // anonymous namespace
46
Jamie Madill9e54b5a2016-05-25 12:57:39 -040047namespace rx
48{
49
Jamie Madille09bd5d2016-11-29 16:20:35 -050050namespace
51{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040052// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
53// one for the vertex shader.
54constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040055// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
56static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040057// Wait a maximum of 10s. If that times out, we declare it a failure.
58static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050059
Omar El Sheikh26c61b22018-06-29 12:50:59 -060060bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
61{
62#if !defined(ANGLE_PLATFORM_ANDROID)
63 // Mock ICD does not currently run on Android
64 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
66 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
67#else
68 return false;
69#endif // !defined(ANGLE_PLATFORM_ANDROID)
70}
71
Jamie Madille09bd5d2016-11-29 16:20:35 -050072VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
73 const std::vector<const char *> &enabledExtensionNames)
74{
75 // Compile the extensions names into a set.
76 std::set<std::string> extensionNames;
77 for (const auto &extensionProp : extensionProps)
78 {
79 extensionNames.insert(extensionProp.extensionName);
80 }
81
Jamie Madillacf2f3a2017-11-21 19:22:44 -050082 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050083 {
84 if (extensionNames.count(extensionName) == 0)
85 {
86 return VK_ERROR_EXTENSION_NOT_PRESENT;
87 }
88 }
89
90 return VK_SUCCESS;
91}
92
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050093bool ExtensionFound(const char *extensionName,
94 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060095{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050096 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060097 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050098 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060099 {
100 return true;
101 }
102 }
103 return false;
104}
105
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500106// Array of Validation error/warning messages that will be ignored, should include bugID
107constexpr std::array<const char *, 1> kSkippedMessages = {
108 // http://anglebug.com/2796
109 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
110
111// Suppress validation errors that are known
112// return "true" if given code/prefix/message is known, else return "false"
113bool IsIgnoredDebugMessage(const char *message)
114{
115 for (const char *msg : kSkippedMessages)
116 {
117 if (strstr(message, msg) != nullptr)
118 {
119 return true;
120 }
121 }
122 return false;
123}
124
125const char *GetVkObjectTypeName(VkObjectType type)
126{
127 switch (type)
128 {
129 case VK_OBJECT_TYPE_UNKNOWN:
130 return "Unknown";
131 case VK_OBJECT_TYPE_INSTANCE:
132 return "Instance";
133 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
134 return "Physical Device";
135 case VK_OBJECT_TYPE_DEVICE:
136 return "Device";
137 case VK_OBJECT_TYPE_QUEUE:
138 return "Queue";
139 case VK_OBJECT_TYPE_SEMAPHORE:
140 return "Semaphore";
141 case VK_OBJECT_TYPE_COMMAND_BUFFER:
142 return "Command Buffer";
143 case VK_OBJECT_TYPE_FENCE:
144 return "Fence";
145 case VK_OBJECT_TYPE_DEVICE_MEMORY:
146 return "Device Memory";
147 case VK_OBJECT_TYPE_BUFFER:
148 return "Buffer";
149 case VK_OBJECT_TYPE_IMAGE:
150 return "Image";
151 case VK_OBJECT_TYPE_EVENT:
152 return "Event";
153 case VK_OBJECT_TYPE_QUERY_POOL:
154 return "Query Pool";
155 case VK_OBJECT_TYPE_BUFFER_VIEW:
156 return "Buffer View";
157 case VK_OBJECT_TYPE_IMAGE_VIEW:
158 return "Image View";
159 case VK_OBJECT_TYPE_SHADER_MODULE:
160 return "Shader Module";
161 case VK_OBJECT_TYPE_PIPELINE_CACHE:
162 return "Pipeline Cache";
163 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
164 return "Pipeline Layout";
165 case VK_OBJECT_TYPE_RENDER_PASS:
166 return "Render Pass";
167 case VK_OBJECT_TYPE_PIPELINE:
168 return "Pipeline";
169 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
170 return "Descriptor Set Layout";
171 case VK_OBJECT_TYPE_SAMPLER:
172 return "Sampler";
173 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
174 return "Descriptor Pool";
175 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
176 return "Descriptor Set";
177 case VK_OBJECT_TYPE_FRAMEBUFFER:
178 return "Framebuffer";
179 case VK_OBJECT_TYPE_COMMAND_POOL:
180 return "Command Pool";
181 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
182 return "Sampler YCbCr Conversion";
183 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
184 return "Descriptor Update Template";
185 case VK_OBJECT_TYPE_SURFACE_KHR:
186 return "Surface";
187 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
188 return "Swapchain";
189 case VK_OBJECT_TYPE_DISPLAY_KHR:
190 return "Display";
191 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
192 return "Display Mode";
193 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
194 return "Debug Report Callback";
195 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
196 return "Object Table";
197 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
198 return "Indirect Commands Layout";
199 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
200 return "Debug Utils Messenger";
201 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
202 return "Validation Cache";
203 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
204 return "Acceleration Structure";
205 default:
206 return "<Unrecognized>";
207 }
208}
209
210VKAPI_ATTR VkBool32 VKAPI_CALL
211DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
212 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
213 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
214 void *userData)
215{
216 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
217 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
218 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
219
220 // Check if we even care about this message.
221 if ((messageSeverity & kSeveritiesToLog) == 0)
222 {
223 return VK_FALSE;
224 }
225
226 // See if it's an issue we are aware of and don't want to be spammed about.
227 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
228 {
229 return VK_FALSE;
230 }
231
232 std::ostringstream log;
233 log << "[ " << callbackData->pMessageIdName << " ] " << callbackData->pMessage << std::endl;
234
235 // Aesthetic value based on length of the function name, line number, etc.
236 constexpr size_t kStartIndent = 28;
237
238 // Output the debug marker hierarchy under which this error has occured.
239 size_t indent = kStartIndent;
240 if (callbackData->queueLabelCount > 0)
241 {
242 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
243 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
244 {
245 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
246 << std::endl;
247 }
248 }
249 if (callbackData->cmdBufLabelCount > 0)
250 {
251 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
252 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
253 {
254 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
255 << std::endl;
256 }
257 }
258 // Output the objects involved in this error message.
259 if (callbackData->objectCount > 0)
260 {
261 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
262 {
263 const char *objectName = callbackData->pObjects[i].pObjectName;
264 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
265 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
266 log << std::string(indent, ' ') << "Object: ";
267 if (objectHandle == 0)
268 {
269 log << "VK_NULL_HANDLE";
270 }
271 else
272 {
273 log << "0x" << std::hex << objectHandle << std::dec;
274 }
275 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
276 if (objectName)
277 {
278 log << " [" << objectName << "]";
279 }
280 log << std::endl;
281 }
282 }
283
284 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
285
286 if (isError)
287 {
288 ERR() << log.str();
289 }
290 else
291 {
292 WARN() << log.str();
293 }
294
295 return VK_FALSE;
296}
297
Yuly Novikov199f4292018-01-19 19:04:05 -0500298VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
299 VkDebugReportObjectTypeEXT objectType,
300 uint64_t object,
301 size_t location,
302 int32_t messageCode,
303 const char *layerPrefix,
304 const char *message,
305 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500306{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600307 if (IsIgnoredDebugMessage(message))
308 {
309 return VK_FALSE;
310 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500311 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
312 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500313 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500314#if !defined(NDEBUG)
315 // Abort the call in Debug builds.
316 return VK_TRUE;
317#endif
318 }
319 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
320 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500321 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500322 }
323 else
324 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500325 // Uncomment this if you want Vulkan spam.
326 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500327 }
328
329 return VK_FALSE;
330}
331
Yuly Novikov199f4292018-01-19 19:04:05 -0500332// If we're loading the validation layers, we could be running from any random directory.
333// Change to the executable directory so we can find the layers, then change back to the
334// previous directory to be safe we don't disrupt the application.
335class ScopedVkLoaderEnvironment : angle::NonCopyable
336{
337 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600338 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
339 : mEnableValidationLayers(enableValidationLayers),
340 mEnableMockICD(enableMockICD),
341 mChangedCWD(false),
342 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500343 {
344// Changing CWD and setting environment variables makes no sense on Android,
345// since this code is a part of Java application there.
346// Android Vulkan loader doesn't need this either.
347#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600348 if (enableMockICD)
349 {
350 // Override environment variable to use built Mock ICD
351 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
352 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
353 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
354 if (!mChangedICDPath)
355 {
356 ERR() << "Error setting Path for Mock/Null Driver.";
357 mEnableMockICD = false;
358 }
359 }
Jamie Madill46848422018-08-09 10:46:06 -0400360 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500361 {
362 const auto &cwd = angle::GetCWD();
363 if (!cwd.valid())
364 {
365 ERR() << "Error getting CWD for Vulkan layers init.";
366 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400367 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500368 }
369 else
370 {
371 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500372 std::string exeDir = angle::GetExecutableDirectory();
373 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500374 if (!mChangedCWD)
375 {
376 ERR() << "Error setting CWD for Vulkan layers init.";
377 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400378 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500379 }
380 }
381 }
382
383 // Override environment variable to use the ANGLE layers.
384 if (mEnableValidationLayers)
385 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700386 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500387 {
388 ERR() << "Error setting environment for Vulkan layers init.";
389 mEnableValidationLayers = false;
390 }
391 }
392#endif // !defined(ANGLE_PLATFORM_ANDROID)
393 }
394
395 ~ScopedVkLoaderEnvironment()
396 {
397 if (mChangedCWD)
398 {
399#if !defined(ANGLE_PLATFORM_ANDROID)
400 ASSERT(mPreviousCWD.valid());
401 angle::SetCWD(mPreviousCWD.value().c_str());
402#endif // !defined(ANGLE_PLATFORM_ANDROID)
403 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600404 if (mChangedICDPath)
405 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600406 if (mPreviousICDPath.value().empty())
407 {
408 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
409 }
410 else
411 {
412 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
413 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600414 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500415 }
416
Jamie Madillaaca96e2018-06-12 10:19:48 -0400417 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500418
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600419 bool canEnableMockICD() const { return mEnableMockICD; }
420
Yuly Novikov199f4292018-01-19 19:04:05 -0500421 private:
422 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600423 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500424 bool mChangedCWD;
425 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool mChangedICDPath;
427 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500428};
429
Jamie Madill21061022018-07-12 23:56:30 -0400430void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
431 bool preferMockICD,
432 VkPhysicalDevice *physicalDeviceOut,
433 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
434{
435 ASSERT(!physicalDevices.empty());
436 if (preferMockICD)
437 {
438 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
439 {
440 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
441 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
442 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
443 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
444 {
445 *physicalDeviceOut = physicalDevice;
446 return;
447 }
448 }
449 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
450 "physicalDevice instead.";
451 }
452
453 // Fall back to first device.
454 *physicalDeviceOut = physicalDevices[0];
455 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
456}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400457
458// Initially dumping the command graphs is disabled.
459constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700460
Jamie Madille09bd5d2016-11-29 16:20:35 -0500461} // anonymous namespace
462
Jamie Madill49ac74b2017-12-21 14:42:33 -0500463// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400464RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500465
Jamie Madillaaca96e2018-06-12 10:19:48 -0400466RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500467
468RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000469 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500470{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500471
472RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
473{
474 std::swap(commandPool, other.commandPool);
475 std::swap(fence, other.fence);
476 std::swap(serial, other.serial);
477 return *this;
478}
479
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000480void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400481{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000482 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400483 fence.destroy(device);
484}
485
Jamie Madill9f2a8612017-11-30 12:43:09 -0500486// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500487RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400488 : mDisplay(nullptr),
489 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700490 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500491 mInstance(VK_NULL_HANDLE),
492 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400493 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500494 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500495 mDebugReportCallback(VK_NULL_HANDLE),
496 mPhysicalDevice(VK_NULL_HANDLE),
497 mQueue(VK_NULL_HANDLE),
498 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
499 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400500 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400501 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400502 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400503 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400504 mCommandGraph(kEnableCommandGraphDiagnostics),
505 mGpuEventsEnabled(false),
506 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
507 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500508{
509 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
510 mFormatProperties.fill(invalid);
511}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400512
Jamie Madillb980c562018-11-27 11:34:27 -0500513RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400514
515void RendererVk::onDestroy(vk::Context *context)
516{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500517 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500518 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500519 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400520 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500521 }
522
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100523 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500524
Jamie Madillc7918ce2018-06-13 13:25:31 -0400525 mPipelineLayoutCache.destroy(mDevice);
526 mDescriptorSetLayoutCache.destroy(mDevice);
527
Jamie Madill9f2a8612017-11-30 12:43:09 -0500528 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500529 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400530 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400531 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400532 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500533
Jamie Madill06ca6342018-07-12 15:56:53 -0400534 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500535
Jamie Madill5deea722017-02-16 10:44:46 -0500536 if (mCommandPool.valid())
537 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000538 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500539 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500540
541 if (mDevice)
542 {
543 vkDestroyDevice(mDevice, nullptr);
544 mDevice = VK_NULL_HANDLE;
545 }
546
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500547 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500548 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500549 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
550 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
551
552 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
553 }
554 else if (mDebugReportCallback)
555 {
556 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
557 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500558 }
559
Jamie Madill4d0bf552016-12-28 15:45:24 -0500560 if (mInstance)
561 {
562 vkDestroyInstance(mInstance, nullptr);
563 mInstance = VK_NULL_HANDLE;
564 }
565
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600566 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500568}
569
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400570void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400571{
572 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400573
574 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500575 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400576 freeAllInFlightResources();
577
578 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400579}
580
581bool RendererVk::isDeviceLost() const
582{
583 return mDeviceLost;
584}
585
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400586angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400587 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400588 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500589{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400590 mDisplay = display;
591 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600592 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
593 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500594 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400595 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500596
Jamie Madill0448ec82016-12-23 13:41:47 -0500597 // Gather global layer properties.
598 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400599 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500600
601 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
602 if (instanceLayerCount > 0)
603 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400604 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
605 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500606 }
607
Jamie Madille09bd5d2016-11-29 16:20:35 -0500608 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400609 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400610 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500611
612 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
613 if (instanceExtensionCount > 0)
614 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400615 ANGLE_VK_TRY(displayVk,
616 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
617 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500618 }
619
Yuly Novikov199f4292018-01-19 19:04:05 -0500620 const char *const *enabledLayerNames = nullptr;
621 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500622 if (mEnableValidationLayers)
623 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500624 bool layersRequested =
625 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
626 mEnableValidationLayers = GetAvailableValidationLayers(
627 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500628 }
629
Jamie Madille09bd5d2016-11-29 16:20:35 -0500630 std::vector<const char *> enabledInstanceExtensions;
631 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500632 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500633
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500634 bool enableDebugUtils =
635 mEnableValidationLayers &&
636 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
637 bool enableDebugReport =
638 mEnableValidationLayers && !enableDebugUtils &&
639 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
640
641 if (enableDebugUtils)
642 {
643 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
644 }
645 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500646 {
647 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
648 }
649
Jamie Madille09bd5d2016-11-29 16:20:35 -0500650 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400651 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400652 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500653
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400654 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500655 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500656 applicationInfo.pApplicationName = "ANGLE";
657 applicationInfo.applicationVersion = 1;
658 applicationInfo.pEngineName = "ANGLE";
659 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700660
661 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
662 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
663 if (!enumerateInstanceVersion)
664 {
665 applicationInfo.apiVersion = VK_API_VERSION_1_0;
666 }
667 else
668 {
669 uint32_t apiVersion = VK_API_VERSION_1_0;
670 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
671 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
672 {
673 // Note: will need to revisit this with Vulkan 1.2+.
674 applicationInfo.apiVersion = VK_API_VERSION_1_1;
675 }
676 else
677 {
678 applicationInfo.apiVersion = VK_API_VERSION_1_0;
679 }
680 }
Jamie Madill327ba852016-11-30 12:38:28 -0500681
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400682 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500683 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
684 instanceInfo.flags = 0;
685 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500686
Jamie Madille09bd5d2016-11-29 16:20:35 -0500687 // Enable requested layers and extensions.
688 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
689 instanceInfo.ppEnabledExtensionNames =
690 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500691 instanceInfo.enabledLayerCount = enabledLayerCount;
692 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500693
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400694 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500695
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500696 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500697 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500698 // Try to use the newer EXT_debug_utils if it exists.
699 InitDebugUtilsEXTFunctions(mInstance);
700
701 // Create the messenger callback.
702 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
703
704 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
705 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
706 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
707 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
708 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
709 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
710 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
711 messengerInfo.pUserData = this;
712
713 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
714 &mDebugUtilsMessenger));
715 }
716 else if (enableDebugReport)
717 {
718 // Fallback to EXT_debug_report.
719 InitDebugReportEXTFunctions(mInstance);
720
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400721 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500722
723 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500724 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500725 debugReportInfo.pfnCallback = &DebugReportCallback;
726 debugReportInfo.pUserData = this;
727
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500728 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
729 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500730 }
731
Jamie Madill4d0bf552016-12-28 15:45:24 -0500732 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400733 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
734 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500735
736 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700737 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400738 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
739 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400740 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700741 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500742
Jamie Madill30b5d842018-08-31 17:19:12 -0400743 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
744
Jamie Madill4d0bf552016-12-28 15:45:24 -0500745 // Ensure we can find a graphics queue family.
746 uint32_t queueCount = 0;
747 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
748
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400749 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500750
751 mQueueFamilyProperties.resize(queueCount);
752 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
753 mQueueFamilyProperties.data());
754
Jamie Madillb980c562018-11-27 11:34:27 -0500755 size_t graphicsQueueFamilyCount = false;
756 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500757 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500758 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
759 {
760 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500761 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500762 {
763 ASSERT(queueInfo.queueCount > 0);
764 graphicsQueueFamilyCount++;
765 if (firstGraphicsQueueFamily == 0)
766 {
767 firstGraphicsQueueFamily = familyIndex;
768 }
769 break;
770 }
771 }
772
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400773 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500774
775 // If only one queue family, go ahead and initialize the device. If there is more than one
776 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
777 if (graphicsQueueFamilyCount == 1)
778 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400779 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500780 }
781
Jamie Madill035fd6b2017-10-03 15:43:22 -0400782 // Store the physical device memory properties so we can find the right memory pools.
783 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500784
Jamie Madill06ca6342018-07-12 15:56:53 -0400785 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500786
Jamie Madill6a89d222017-11-02 11:59:51 -0400787 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500788 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400789
Jamie Madill7c985f52018-11-29 18:16:17 -0500790 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400791}
792
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400793angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500794{
795 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400796 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400797 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500798
799 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
800 if (deviceLayerCount > 0)
801 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400802 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
803 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500804 }
805
806 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400807 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
808 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500809
810 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
811 if (deviceExtensionCount > 0)
812 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400813 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
814 &deviceExtensionCount,
815 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500816 }
817
Yuly Novikov199f4292018-01-19 19:04:05 -0500818 const char *const *enabledLayerNames = nullptr;
819 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500820 if (mEnableValidationLayers)
821 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500822 mEnableValidationLayers = GetAvailableValidationLayers(
823 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500824 }
825
826 std::vector<const char *> enabledDeviceExtensions;
827 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
828
Ian Elliottbcb78902018-12-19 11:46:29 -0700829 initFeatures(deviceExtensionProps);
830 mFeaturesInitialized = true;
831
Luc Ferronbf6dc372018-06-28 15:24:19 -0400832 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700833 if ((getFeatures().flipViewportY) &&
834 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400835 {
836 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
837 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700838 if (getFeatures().supportsIncrementalPresent)
839 {
840 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
841 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400842
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400843 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500844
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400845 // Select additional features to be enabled
846 VkPhysicalDeviceFeatures enabledFeatures = {};
847 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500848 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400849
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400850 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500851
852 float zeroPriority = 0.0f;
853
854 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500855 queueCreateInfo.flags = 0;
856 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
857 queueCreateInfo.queueCount = 1;
858 queueCreateInfo.pQueuePriorities = &zeroPriority;
859
860 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400861 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862
Jamie Madill50cf2be2018-06-15 09:46:57 -0400863 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400864 createInfo.flags = 0;
865 createInfo.queueCreateInfoCount = 1;
866 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500867 createInfo.enabledLayerCount = enabledLayerCount;
868 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500869 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
870 createInfo.ppEnabledExtensionNames =
871 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400872 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400874 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500875
876 mCurrentQueueFamilyIndex = queueFamilyIndex;
877
878 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
879
880 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400881 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500882 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
883 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
884 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500885
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000886 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400887
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400888 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500889 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500890
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400891 // Initialize the submission semaphore pool.
892 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
893
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400894#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
895 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
896 ASSERT(platform);
897
898 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
899 // platform discovery.
900 const unsigned char *gpuEventsEnabled =
901 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
902 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
903#endif
904
905 if (mGpuEventsEnabled)
906 {
907 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
908 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
909 vk::kDefaultTimestampQueryPoolSize));
910 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
911 }
912
Jamie Madill7c985f52018-11-29 18:16:17 -0500913 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500914}
915
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400916angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400917 VkSurfaceKHR surface,
918 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500919{
920 // We've already initialized a device, and can't re-create it unless it's never been used.
921 // TODO(jmadill): Handle the re-creation case if necessary.
922 if (mDevice != VK_NULL_HANDLE)
923 {
924 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
925
926 // Check if the current device supports present on this surface.
927 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400928 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400929 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500930 surface, &supportsPresent));
931
Jamie Madill6cad7732018-07-11 09:01:17 -0400932 if (supportsPresent == VK_TRUE)
933 {
934 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500935 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400936 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500937 }
938
939 // Find a graphics and present queue.
940 Optional<uint32_t> newPresentQueue;
941 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500942 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500943 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
944 {
945 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500946 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500947 {
948 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400949 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
950 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500951
952 if (supportsPresent == VK_TRUE)
953 {
954 newPresentQueue = queueIndex;
955 break;
956 }
957 }
958 }
959
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400960 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
961 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500962
Jamie Madill6cad7732018-07-11 09:01:17 -0400963 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -0500964 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500965}
966
967std::string RendererVk::getVendorString() const
968{
Olli Etuahoc6a06182018-04-13 14:11:46 +0300969 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500970}
971
Jamie Madille09bd5d2016-11-29 16:20:35 -0500972std::string RendererVk::getRendererDescription() const
973{
Jamie Madill4d0bf552016-12-28 15:45:24 -0500974 std::stringstream strstr;
975
976 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
977
978 strstr << "Vulkan ";
979 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
980 strstr << VK_VERSION_MINOR(apiVersion) << ".";
981 strstr << VK_VERSION_PATCH(apiVersion);
982
Olli Etuahoc6a06182018-04-13 14:11:46 +0300983 strstr << "(";
984
985 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
986 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
987 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
988 // driver detection.
989 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
990 {
991 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
992 }
993
Geoff Langa7af56b2018-12-14 14:20:28 -0500994 strstr << mPhysicalDeviceProperties.deviceName;
995 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
996
997 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -0500998
999 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001000}
1001
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001002gl::Version RendererVk::getMaxSupportedESVersion() const
1003{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001004 // Current highest supported version
1005 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1006 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001007
Geoff Lang0c2c9232019-01-14 16:01:38 -05001008 // Vulkan inherited queries are required to support any GL query type
1009 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001010 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001011 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001012 }
1013
Geoff Lang0c2c9232019-01-14 16:01:38 -05001014 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001015}
1016
Ian Elliottbcb78902018-12-19 11:46:29 -07001017void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001018{
Jamie Madillb36a4812018-09-25 10:15:11 -04001019// Use OpenGL line rasterization rules by default.
1020// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1021#if defined(ANGLE_PLATFORM_ANDROID)
1022 mFeatures.basicGLLineRasterization = false;
1023#else
Jamie Madill12222072018-07-11 14:59:48 -04001024 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001025#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001026
Ian Elliott52f5da42018-12-21 09:02:09 -07001027 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1028 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001029 {
1030 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1031 // investigation. http://anglebug.com/2728
1032 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1033 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001034
1035#ifdef ANGLE_PLATFORM_WINDOWS
1036 // http://anglebug.com/2838
1037 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001038
1039 // http://anglebug.com/3055
1040 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001041#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001042
1043 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1044 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001045
1046 // Work around incorrect NVIDIA point size range clamping.
1047 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1048 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1049 {
1050 mFeatures.clampPointSize = true;
1051 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001052
1053#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001054 // Work around ineffective compute-graphics barriers on Nexus 5X.
1055 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1056 // http://anglebug.com/3019
1057 mFeatures.flushAfterVertexConversion =
1058 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001059#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001060
1061 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1062 {
1063 mFeatures.supportsIncrementalPresent = true;
1064 }
Jamie Madill12222072018-07-11 14:59:48 -04001065}
1066
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001067void RendererVk::initPipelineCacheVkKey()
1068{
1069 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1070 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1071 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1072 // there is no '\0' in the result.
1073 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1074 {
1075 hashStream << std::hex << c;
1076 }
1077 // Add the vendor and device id too for good measure.
1078 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1079 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1080
1081 const std::string &hashString = hashStream.str();
1082 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1083 hashString.length(), mPipelineCacheVkBlobKey.data());
1084}
1085
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001086angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001087{
1088 initPipelineCacheVkKey();
1089
1090 egl::BlobCache::Value initialData;
1091 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1092 mPipelineCacheVkBlobKey, &initialData);
1093
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001094 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001095
1096 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001097 pipelineCacheCreateInfo.flags = 0;
1098 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1099 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1100
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001101 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001102 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001103}
1104
Jamie Madillacccc6c2016-05-03 17:22:10 -04001105void RendererVk::ensureCapsInitialized() const
1106{
1107 if (!mCapsInitialized)
1108 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001109 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1110 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1111 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001112 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001113 mCapsInitialized = true;
1114 }
1115}
1116
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001117void RendererVk::getSubmitWaitSemaphores(
1118 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001119 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1120 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001121{
1122 if (mSubmitLastSignaledSemaphore.getSemaphore())
1123 {
1124 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001125 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001126
1127 // Return the semaphore to the pool (which will remain valid and unused until the
1128 // queue it's about to be waited on has finished execution).
1129 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1130 }
1131
1132 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1133 {
1134 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001135 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1136
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001137 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1138 }
1139 mSubmitWaitSemaphores.clear();
1140}
1141
Jamie Madillacccc6c2016-05-03 17:22:10 -04001142const gl::Caps &RendererVk::getNativeCaps() const
1143{
1144 ensureCapsInitialized();
1145 return mNativeCaps;
1146}
1147
1148const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1149{
1150 ensureCapsInitialized();
1151 return mNativeTextureCaps;
1152}
1153
1154const gl::Extensions &RendererVk::getNativeExtensions() const
1155{
1156 ensureCapsInitialized();
1157 return mNativeExtensions;
1158}
1159
1160const gl::Limitations &RendererVk::getNativeLimitations() const
1161{
1162 ensureCapsInitialized();
1163 return mNativeLimitations;
1164}
1165
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001166uint32_t RendererVk::getMaxActiveTextures()
1167{
1168 // TODO(lucferron): expose this limitation to GL in Context Caps
1169 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1170 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1171}
1172
Jamie Madill49ac74b2017-12-21 14:42:33 -05001173const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001174{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001175 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001176}
1177
Jamie Madill21061022018-07-12 23:56:30 -04001178angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001179{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001180 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001181 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001182 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1183
Luc Ferron1617e692018-07-11 11:08:19 -04001184 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1185 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001186
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001187 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001188 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1189 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001190
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001191 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001192 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001193 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1194 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001195 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001196 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001197 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001198 submitInfo.signalSemaphoreCount = 0;
1199 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001200
Jamie Madill21061022018-07-12 23:56:30 -04001201 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001202 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001203
Jamie Madill4c26fc22017-02-24 11:04:10 -05001204 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001205 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001206 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001207
1208 if (mGpuEventsEnabled)
1209 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001210 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001211 while (mInFlightGpuEventQueries.size() > 0)
1212 {
1213 ANGLE_TRY(checkCompletedGpuEvents(context));
1214 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001215 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1216 // synchronization if there is no event to be adjusted (happens when finish() gets called
1217 // multiple times towards the end of the application).
1218 if (mGpuEvents.size() > 0)
1219 {
1220 ANGLE_TRY(synchronizeCpuGpuTime(context));
1221 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001222 }
1223
Jamie Madill7c985f52018-11-29 18:16:17 -05001224 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001225}
1226
Jamie Madill0c0dc342017-03-24 14:18:51 -04001227void RendererVk::freeAllInFlightResources()
1228{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001229 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001230 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001231 // On device loss we need to wait for fence to be signaled before destroying it
1232 if (mDeviceLost)
1233 {
1234 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1235 // If wait times out, it is probably not possible to recover from lost device
1236 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1237 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001238 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001239 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001240 }
1241 mInFlightCommands.clear();
1242
1243 for (auto &garbage : mGarbage)
1244 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001245 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001246 }
1247 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001248
1249 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001250}
1251
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001252angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001253{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001254 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001255
Jamie Madill49ac74b2017-12-21 14:42:33 -05001256 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001257 {
Yuly Novikov27780292018-11-09 11:19:49 -05001258 VkResult result = batch.fence.getStatus(mDevice);
1259 if (result == VK_NOT_READY)
1260 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001261 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001262 }
1263 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001264
Jamie Madill49ac74b2017-12-21 14:42:33 -05001265 ASSERT(batch.serial > mLastCompletedQueueSerial);
1266 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001267
Jamie Madill49ac74b2017-12-21 14:42:33 -05001268 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001269 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001270 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001271 }
1272
Jamie Madill49ac74b2017-12-21 14:42:33 -05001273 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001274
1275 size_t freeIndex = 0;
1276 for (; freeIndex < mGarbage.size(); ++freeIndex)
1277 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001278 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001279 break;
1280 }
1281
1282 // Remove the entries from the garbage list - they should be ready to go.
1283 if (freeIndex > 0)
1284 {
1285 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001286 }
1287
Jamie Madill7c985f52018-11-29 18:16:17 -05001288 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001289}
1290
Jamie Madill21061022018-07-12 23:56:30 -04001291angle::Result RendererVk::submitFrame(vk::Context *context,
1292 const VkSubmitInfo &submitInfo,
1293 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001294{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001295 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001296 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001297 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1298 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001299
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001300 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001301 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001302 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001303
Jamie Madill21061022018-07-12 23:56:30 -04001304 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001305
1306 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001307 batch.commandPool = std::move(mCommandPool);
1308 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001309
Jamie Madillbea35a62018-07-05 11:54:10 -04001310 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001311
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001312 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1313 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001314 // so the limit is larger than the expected number of images. The
1315 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001316 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001317
Jamie Madill85ca1892019-01-16 13:27:15 -05001318 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001319
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001320 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001321
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001322 if (mGpuEventsEnabled)
1323 {
1324 ANGLE_TRY(checkCompletedGpuEvents(context));
1325 }
1326
Jamie Madill49ac74b2017-12-21 14:42:33 -05001327 // Simply null out the command buffer here - it was allocated using the command pool.
1328 commandBuffer.releaseHandle();
1329
1330 // Reallocate the command pool for next frame.
1331 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001332 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001333 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001334 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001335 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001336
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001337 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001338 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001339}
1340
Jamie Madill85ca1892019-01-16 13:27:15 -05001341void RendererVk::nextSerial()
1342{
1343 // Increment the queue serial. If this fails, we should restart ANGLE.
1344 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1345 mCurrentQueueSerial = mQueueSerialFactory.generate();
1346
1347 // Notify the Contexts that they should be starting new command buffers.
1348 // We use one command pool per serial/submit associated with this VkQueue. We can also
1349 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1350 // check for a new serial when starting a new command buffer. We just check that the current
1351 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1352 // using this VkQueue that they their current command buffer is no longer valid.
1353 for (gl::Context *context : mDisplay->getContextSet())
1354 {
1355 ContextVk *contextVk = vk::GetImpl(context);
1356 contextVk->onCommandBufferFinished();
1357 }
1358}
1359
Jamie Madillaaca96e2018-06-12 10:19:48 -04001360bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001361{
1362 return serial > mLastCompletedQueueSerial;
1363}
1364
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001365angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1366{
1367 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1368 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001369 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001370 }
1371
1372 // Find the first batch with serial equal to or bigger than given serial (note that
1373 // the batch serials are unique, otherwise upper-bound would have been necessary).
1374 size_t batchIndex = mInFlightCommands.size() - 1;
1375 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1376 {
1377 if (mInFlightCommands[i].serial >= serial)
1378 {
1379 batchIndex = i;
1380 break;
1381 }
1382 }
1383 const CommandBatch &batch = mInFlightCommands[batchIndex];
1384
1385 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001386 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001387
1388 // Clean up finished batches.
1389 return checkCompletedCommands(context);
1390}
1391
Jamie Madill21061022018-07-12 23:56:30 -04001392angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1393 const vk::RenderPassDesc &desc,
1394 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001395{
Jamie Madill21061022018-07-12 23:56:30 -04001396 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001397 renderPassOut);
1398}
1399
Jamie Madill21061022018-07-12 23:56:30 -04001400angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1401 const vk::RenderPassDesc &desc,
1402 const vk::AttachmentOpsArray &ops,
1403 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001404{
Jamie Madill21061022018-07-12 23:56:30 -04001405 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001406 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001407}
1408
Jamie Madilla5e06072018-05-18 14:36:05 -04001409vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001410{
Jamie Madilla5e06072018-05-18 14:36:05 -04001411 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001412}
1413
Jamie Madill21061022018-07-12 23:56:30 -04001414angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001415{
Jamie Madill21061022018-07-12 23:56:30 -04001416 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001417 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001418}
1419
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001420angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001421{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001422 if (mCommandGraph.empty())
1423 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001424 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001425 }
1426
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001427 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1428
Jamie Madillbea35a62018-07-05 11:54:10 -04001429 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1430 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001431
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001432 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001433 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1434 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001435
1436 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1437 // will be waited on.
1438 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001439
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001440 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001441 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001442 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1443 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001444 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001445 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001446 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001447 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001448 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001449
Jamie Madill21061022018-07-12 23:56:30 -04001450 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001451
Jamie Madill7c985f52018-11-29 18:16:17 -05001452 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001453}
1454
Jamie Madill78feddc2018-04-27 11:45:05 -04001455Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001456{
Jamie Madill78feddc2018-04-27 11:45:05 -04001457 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001458}
1459
Jamie Madill21061022018-07-12 23:56:30 -04001460angle::Result RendererVk::getDescriptorSetLayout(
1461 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001462 const vk::DescriptorSetLayoutDesc &desc,
1463 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1464{
Jamie Madill21061022018-07-12 23:56:30 -04001465 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001466}
1467
Jamie Madill21061022018-07-12 23:56:30 -04001468angle::Result RendererVk::getPipelineLayout(
1469 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001470 const vk::PipelineLayoutDesc &desc,
1471 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1472 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1473{
Jamie Madill21061022018-07-12 23:56:30 -04001474 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001475 pipelineLayoutOut);
1476}
1477
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001478angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1479{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001480 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001481
1482 if (--mPipelineCacheVkUpdateTimeout > 0)
1483 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001484 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001485 }
1486
1487 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1488
1489 // Get the size of the cache.
1490 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001491 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001492 if (result != VK_INCOMPLETE)
1493 {
1494 ANGLE_VK_TRY(displayVk, result);
1495 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001496
1497 angle::MemoryBuffer *pipelineCacheData = nullptr;
1498 ANGLE_VK_CHECK_ALLOC(displayVk,
1499 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1500
1501 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001502 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001503 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1504 // was determined just above), so receiving it hints at an implementation bug we would want
1505 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001506 ASSERT(result != VK_INCOMPLETE);
1507 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001508
1509 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1510 // the buffer to avoid leaking garbage memory.
1511 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1512 if (pipelineCacheSize < originalPipelineCacheSize)
1513 {
1514 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1515 originalPipelineCacheSize - pipelineCacheSize);
1516 }
1517
1518 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1519
Jamie Madill7c985f52018-11-29 18:16:17 -05001520 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001521}
1522
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001523angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1524 const vk::Semaphore **outSemaphore)
1525{
1526 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1527
1528 vk::SemaphoreHelper semaphore;
1529 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1530
1531 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1532 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1533
Jamie Madill7c985f52018-11-29 18:16:17 -05001534 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001535}
1536
1537const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1538{
1539 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1540
1541 // Return the semaphore to the pool (which will remain valid and unused until the
1542 // queue it's about to be waited on has finished execution). The caller is about
1543 // to wait on it.
1544 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1545
1546 return semaphore;
1547}
1548
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001549angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1550{
1551 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1552 // that seems impossible, so instead, we are going to make a small submission with just a
1553 // timestamp query. First, the disjoint timer query extension says:
1554 //
1555 // > This will return the GL time after all previous commands have reached the GL server but
1556 // have not yet necessarily executed.
1557 //
1558 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1559 // The wording allows us to make a submission to get the timestamp without performing a flush.
1560 //
1561 // Second:
1562 //
1563 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1564 // object target, applications can measure the latency between when commands reach the GL server
1565 // and when they are realized in the framebuffer.
1566 //
1567 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1568 // GPU bubble. This function directly generates a command buffer and submits it instead of
1569 // using the other member functions. This is to avoid changing any state, such as the queue
1570 // serial.
1571
1572 // Create a query used to receive the GPU timestamp
1573 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1574 vk::QueryHelper timestampQuery;
1575 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1576 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1577
1578 // Record the command buffer
1579 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1580 vk::CommandBuffer &commandBuffer = commandBatch.get();
1581
1582 VkCommandBufferAllocateInfo commandBufferInfo = {};
1583 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1584 commandBufferInfo.commandPool = mCommandPool.getHandle();
1585 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1586 commandBufferInfo.commandBufferCount = 1;
1587
Yuly Novikov27780292018-11-09 11:19:49 -05001588 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001589
1590 VkCommandBufferBeginInfo beginInfo = {};
1591 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1592 beginInfo.flags = 0;
1593 beginInfo.pInheritanceInfo = nullptr;
1594
Yuly Novikov27780292018-11-09 11:19:49 -05001595 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001596
1597 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1598 timestampQuery.getQuery(), 1);
1599 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1600 timestampQuery.getQueryPool()->getHandle(),
1601 timestampQuery.getQuery());
1602
Yuly Novikov27780292018-11-09 11:19:49 -05001603 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001604
1605 // Create fence for the submission
1606 VkFenceCreateInfo fenceInfo = {};
1607 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1608 fenceInfo.flags = 0;
1609
1610 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001611 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001612
1613 // Submit the command buffer
1614 VkSubmitInfo submitInfo = {};
1615 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1616 submitInfo.waitSemaphoreCount = 0;
1617 submitInfo.pWaitSemaphores = nullptr;
1618 submitInfo.pWaitDstStageMask = nullptr;
1619 submitInfo.commandBufferCount = 1;
1620 submitInfo.pCommandBuffers = commandBuffer.ptr();
1621 submitInfo.signalSemaphoreCount = 0;
1622 submitInfo.pSignalSemaphores = nullptr;
1623
1624 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1625
1626 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1627 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001628 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001629
1630 // Get the query results
1631 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1632
Yuly Novikov27780292018-11-09 11:19:49 -05001633 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1634 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1635 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001636
1637 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1638
Jamie Madill7c985f52018-11-29 18:16:17 -05001639 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001640}
1641
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001642// These functions look at the mandatory format for support, and fallback to querying the device (if
1643// necessary) to test the availability of the bits.
1644bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1645 const VkFormatFeatureFlags featureBits)
1646{
1647 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1648}
1649
1650bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1651 const VkFormatFeatureFlags featureBits)
1652{
1653 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1654}
1655
1656bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1657{
1658 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1659}
1660
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001661angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1662{
1663 ASSERT(mGpuEventsEnabled);
1664
1665 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1666 ASSERT(platform);
1667
1668 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1669 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1670 //
1671 // CPU GPU
1672 //
1673 // Record command buffer
1674 // with timestamp query
1675 //
1676 // Submit command buffer
1677 //
1678 // Post-submission work Begin execution
1679 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001680 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001681 //
1682 // ???? End execution
1683 //
1684 // ???? Return query results
1685 //
1686 // ????
1687 //
1688 // Get query results
1689 //
1690 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1691 // finished post-submission work while the GPU is executing in parallel. With no further work,
1692 // querying CPU timestamps before submission and after getting query results give the bounds to
1693 // Tgpu, which could be quite large.
1694 //
1695 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1696 // reduce this range. This function implements the following procedure:
1697 //
1698 // CPU GPU
1699 //
1700 // Record command buffer
1701 // with timestamp query
1702 //
1703 // Submit command buffer
1704 //
1705 // Post-submission work Begin execution
1706 //
1707 // ???? Set Event GPUReady
1708 //
1709 // Wait on Event GPUReady Wait on Event CPUReady
1710 //
1711 // Get CPU Time Ts Wait on Event CPUReady
1712 //
1713 // Set Event CPUReady Wait on Event CPUReady
1714 //
1715 // Get CPU Time Tcpu Get GPU Time Tgpu
1716 //
1717 // Wait on Event GPUDone Set Event GPUDone
1718 //
1719 // Get CPU Time Te End Execution
1720 //
1721 // Idle Return query results
1722 //
1723 // Get query results
1724 //
1725 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1726 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1727 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1728 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1729 // calibration.
1730 //
1731 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1732
1733 // Make sure nothing is running
1734 ASSERT(mCommandGraph.empty());
1735
1736 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1737
1738 // Create a query used to receive the GPU timestamp
1739 vk::QueryHelper timestampQuery;
1740 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1741
1742 // Create the three events
1743 VkEventCreateInfo eventCreateInfo = {};
1744 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1745 eventCreateInfo.flags = 0;
1746
1747 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001748 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1749 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1750 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001751
1752 constexpr uint32_t kRetries = 10;
1753
1754 // Time suffixes used are S for seconds and Cycles for cycles
1755 double tightestRangeS = 1e6f;
1756 double TcpuS = 0;
1757 uint64_t TgpuCycles = 0;
1758 for (uint32_t i = 0; i < kRetries; ++i)
1759 {
1760 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001761 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1762 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1763 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001764
1765 // Record the command buffer
1766 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1767 vk::CommandBuffer &commandBuffer = commandBatch.get();
1768
1769 VkCommandBufferAllocateInfo commandBufferInfo = {};
1770 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1771 commandBufferInfo.commandPool = mCommandPool.getHandle();
1772 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1773 commandBufferInfo.commandBufferCount = 1;
1774
Yuly Novikov27780292018-11-09 11:19:49 -05001775 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001776
1777 VkCommandBufferBeginInfo beginInfo = {};
1778 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1779 beginInfo.flags = 0;
1780 beginInfo.pInheritanceInfo = nullptr;
1781
Yuly Novikov27780292018-11-09 11:19:49 -05001782 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001783
1784 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1785 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1786 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1787 nullptr);
1788
1789 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1790 timestampQuery.getQuery(), 1);
1791 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1792 timestampQuery.getQueryPool()->getHandle(),
1793 timestampQuery.getQuery());
1794
1795 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1796
Yuly Novikov27780292018-11-09 11:19:49 -05001797 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001798
1799 // Submit the command buffer
1800 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1801 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1802 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1803
1804 VkSubmitInfo submitInfo = {};
1805 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1806 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1807 submitInfo.pWaitSemaphores = waitSemaphores.data();
1808 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1809 submitInfo.commandBufferCount = 1;
1810 submitInfo.pCommandBuffers = commandBuffer.ptr();
1811 submitInfo.signalSemaphoreCount = 0;
1812 submitInfo.pSignalSemaphores = nullptr;
1813
1814 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1815
1816 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001817 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001818 do
1819 {
Yuly Novikov27780292018-11-09 11:19:49 -05001820 result = gpuReady.get().getStatus(mDevice);
1821 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1822 {
1823 ANGLE_VK_TRY(context, result);
1824 }
1825 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001826
1827 double TsS = platform->monotonicallyIncreasingTime(platform);
1828
1829 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001830 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001831 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1832
1833 // Wait for GPU to be done. Another short busy wait.
1834 do
1835 {
Yuly Novikov27780292018-11-09 11:19:49 -05001836 result = gpuDone.get().getStatus(mDevice);
1837 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1838 {
1839 ANGLE_VK_TRY(context, result);
1840 }
1841 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001842
1843 double TeS = platform->monotonicallyIncreasingTime(platform);
1844
1845 // Get the query results
1846 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1847
1848 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1849
1850 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001851 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1852 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1853 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001854
1855 // Use the first timestamp queried as origin.
1856 if (mGpuEventTimestampOrigin == 0)
1857 {
1858 mGpuEventTimestampOrigin = gpuTimestampCycles;
1859 }
1860
1861 // Take these CPU and GPU timestamps if there is better confidence.
1862 double confidenceRangeS = TeS - TsS;
1863 if (confidenceRangeS < tightestRangeS)
1864 {
1865 tightestRangeS = confidenceRangeS;
1866 TcpuS = cpuTimestampS;
1867 TgpuCycles = gpuTimestampCycles;
1868 }
1869 }
1870
1871 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1872
1873 // timestampPeriod gives nanoseconds/cycle.
1874 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1875 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1876 1'000'000'000.0;
1877
1878 flushGpuEvents(TgpuS, TcpuS);
1879
1880 mGpuClockSync.gpuTimestampS = TgpuS;
1881 mGpuClockSync.cpuTimestampS = TcpuS;
1882
Jamie Madill7c985f52018-11-29 18:16:17 -05001883 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001884}
1885
1886angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1887 vk::CommandBuffer *commandBuffer,
1888 char phase,
1889 const char *name)
1890{
1891 ASSERT(mGpuEventsEnabled);
1892
1893 GpuEventQuery event;
1894
1895 event.name = name;
1896 event.phase = phase;
1897 event.serial = mCurrentQueueSerial;
1898
1899 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1900
1901 commandBuffer->resetQueryPool(
1902 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1903 commandBuffer->writeTimestamp(
1904 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1905 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1906
1907 mInFlightGpuEventQueries.push_back(std::move(event));
1908
Jamie Madill7c985f52018-11-29 18:16:17 -05001909 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001910}
1911
1912angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1913{
1914 ASSERT(mGpuEventsEnabled);
1915
1916 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1917 ASSERT(platform);
1918
1919 int finishedCount = 0;
1920
1921 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1922 {
1923 // Only check the timestamp query if the submission has finished.
1924 if (eventQuery.serial > mLastCompletedQueueSerial)
1925 {
1926 break;
1927 }
1928
1929 // See if the results are available.
1930 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001931 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1932 ->getResults(mDevice, eventQuery.queryIndex, 1,
1933 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1934 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1935 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001936 {
1937 break;
1938 }
Yuly Novikov27780292018-11-09 11:19:49 -05001939 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001940
1941 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1942
1943 GpuEvent event;
1944 event.gpuTimestampCycles = gpuTimestampCycles;
1945 event.name = eventQuery.name;
1946 event.phase = eventQuery.phase;
1947
1948 mGpuEvents.emplace_back(event);
1949
1950 ++finishedCount;
1951 }
1952
1953 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
1954 mInFlightGpuEventQueries.begin() + finishedCount);
1955
Jamie Madill7c985f52018-11-29 18:16:17 -05001956 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001957}
1958
1959void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
1960{
1961 if (mGpuEvents.size() == 0)
1962 {
1963 return;
1964 }
1965
1966 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1967 ASSERT(platform);
1968
1969 // Find the slope of the clock drift for adjustment
1970 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
1971 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
1972 double gpuSyncDriftSlope = 0;
1973
1974 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
1975 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
1976
1977 // No gpu trace events should have been generated before the clock sync, so if there is no
1978 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
1979 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
1980 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
1981
1982 gpuSyncDriftSlope =
1983 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
1984
1985 for (const GpuEvent &event : mGpuEvents)
1986 {
1987 double gpuTimestampS =
1988 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
1989 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
1990
1991 // Account for clock drift.
1992 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
1993
1994 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
1995 // for.
1996 static long long eventId = 1;
1997 static const unsigned char *categoryEnabled =
1998 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
1999 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2000 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2001 }
2002
2003 mGpuEvents.clear();
2004}
2005
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002006template <VkFormatFeatureFlags VkFormatProperties::*features>
2007bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2008{
2009 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2010 VkFormatProperties &deviceProperties = mFormatProperties[format];
2011
2012 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2013 {
2014 // If we don't have the actual device features, see if the requested features are mandatory.
2015 // If so, there's no need to query the device.
2016 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2017 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2018 {
2019 return true;
2020 }
2021
2022 // Otherwise query the format features and cache it.
2023 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2024 }
2025
2026 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2027}
2028
Jamie Madillaaca96e2018-06-12 10:19:48 -04002029uint32_t GetUniformBufferDescriptorCount()
2030{
2031 return kUniformBufferDescriptorsPerDescriptorSet;
2032}
2033
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002034} // namespace rx