blob: c4d0d2de4400923c71ac6c26c18b4ac9a5054160 [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"
Shahbaz Youssefi61656022018-10-24 15:00:50 -040034#include "third_party/trace_event/trace_event.h"
35
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070036// Consts
37namespace
38{
Jamie Madill7c985f52018-11-29 18:16:17 -050039const uint32_t kMockVendorID = 0xba5eba11;
40const uint32_t kMockDeviceID = 0xf005ba11;
41constexpr char kMockDeviceName[] = "Vulkan Mock Device";
42constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050043constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070044} // anonymous namespace
45
Jamie Madill9e54b5a2016-05-25 12:57:39 -040046namespace rx
47{
48
Jamie Madille09bd5d2016-11-29 16:20:35 -050049namespace
50{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040051// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
52// one for the vertex shader.
53constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040054// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050055constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040056// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050057constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Ian Elliott356d26c2019-02-11 11:27:01 -070058// Per the Vulkan specification, as long as Vulkan 1.1+ is returned by vkEnumerateInstanceVersion,
59// ANGLE must indicate the highest version of Vulkan functionality that it uses. The Vulkan
60// validation layers will issue messages for any core functionality that requires a higher version.
61// This value must be increased whenever ANGLE starts using functionality from a newer core
62// version of Vulkan.
63constexpr uint32_t kPreferredVulkanAPIVersion = VK_API_VERSION_1_1;
Jamie Madille09bd5d2016-11-29 16:20:35 -050064
Omar El Sheikh26c61b22018-06-29 12:50:59 -060065bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
66{
67#if !defined(ANGLE_PLATFORM_ANDROID)
68 // Mock ICD does not currently run on Android
69 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
70 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
71 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
72#else
73 return false;
74#endif // !defined(ANGLE_PLATFORM_ANDROID)
75}
76
Frank Henigman52047de2018-11-13 17:22:36 -050077bool StrLess(const char *a, const char *b)
Jamie Madille09bd5d2016-11-29 16:20:35 -050078{
Frank Henigman52047de2018-11-13 17:22:36 -050079 return strcmp(a, b) < 0;
Jamie Madille09bd5d2016-11-29 16:20:35 -050080}
81
Frank Henigman52047de2018-11-13 17:22:36 -050082bool ExtensionFound(const char *needle, const RendererVk::ExtensionNameList &haystack)
83{
84 // NOTE: The list must be sorted.
85 return std::binary_search(haystack.begin(), haystack.end(), needle, StrLess);
Tobin Ehlis3a181e32018-08-29 15:17:05 -060086}
87
Yuly Novikovdbbdf562019-02-27 19:48:16 -050088VkResult VerifyExtensionsPresent(const RendererVk::ExtensionNameList &haystack,
89 const RendererVk::ExtensionNameList &needles)
90{
91 // NOTE: The lists must be sorted.
92 if (std::includes(haystack.begin(), haystack.end(), needles.begin(), needles.end(), StrLess))
93 {
94 return VK_SUCCESS;
95 }
96 for (const char *needle : needles)
97 {
98 if (!ExtensionFound(needle, haystack))
99 {
100 ERR() << "Extension not supported: " << needle;
101 }
102 }
103 return VK_ERROR_EXTENSION_NOT_PRESENT;
104}
105
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500106// Array of Validation error/warning messages that will be ignored, should include bugID
Jamie Madill00f43c92019-02-09 11:41:12 -0500107constexpr const char *kSkippedMessages[] = {
108 // http://anglebug.com/2866
109 "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500110 // http://anglebug.com/2796
Jamie Madill00f43c92019-02-09 11:41:12 -0500111 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing",
112};
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500113
114// Suppress validation errors that are known
115// return "true" if given code/prefix/message is known, else return "false"
116bool IsIgnoredDebugMessage(const char *message)
117{
Michael Spang25839802019-01-30 18:02:51 -0500118 if (!message)
119 {
120 return false;
121 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500122 for (const char *msg : kSkippedMessages)
123 {
124 if (strstr(message, msg) != nullptr)
125 {
126 return true;
127 }
128 }
129 return false;
130}
131
132const char *GetVkObjectTypeName(VkObjectType type)
133{
134 switch (type)
135 {
136 case VK_OBJECT_TYPE_UNKNOWN:
137 return "Unknown";
138 case VK_OBJECT_TYPE_INSTANCE:
139 return "Instance";
140 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
141 return "Physical Device";
142 case VK_OBJECT_TYPE_DEVICE:
143 return "Device";
144 case VK_OBJECT_TYPE_QUEUE:
145 return "Queue";
146 case VK_OBJECT_TYPE_SEMAPHORE:
147 return "Semaphore";
148 case VK_OBJECT_TYPE_COMMAND_BUFFER:
149 return "Command Buffer";
150 case VK_OBJECT_TYPE_FENCE:
151 return "Fence";
152 case VK_OBJECT_TYPE_DEVICE_MEMORY:
153 return "Device Memory";
154 case VK_OBJECT_TYPE_BUFFER:
155 return "Buffer";
156 case VK_OBJECT_TYPE_IMAGE:
157 return "Image";
158 case VK_OBJECT_TYPE_EVENT:
159 return "Event";
160 case VK_OBJECT_TYPE_QUERY_POOL:
161 return "Query Pool";
162 case VK_OBJECT_TYPE_BUFFER_VIEW:
163 return "Buffer View";
164 case VK_OBJECT_TYPE_IMAGE_VIEW:
165 return "Image View";
166 case VK_OBJECT_TYPE_SHADER_MODULE:
167 return "Shader Module";
168 case VK_OBJECT_TYPE_PIPELINE_CACHE:
169 return "Pipeline Cache";
170 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
171 return "Pipeline Layout";
172 case VK_OBJECT_TYPE_RENDER_PASS:
173 return "Render Pass";
174 case VK_OBJECT_TYPE_PIPELINE:
175 return "Pipeline";
176 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
177 return "Descriptor Set Layout";
178 case VK_OBJECT_TYPE_SAMPLER:
179 return "Sampler";
180 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
181 return "Descriptor Pool";
182 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
183 return "Descriptor Set";
184 case VK_OBJECT_TYPE_FRAMEBUFFER:
185 return "Framebuffer";
186 case VK_OBJECT_TYPE_COMMAND_POOL:
187 return "Command Pool";
188 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
189 return "Sampler YCbCr Conversion";
190 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
191 return "Descriptor Update Template";
192 case VK_OBJECT_TYPE_SURFACE_KHR:
193 return "Surface";
194 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
195 return "Swapchain";
196 case VK_OBJECT_TYPE_DISPLAY_KHR:
197 return "Display";
198 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
199 return "Display Mode";
200 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
201 return "Debug Report Callback";
202 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
203 return "Object Table";
204 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
205 return "Indirect Commands Layout";
206 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
207 return "Debug Utils Messenger";
208 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
209 return "Validation Cache";
Shahbaz Youssefi38051222019-02-13 21:21:13 +0000210 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500211 return "Acceleration Structure";
212 default:
213 return "<Unrecognized>";
214 }
215}
216
217VKAPI_ATTR VkBool32 VKAPI_CALL
218DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
219 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
220 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
221 void *userData)
222{
Shahbaz Youssefi0c01e362019-02-13 21:27:23 +0000223 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
224 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
225 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
226
227 // Check if we even care about this message.
228 if ((messageSeverity & kSeveritiesToLog) == 0)
229 {
230 return VK_FALSE;
231 }
232
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500233 // See if it's an issue we are aware of and don't want to be spammed about.
234 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
235 {
236 return VK_FALSE;
237 }
238
239 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500240 if (callbackData->pMessageIdName)
241 {
242 log << "[ " << callbackData->pMessageIdName << " ] ";
243 }
244 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500245
246 // Aesthetic value based on length of the function name, line number, etc.
247 constexpr size_t kStartIndent = 28;
248
249 // Output the debug marker hierarchy under which this error has occured.
250 size_t indent = kStartIndent;
251 if (callbackData->queueLabelCount > 0)
252 {
253 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
254 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
255 {
256 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
257 << std::endl;
258 }
259 }
260 if (callbackData->cmdBufLabelCount > 0)
261 {
262 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
263 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
264 {
265 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
266 << std::endl;
267 }
268 }
269 // Output the objects involved in this error message.
270 if (callbackData->objectCount > 0)
271 {
272 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
273 {
274 const char *objectName = callbackData->pObjects[i].pObjectName;
275 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
276 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
277 log << std::string(indent, ' ') << "Object: ";
278 if (objectHandle == 0)
279 {
280 log << "VK_NULL_HANDLE";
281 }
282 else
283 {
284 log << "0x" << std::hex << objectHandle << std::dec;
285 }
286 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
287 if (objectName)
288 {
289 log << " [" << objectName << "]";
290 }
291 log << std::endl;
292 }
293 }
294
Jamie Madill54ed8f02019-02-11 12:32:04 -0500295 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
296 std::string msg = log.str();
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500297
298 if (isError)
299 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500300 ERR() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500301 }
302 else
303 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500304 WARN() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500305 }
306
307 return VK_FALSE;
308}
309
Yuly Novikov199f4292018-01-19 19:04:05 -0500310VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
311 VkDebugReportObjectTypeEXT objectType,
312 uint64_t object,
313 size_t location,
314 int32_t messageCode,
315 const char *layerPrefix,
316 const char *message,
317 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500318{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600319 if (IsIgnoredDebugMessage(message))
320 {
321 return VK_FALSE;
322 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500323 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
324 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500325 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500326#if !defined(NDEBUG)
327 // Abort the call in Debug builds.
328 return VK_TRUE;
329#endif
330 }
331 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
332 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500333 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500334 }
335 else
336 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500337 // Uncomment this if you want Vulkan spam.
338 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500339 }
340
341 return VK_FALSE;
342}
343
Yuly Novikov199f4292018-01-19 19:04:05 -0500344// If we're loading the validation layers, we could be running from any random directory.
345// Change to the executable directory so we can find the layers, then change back to the
346// previous directory to be safe we don't disrupt the application.
347class ScopedVkLoaderEnvironment : angle::NonCopyable
348{
349 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600350 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
351 : mEnableValidationLayers(enableValidationLayers),
352 mEnableMockICD(enableMockICD),
353 mChangedCWD(false),
354 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500355 {
356// Changing CWD and setting environment variables makes no sense on Android,
357// since this code is a part of Java application there.
358// Android Vulkan loader doesn't need this either.
Michael Spang229fc832019-01-21 18:09:15 -0500359#if !defined(ANGLE_PLATFORM_ANDROID) && !defined(ANGLE_PLATFORM_FUCHSIA)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600360 if (enableMockICD)
361 {
362 // Override environment variable to use built Mock ICD
363 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
364 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
365 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
366 if (!mChangedICDPath)
367 {
368 ERR() << "Error setting Path for Mock/Null Driver.";
369 mEnableMockICD = false;
370 }
371 }
Jamie Madill46848422018-08-09 10:46:06 -0400372 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500373 {
374 const auto &cwd = angle::GetCWD();
375 if (!cwd.valid())
376 {
377 ERR() << "Error getting CWD for Vulkan layers init.";
378 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400379 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500380 }
381 else
382 {
383 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500384 std::string exeDir = angle::GetExecutableDirectory();
385 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500386 if (!mChangedCWD)
387 {
388 ERR() << "Error setting CWD for Vulkan layers init.";
389 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400390 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500391 }
392 }
393 }
394
395 // Override environment variable to use the ANGLE layers.
396 if (mEnableValidationLayers)
397 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700398 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500399 {
400 ERR() << "Error setting environment for Vulkan layers init.";
401 mEnableValidationLayers = false;
402 }
403 }
404#endif // !defined(ANGLE_PLATFORM_ANDROID)
405 }
406
407 ~ScopedVkLoaderEnvironment()
408 {
409 if (mChangedCWD)
410 {
411#if !defined(ANGLE_PLATFORM_ANDROID)
412 ASSERT(mPreviousCWD.valid());
413 angle::SetCWD(mPreviousCWD.value().c_str());
414#endif // !defined(ANGLE_PLATFORM_ANDROID)
415 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600416 if (mChangedICDPath)
417 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600418 if (mPreviousICDPath.value().empty())
419 {
420 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
421 }
422 else
423 {
424 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
425 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500427 }
428
Jamie Madillaaca96e2018-06-12 10:19:48 -0400429 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500430
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600431 bool canEnableMockICD() const { return mEnableMockICD; }
432
Yuly Novikov199f4292018-01-19 19:04:05 -0500433 private:
434 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600435 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500436 bool mChangedCWD;
437 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600438 bool mChangedICDPath;
439 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500440};
441
Jamie Madill21061022018-07-12 23:56:30 -0400442void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
443 bool preferMockICD,
444 VkPhysicalDevice *physicalDeviceOut,
445 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
446{
447 ASSERT(!physicalDevices.empty());
448 if (preferMockICD)
449 {
450 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
451 {
452 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
453 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
454 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
455 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
456 {
457 *physicalDeviceOut = physicalDevice;
458 return;
459 }
460 }
461 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
462 "physicalDevice instead.";
463 }
464
465 // Fall back to first device.
466 *physicalDeviceOut = physicalDevices[0];
467 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
468}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400469
470// Initially dumping the command graphs is disabled.
471constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700472
Jamie Madille09bd5d2016-11-29 16:20:35 -0500473} // anonymous namespace
474
Jamie Madill49ac74b2017-12-21 14:42:33 -0500475// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400476RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500477
Jamie Madillaaca96e2018-06-12 10:19:48 -0400478RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500479
480RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000481 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500482{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500483
484RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
485{
486 std::swap(commandPool, other.commandPool);
487 std::swap(fence, other.fence);
488 std::swap(serial, other.serial);
489 return *this;
490}
491
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000492void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400493{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000494 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400495 fence.destroy(device);
496}
497
Jamie Madill9f2a8612017-11-30 12:43:09 -0500498// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500499RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400500 : mDisplay(nullptr),
501 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700502 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500503 mInstance(VK_NULL_HANDLE),
504 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400505 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500506 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500507 mDebugReportCallback(VK_NULL_HANDLE),
508 mPhysicalDevice(VK_NULL_HANDLE),
509 mQueue(VK_NULL_HANDLE),
510 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
Frank Henigman52047de2018-11-13 17:22:36 -0500511 mMaxVertexAttribDivisor(1),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500512 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400513 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400514 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400515 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400516 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400517 mCommandGraph(kEnableCommandGraphDiagnostics),
518 mGpuEventsEnabled(false),
519 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
520 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500521{
522 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
523 mFormatProperties.fill(invalid);
524}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400525
Jamie Madillb980c562018-11-27 11:34:27 -0500526RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400527
528void RendererVk::onDestroy(vk::Context *context)
529{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500530 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500531 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500532 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400533 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500534 }
535
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100536 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500537
Jamie Madillc7918ce2018-06-13 13:25:31 -0400538 mPipelineLayoutCache.destroy(mDevice);
539 mDescriptorSetLayoutCache.destroy(mDevice);
540
Jamie Madill9f2a8612017-11-30 12:43:09 -0500541 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500542 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400543 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400544 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400545 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500546
Jamie Madill06ca6342018-07-12 15:56:53 -0400547 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500548
Jamie Madill5deea722017-02-16 10:44:46 -0500549 if (mCommandPool.valid())
550 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000551 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500552 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500553
554 if (mDevice)
555 {
556 vkDestroyDevice(mDevice, nullptr);
557 mDevice = VK_NULL_HANDLE;
558 }
559
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500560 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500561 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500562 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
563 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
564
565 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
566 }
567 else if (mDebugReportCallback)
568 {
569 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
570 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500571 }
572
Jamie Madill4d0bf552016-12-28 15:45:24 -0500573 if (mInstance)
574 {
575 vkDestroyInstance(mInstance, nullptr);
576 mInstance = VK_NULL_HANDLE;
577 }
578
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600579 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500580 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500581}
582
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400583void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400584{
585 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400586
587 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500588 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400589 freeAllInFlightResources();
590
591 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400592}
593
594bool RendererVk::isDeviceLost() const
595{
596 return mDeviceLost;
597}
598
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400599angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400600 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500601 const char *wsiExtension,
602 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500603{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400604 mDisplay = display;
605 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600606 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
607 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500608 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400609 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500610
Jamie Madill0448ec82016-12-23 13:41:47 -0500611 // Gather global layer properties.
612 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400613 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500614
615 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
616 if (instanceLayerCount > 0)
617 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400618 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
619 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500620 }
621
Michael Spang6c13c702019-02-06 15:59:44 -0500622 VulkanLayerVector enabledInstanceLayerNames;
623 if (mEnableValidationLayers)
624 {
625 bool layersRequested =
626 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
627 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
628 &enabledInstanceLayerNames);
629 }
630
631 if (wsiLayer)
632 {
633 enabledInstanceLayerNames.push_back(wsiLayer);
634 }
635
636 // Enumerate instance extensions that are provided by the vulkan
637 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500638 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400639 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400640 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500641
642 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
643 if (instanceExtensionCount > 0)
644 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400645 ANGLE_VK_TRY(displayVk,
646 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
647 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500648 }
649
Michael Spang6c13c702019-02-06 15:59:44 -0500650 // Enumerate instance extensions that are provided by explicit layers.
651 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500652 {
Michael Spang6c13c702019-02-06 15:59:44 -0500653 uint32_t previousExtensionCount = instanceExtensionProps.size();
654 uint32_t instanceLayerExtensionCount = 0;
655 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
656 layerName, &instanceLayerExtensionCount, nullptr));
657 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
658 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
659 layerName, &instanceLayerExtensionCount,
660 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500661 }
662
Frank Henigman52047de2018-11-13 17:22:36 -0500663 ExtensionNameList instanceExtensionNames;
664 if (!instanceExtensionProps.empty())
665 {
666 for (const VkExtensionProperties &i : instanceExtensionProps)
667 {
668 instanceExtensionNames.push_back(i.extensionName);
669 }
670 std::sort(instanceExtensionNames.begin(), instanceExtensionNames.end(), StrLess);
671 }
672
673 ExtensionNameList enabledInstanceExtensions;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500674 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500675 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500676
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500677 bool enableDebugUtils =
678 mEnableValidationLayers &&
Frank Henigman52047de2018-11-13 17:22:36 -0500679 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionNames);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500680 bool enableDebugReport =
681 mEnableValidationLayers && !enableDebugUtils &&
Frank Henigman52047de2018-11-13 17:22:36 -0500682 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionNames);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500683
684 if (enableDebugUtils)
685 {
686 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
687 }
688 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500689 {
690 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
691 }
692
Jamie Madille09bd5d2016-11-29 16:20:35 -0500693 // Verify the required extensions are in the extension names set. Fail if not.
Frank Henigman52047de2018-11-13 17:22:36 -0500694 std::sort(enabledInstanceExtensions.begin(), enabledInstanceExtensions.end(), StrLess);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400695 ANGLE_VK_TRY(displayVk,
Frank Henigman52047de2018-11-13 17:22:36 -0500696 VerifyExtensionsPresent(instanceExtensionNames, enabledInstanceExtensions));
697
698 // Enable VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME if available.
699 if (ExtensionFound(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
700 instanceExtensionNames))
701 {
702 enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
703 }
Jamie Madille09bd5d2016-11-29 16:20:35 -0500704
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400705 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500706 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500707 applicationInfo.pApplicationName = "ANGLE";
708 applicationInfo.applicationVersion = 1;
709 applicationInfo.pEngineName = "ANGLE";
710 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700711
712 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
713 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
714 if (!enumerateInstanceVersion)
715 {
716 applicationInfo.apiVersion = VK_API_VERSION_1_0;
717 }
718 else
719 {
720 uint32_t apiVersion = VK_API_VERSION_1_0;
721 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
722 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
723 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700724 // This is the highest version of core Vulkan functionality that ANGLE uses.
725 applicationInfo.apiVersion = kPreferredVulkanAPIVersion;
Ian Elliott899c5d22018-12-21 13:12:50 -0700726 }
727 else
728 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700729 // Since only 1.0 instance-level functionality is available, this must set to 1.0.
Ian Elliott899c5d22018-12-21 13:12:50 -0700730 applicationInfo.apiVersion = VK_API_VERSION_1_0;
731 }
732 }
Jamie Madill327ba852016-11-30 12:38:28 -0500733
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400734 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500735 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
736 instanceInfo.flags = 0;
737 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500738
Jamie Madille09bd5d2016-11-29 16:20:35 -0500739 // Enable requested layers and extensions.
740 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
741 instanceInfo.ppEnabledExtensionNames =
742 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500743 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
744 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500745
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400746 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500747
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500748 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500749 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500750 // Try to use the newer EXT_debug_utils if it exists.
751 InitDebugUtilsEXTFunctions(mInstance);
752
753 // Create the messenger callback.
754 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
755
756 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
Shahbaz Youssefi0c01e362019-02-13 21:27:23 +0000757 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
758 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
759 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
760 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
761 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500762 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
763 messengerInfo.pUserData = this;
764
765 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
766 &mDebugUtilsMessenger));
767 }
768 else if (enableDebugReport)
769 {
770 // Fallback to EXT_debug_report.
771 InitDebugReportEXTFunctions(mInstance);
772
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400773 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500774
775 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500776 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500777 debugReportInfo.pfnCallback = &DebugReportCallback;
778 debugReportInfo.pUserData = this;
779
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500780 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
781 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500782 }
783
Frank Henigman52047de2018-11-13 17:22:36 -0500784 if (std::find(enabledInstanceExtensions.begin(), enabledInstanceExtensions.end(),
785 VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) !=
786 enabledInstanceExtensions.end())
787 {
788 InitGetPhysicalDeviceProperties2KHRFunctions(mInstance);
789 ASSERT(vkGetPhysicalDeviceProperties2KHR);
790 }
791
Jamie Madill4d0bf552016-12-28 15:45:24 -0500792 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400793 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
794 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500795
796 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700797 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400798 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
799 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400800 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700801 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500802
Jamie Madill30b5d842018-08-31 17:19:12 -0400803 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
804
Jamie Madill4d0bf552016-12-28 15:45:24 -0500805 // Ensure we can find a graphics queue family.
806 uint32_t queueCount = 0;
807 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
808
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400809 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500810
811 mQueueFamilyProperties.resize(queueCount);
812 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
813 mQueueFamilyProperties.data());
814
Jamie Madillb980c562018-11-27 11:34:27 -0500815 size_t graphicsQueueFamilyCount = false;
816 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500817 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500818 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
819 {
820 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500821 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500822 {
823 ASSERT(queueInfo.queueCount > 0);
824 graphicsQueueFamilyCount++;
825 if (firstGraphicsQueueFamily == 0)
826 {
827 firstGraphicsQueueFamily = familyIndex;
828 }
829 break;
830 }
831 }
832
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400833 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500834
835 // If only one queue family, go ahead and initialize the device. If there is more than one
836 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
837 if (graphicsQueueFamilyCount == 1)
838 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400839 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500840 }
841
Jamie Madill035fd6b2017-10-03 15:43:22 -0400842 // Store the physical device memory properties so we can find the right memory pools.
843 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500844
Jamie Madill06ca6342018-07-12 15:56:53 -0400845 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500846
Jamie Madill6a89d222017-11-02 11:59:51 -0400847 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500848 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400849
Jamie Madill7c985f52018-11-29 18:16:17 -0500850 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400851}
852
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400853angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500854{
855 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400856 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400857 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500858
859 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
860 if (deviceLayerCount > 0)
861 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400862 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
863 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500864 }
865
Michael Spang6c13c702019-02-06 15:59:44 -0500866 VulkanLayerVector enabledDeviceLayerNames;
867 if (mEnableValidationLayers)
868 {
869 mEnableValidationLayers =
870 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
871 }
872
873 const char *wsiLayer = displayVk->getWSILayer();
874 if (wsiLayer)
875 {
876 enabledDeviceLayerNames.push_back(wsiLayer);
877 }
878
879 // Enumerate device extensions that are provided by the vulkan
880 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500881 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400882 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
883 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500884
885 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
886 if (deviceExtensionCount > 0)
887 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400888 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
889 &deviceExtensionCount,
890 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500891 }
892
Michael Spang6c13c702019-02-06 15:59:44 -0500893 // Enumerate device extensions that are provided by explicit layers.
894 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500895 {
Michael Spang6c13c702019-02-06 15:59:44 -0500896 uint32_t previousExtensionCount = deviceExtensionProps.size();
897 uint32_t deviceLayerExtensionCount = 0;
898 ANGLE_VK_TRY(displayVk,
899 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
900 &deviceLayerExtensionCount, nullptr));
901 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
902 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
903 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
904 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500905 }
906
Frank Henigman52047de2018-11-13 17:22:36 -0500907 ExtensionNameList deviceExtensionNames;
908 if (!deviceExtensionProps.empty())
909 {
910 ASSERT(deviceExtensionNames.size() <= deviceExtensionProps.size());
911 for (const VkExtensionProperties &prop : deviceExtensionProps)
912 {
913 deviceExtensionNames.push_back(prop.extensionName);
914 }
915 std::sort(deviceExtensionNames.begin(), deviceExtensionNames.end(), StrLess);
916 }
917
918 ExtensionNameList enabledDeviceExtensions;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500919 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
920
Frank Henigman52047de2018-11-13 17:22:36 -0500921 initFeatures(deviceExtensionNames);
Ian Elliottbcb78902018-12-19 11:46:29 -0700922 mFeaturesInitialized = true;
923
Luc Ferronbf6dc372018-06-28 15:24:19 -0400924 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700925 if ((getFeatures().flipViewportY) &&
926 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400927 {
928 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
929 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700930 if (getFeatures().supportsIncrementalPresent)
931 {
932 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
933 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400934
Geoff Lang009696c2019-01-31 14:47:07 -0500935#if defined(ANGLE_PLATFORM_ANDROID)
936 if (getFeatures().supportsAndroidHardwareBuffer)
937 {
938 enabledDeviceExtensions.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
939 enabledDeviceExtensions.push_back(
940 VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
941 InitExternalMemoryHardwareBufferANDROIDFunctions(mInstance);
942 }
943#else
944 ASSERT(!getFeatures().supportsAndroidHardwareBuffer);
945#endif
946
Frank Henigman52047de2018-11-13 17:22:36 -0500947 std::sort(enabledDeviceExtensions.begin(), enabledDeviceExtensions.end(), StrLess);
948 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionNames, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500949
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400950 // Select additional features to be enabled
Frank Henigman52047de2018-11-13 17:22:36 -0500951 VkPhysicalDeviceFeatures2KHR enabledFeatures = {};
952 enabledFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
953 enabledFeatures.features.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
954 enabledFeatures.features.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi962c2222019-02-20 15:43:41 -0500955 enabledFeatures.features.samplerAnisotropy = mPhysicalDeviceFeatures.samplerAnisotropy;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400956
Frank Henigman52047de2018-11-13 17:22:36 -0500957 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisorFeatures = {};
958 divisorFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT;
959 divisorFeatures.vertexAttributeInstanceRateDivisor = true;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500960
961 float zeroPriority = 0.0f;
Frank Henigman52047de2018-11-13 17:22:36 -0500962 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500963 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500964 queueCreateInfo.flags = 0;
965 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
966 queueCreateInfo.queueCount = 1;
967 queueCreateInfo.pQueuePriorities = &zeroPriority;
968
969 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400970 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500971
Jamie Madill50cf2be2018-06-15 09:46:57 -0400972 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400973 createInfo.flags = 0;
974 createInfo.queueCreateInfoCount = 1;
975 createInfo.pQueueCreateInfos = &queueCreateInfo;
Michael Spang6c13c702019-02-06 15:59:44 -0500976 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
977 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Frank Henigman52047de2018-11-13 17:22:36 -0500978
979 if (vkGetPhysicalDeviceProperties2KHR &&
980 ExtensionFound(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, deviceExtensionNames))
981 {
982 enabledDeviceExtensions.push_back(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME);
983 enabledFeatures.pNext = &divisorFeatures;
984
985 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT divisorProperties = {};
986 divisorProperties.sType =
987 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT;
988
989 VkPhysicalDeviceProperties2 deviceProperties = {};
990 deviceProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
991 deviceProperties.pNext = &divisorProperties;
992
993 vkGetPhysicalDeviceProperties2KHR(mPhysicalDevice, &deviceProperties);
994 mMaxVertexAttribDivisor = divisorProperties.maxVertexAttribDivisor;
995
996 createInfo.pNext = &enabledFeatures;
997 }
998 else
999 {
1000 createInfo.pEnabledFeatures = &enabledFeatures.features;
1001 }
1002
Jamie Madill4d0bf552016-12-28 15:45:24 -05001003 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
1004 createInfo.ppEnabledExtensionNames =
1005 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -05001006
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001007 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001008
1009 mCurrentQueueFamilyIndex = queueFamilyIndex;
1010
1011 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
1012
1013 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001014 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001015 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1016 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
1017 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001018
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001019 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001020
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001021 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001022 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001023
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001024 // Initialize the submission semaphore pool.
1025 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
1026
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001027#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
1028 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1029 ASSERT(platform);
1030
1031 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
1032 // platform discovery.
1033 const unsigned char *gpuEventsEnabled =
1034 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
1035 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
1036#endif
1037
1038 if (mGpuEventsEnabled)
1039 {
1040 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
1041 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
1042 vk::kDefaultTimestampQueryPoolSize));
1043 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
1044 }
1045
Jamie Madill7c985f52018-11-29 18:16:17 -05001046 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001047}
1048
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001049angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -04001050 VkSurfaceKHR surface,
1051 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001052{
1053 // We've already initialized a device, and can't re-create it unless it's never been used.
1054 // TODO(jmadill): Handle the re-creation case if necessary.
1055 if (mDevice != VK_NULL_HANDLE)
1056 {
1057 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
1058
1059 // Check if the current device supports present on this surface.
1060 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001061 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -04001062 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -05001063 surface, &supportsPresent));
1064
Jamie Madill6cad7732018-07-11 09:01:17 -04001065 if (supportsPresent == VK_TRUE)
1066 {
1067 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -05001068 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -04001069 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001070 }
1071
1072 // Find a graphics and present queue.
1073 Optional<uint32_t> newPresentQueue;
1074 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001075 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001076 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
1077 {
1078 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001079 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001080 {
1081 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001082 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
1083 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001084
1085 if (supportsPresent == VK_TRUE)
1086 {
1087 newPresentQueue = queueIndex;
1088 break;
1089 }
1090 }
1091 }
1092
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001093 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1094 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001095
Jamie Madill6cad7732018-07-11 09:01:17 -04001096 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001097 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001098}
1099
1100std::string RendererVk::getVendorString() const
1101{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001102 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001103}
1104
Jamie Madille09bd5d2016-11-29 16:20:35 -05001105std::string RendererVk::getRendererDescription() const
1106{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001107 std::stringstream strstr;
1108
1109 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1110
1111 strstr << "Vulkan ";
1112 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1113 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1114 strstr << VK_VERSION_PATCH(apiVersion);
1115
Olli Etuahoc6a06182018-04-13 14:11:46 +03001116 strstr << "(";
1117
1118 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1119 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1120 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1121 // driver detection.
1122 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1123 {
1124 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1125 }
1126
Geoff Langa7af56b2018-12-14 14:20:28 -05001127 strstr << mPhysicalDeviceProperties.deviceName;
1128 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1129
1130 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001131
1132 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001133}
1134
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001135gl::Version RendererVk::getMaxSupportedESVersion() const
1136{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001137 // Current highest supported version
Shahbaz Youssefi9dc8eaf2019-02-11 11:04:54 -05001138 gl::Version maxVersion = gl::Version(3, 0);
1139
1140#if ANGLE_VULKAN_CONFORMANT_CONFIGS_ONLY
1141 // TODO: Disallow ES 3.0 until supported. http://crbug.com/angleproject/2950
1142 maxVersion = gl::Version(2, 0);
1143#endif
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001144
Geoff Lang0c2c9232019-01-14 16:01:38 -05001145 // Vulkan inherited queries are required to support any GL query type
1146 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001147 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001148 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001149 }
1150
Geoff Lang0c2c9232019-01-14 16:01:38 -05001151 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001152}
1153
Frank Henigman52047de2018-11-13 17:22:36 -05001154void RendererVk::initFeatures(const ExtensionNameList &deviceExtensionNames)
Jamie Madill12222072018-07-11 14:59:48 -04001155{
Jamie Madillb36a4812018-09-25 10:15:11 -04001156// Use OpenGL line rasterization rules by default.
1157// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1158#if defined(ANGLE_PLATFORM_ANDROID)
1159 mFeatures.basicGLLineRasterization = false;
1160#else
Jamie Madill12222072018-07-11 14:59:48 -04001161 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001162#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001163
Ian Elliott52f5da42018-12-21 09:02:09 -07001164 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
Frank Henigman52047de2018-11-13 17:22:36 -05001165 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionNames))
Ian Elliottd50521f2018-12-20 12:05:14 -07001166 {
1167 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1168 // investigation. http://anglebug.com/2728
1169 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1170 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001171
1172#ifdef ANGLE_PLATFORM_WINDOWS
1173 // http://anglebug.com/2838
1174 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001175
1176 // http://anglebug.com/3055
1177 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001178#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001179
1180 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1181 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001182
1183 // Work around incorrect NVIDIA point size range clamping.
1184 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1185 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1186 {
1187 mFeatures.clampPointSize = true;
1188 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001189
Jamie Madillfa7ca182019-01-15 11:20:58 -05001190 // We also need to clamp point size on several Android drivers.
1191 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1192 if (IsAndroid())
1193 {
1194 mFeatures.clampPointSize = true;
1195 }
1196
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001197#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001198 // Work around ineffective compute-graphics barriers on Nexus 5X.
1199 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1200 // http://anglebug.com/3019
1201 mFeatures.flushAfterVertexConversion =
1202 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001203#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001204
Frank Henigman52047de2018-11-13 17:22:36 -05001205 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionNames))
Ian Elliottbcb78902018-12-19 11:46:29 -07001206 {
1207 mFeatures.supportsIncrementalPresent = true;
1208 }
Geoff Lang009696c2019-01-31 14:47:07 -05001209
1210#if defined(ANGLE_PLATFORM_ANDROID)
Yuly Novikovdbbdf562019-02-27 19:48:16 -05001211 mFeatures.supportsAndroidHardwareBuffer =
1212 ExtensionFound(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME,
1213 deviceExtensionNames) &&
1214 ExtensionFound(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, deviceExtensionNames);
Geoff Lang009696c2019-01-31 14:47:07 -05001215#endif
Jamie Madill12222072018-07-11 14:59:48 -04001216}
1217
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001218void RendererVk::initPipelineCacheVkKey()
1219{
1220 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1221 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1222 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1223 // there is no '\0' in the result.
1224 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1225 {
1226 hashStream << std::hex << c;
1227 }
1228 // Add the vendor and device id too for good measure.
1229 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1230 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1231
1232 const std::string &hashString = hashStream.str();
1233 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1234 hashString.length(), mPipelineCacheVkBlobKey.data());
1235}
1236
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001237angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001238{
1239 initPipelineCacheVkKey();
1240
1241 egl::BlobCache::Value initialData;
1242 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1243 mPipelineCacheVkBlobKey, &initialData);
1244
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001245 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001246
1247 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001248 pipelineCacheCreateInfo.flags = 0;
1249 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1250 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1251
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001252 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001253 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001254}
1255
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001256void RendererVk::getSubmitWaitSemaphores(
1257 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001258 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1259 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001260{
1261 if (mSubmitLastSignaledSemaphore.getSemaphore())
1262 {
1263 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001264 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001265
1266 // Return the semaphore to the pool (which will remain valid and unused until the
1267 // queue it's about to be waited on has finished execution).
1268 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1269 }
1270
1271 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1272 {
1273 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001274 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1275
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001276 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1277 }
1278 mSubmitWaitSemaphores.clear();
1279}
1280
Jamie Madillacccc6c2016-05-03 17:22:10 -04001281const gl::Caps &RendererVk::getNativeCaps() const
1282{
1283 ensureCapsInitialized();
1284 return mNativeCaps;
1285}
1286
1287const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1288{
1289 ensureCapsInitialized();
1290 return mNativeTextureCaps;
1291}
1292
1293const gl::Extensions &RendererVk::getNativeExtensions() const
1294{
1295 ensureCapsInitialized();
1296 return mNativeExtensions;
1297}
1298
1299const gl::Limitations &RendererVk::getNativeLimitations() const
1300{
1301 ensureCapsInitialized();
1302 return mNativeLimitations;
1303}
1304
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001305uint32_t RendererVk::getMaxActiveTextures()
1306{
1307 // TODO(lucferron): expose this limitation to GL in Context Caps
1308 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1309 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1310}
1311
Jamie Madill49ac74b2017-12-21 14:42:33 -05001312const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001313{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001314 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001315}
1316
Jamie Madill21061022018-07-12 23:56:30 -04001317angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001318{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001319 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001320 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001321 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1322
Luc Ferron1617e692018-07-11 11:08:19 -04001323 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1324 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001325
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001326 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001327 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1328 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001329
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001330 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001331 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001332 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1333 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001334 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001335 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001336 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001337 submitInfo.signalSemaphoreCount = 0;
1338 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001339
Jamie Madill21061022018-07-12 23:56:30 -04001340 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001341 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001342
Jamie Madill4c26fc22017-02-24 11:04:10 -05001343 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001344 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001345 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001346
1347 if (mGpuEventsEnabled)
1348 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001349 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001350 while (mInFlightGpuEventQueries.size() > 0)
1351 {
1352 ANGLE_TRY(checkCompletedGpuEvents(context));
1353 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001354 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1355 // synchronization if there is no event to be adjusted (happens when finish() gets called
1356 // multiple times towards the end of the application).
1357 if (mGpuEvents.size() > 0)
1358 {
1359 ANGLE_TRY(synchronizeCpuGpuTime(context));
1360 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001361 }
1362
Jamie Madill7c985f52018-11-29 18:16:17 -05001363 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001364}
1365
Jamie Madill0c0dc342017-03-24 14:18:51 -04001366void RendererVk::freeAllInFlightResources()
1367{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001368 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001369 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001370 // On device loss we need to wait for fence to be signaled before destroying it
1371 if (mDeviceLost)
1372 {
1373 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1374 // If wait times out, it is probably not possible to recover from lost device
1375 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1376 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001377 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001378 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001379 }
1380 mInFlightCommands.clear();
1381
1382 for (auto &garbage : mGarbage)
1383 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001384 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001385 }
1386 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001387
1388 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001389}
1390
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001391angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001392{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001393 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001394
Jamie Madill49ac74b2017-12-21 14:42:33 -05001395 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001396 {
Yuly Novikov27780292018-11-09 11:19:49 -05001397 VkResult result = batch.fence.getStatus(mDevice);
1398 if (result == VK_NOT_READY)
1399 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001400 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001401 }
1402 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001403
Jamie Madill49ac74b2017-12-21 14:42:33 -05001404 ASSERT(batch.serial > mLastCompletedQueueSerial);
1405 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001406
Jamie Madill49ac74b2017-12-21 14:42:33 -05001407 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001408 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001409 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001410 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001411 }
1412
Jamie Madill49ac74b2017-12-21 14:42:33 -05001413 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001414
1415 size_t freeIndex = 0;
1416 for (; freeIndex < mGarbage.size(); ++freeIndex)
1417 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001418 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001419 break;
1420 }
1421
1422 // Remove the entries from the garbage list - they should be ready to go.
1423 if (freeIndex > 0)
1424 {
1425 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001426 }
1427
Jamie Madill7c985f52018-11-29 18:16:17 -05001428 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001429}
1430
Jamie Madill21061022018-07-12 23:56:30 -04001431angle::Result RendererVk::submitFrame(vk::Context *context,
1432 const VkSubmitInfo &submitInfo,
1433 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001434{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001435 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001436 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001437 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1438 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001439
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001440 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001441 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001442 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001443
Jamie Madill21061022018-07-12 23:56:30 -04001444 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001445
1446 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001447 batch.commandPool = std::move(mCommandPool);
1448 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001449
Jamie Madillbea35a62018-07-05 11:54:10 -04001450 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001451
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001452 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1453 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001454 // so the limit is larger than the expected number of images. The
1455 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001456 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001457
Jamie Madill85ca1892019-01-16 13:27:15 -05001458 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001459
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001460 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001461
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001462 if (mGpuEventsEnabled)
1463 {
1464 ANGLE_TRY(checkCompletedGpuEvents(context));
1465 }
1466
Jamie Madill49ac74b2017-12-21 14:42:33 -05001467 // Simply null out the command buffer here - it was allocated using the command pool.
1468 commandBuffer.releaseHandle();
1469
1470 // Reallocate the command pool for next frame.
1471 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001472 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001473 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001474 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001475 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001476
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001477 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001478 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001479}
1480
Jamie Madill85ca1892019-01-16 13:27:15 -05001481void RendererVk::nextSerial()
1482{
1483 // Increment the queue serial. If this fails, we should restart ANGLE.
1484 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1485 mCurrentQueueSerial = mQueueSerialFactory.generate();
1486
1487 // Notify the Contexts that they should be starting new command buffers.
1488 // We use one command pool per serial/submit associated with this VkQueue. We can also
1489 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1490 // check for a new serial when starting a new command buffer. We just check that the current
1491 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1492 // using this VkQueue that they their current command buffer is no longer valid.
1493 for (gl::Context *context : mDisplay->getContextSet())
1494 {
1495 ContextVk *contextVk = vk::GetImpl(context);
1496 contextVk->onCommandBufferFinished();
1497 }
1498}
1499
Jamie Madillaaca96e2018-06-12 10:19:48 -04001500bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001501{
1502 return serial > mLastCompletedQueueSerial;
1503}
1504
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001505angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1506{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001507 bool timedOut = false;
1508 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1509
1510 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1511 if (timedOut)
1512 {
1513 result = angle::Result::Stop;
1514 }
1515 return result;
1516}
1517
1518angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1519 Serial serial,
1520 uint64_t timeout,
1521 bool *outTimedOut)
1522{
1523 *outTimedOut = false;
1524
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001525 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1526 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001527 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001528 }
1529
1530 // Find the first batch with serial equal to or bigger than given serial (note that
1531 // the batch serials are unique, otherwise upper-bound would have been necessary).
1532 size_t batchIndex = mInFlightCommands.size() - 1;
1533 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1534 {
1535 if (mInFlightCommands[i].serial >= serial)
1536 {
1537 batchIndex = i;
1538 break;
1539 }
1540 }
1541 const CommandBatch &batch = mInFlightCommands[batchIndex];
1542
1543 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001544 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1545
1546 // If timed out, report it as such.
1547 if (status == VK_TIMEOUT)
1548 {
1549 *outTimedOut = true;
1550 return angle::Result::Continue;
1551 }
1552
1553 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001554
1555 // Clean up finished batches.
1556 return checkCompletedCommands(context);
1557}
1558
Jamie Madill21061022018-07-12 23:56:30 -04001559angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1560 const vk::RenderPassDesc &desc,
1561 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001562{
Jamie Madill21061022018-07-12 23:56:30 -04001563 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001564 renderPassOut);
1565}
1566
Jamie Madill21061022018-07-12 23:56:30 -04001567angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1568 const vk::RenderPassDesc &desc,
1569 const vk::AttachmentOpsArray &ops,
1570 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001571{
Jamie Madill21061022018-07-12 23:56:30 -04001572 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001573 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001574}
1575
Jamie Madilla5e06072018-05-18 14:36:05 -04001576vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001577{
Jamie Madilla5e06072018-05-18 14:36:05 -04001578 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001579}
1580
Jamie Madill21061022018-07-12 23:56:30 -04001581angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001582{
Jamie Madill21061022018-07-12 23:56:30 -04001583 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001584 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001585}
1586
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001587angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001588{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001589 if (mCommandGraph.empty())
1590 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001591 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001592 }
1593
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001594 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1595
Jamie Madillbea35a62018-07-05 11:54:10 -04001596 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1597 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001598
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001599 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001600 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1601 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001602
1603 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1604 // will be waited on.
1605 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001606
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001607 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001608 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001609 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1610 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001611 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001612 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001613 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001614 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001615 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001616
Jamie Madill21061022018-07-12 23:56:30 -04001617 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001618
Jamie Madill7c985f52018-11-29 18:16:17 -05001619 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001620}
1621
Jamie Madill78feddc2018-04-27 11:45:05 -04001622Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001623{
Jamie Madill78feddc2018-04-27 11:45:05 -04001624 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001625}
1626
Jamie Madill21061022018-07-12 23:56:30 -04001627angle::Result RendererVk::getDescriptorSetLayout(
1628 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001629 const vk::DescriptorSetLayoutDesc &desc,
1630 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1631{
Jamie Madill21061022018-07-12 23:56:30 -04001632 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001633}
1634
Jamie Madill21061022018-07-12 23:56:30 -04001635angle::Result RendererVk::getPipelineLayout(
1636 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001637 const vk::PipelineLayoutDesc &desc,
1638 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1639 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1640{
Jamie Madill21061022018-07-12 23:56:30 -04001641 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001642 pipelineLayoutOut);
1643}
1644
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001645angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1646{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001647 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001648
1649 if (--mPipelineCacheVkUpdateTimeout > 0)
1650 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001651 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001652 }
1653
1654 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1655
1656 // Get the size of the cache.
1657 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001658 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001659 if (result != VK_INCOMPLETE)
1660 {
1661 ANGLE_VK_TRY(displayVk, result);
1662 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001663
1664 angle::MemoryBuffer *pipelineCacheData = nullptr;
1665 ANGLE_VK_CHECK_ALLOC(displayVk,
1666 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1667
1668 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001669 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001670 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1671 // was determined just above), so receiving it hints at an implementation bug we would want
1672 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001673 ASSERT(result != VK_INCOMPLETE);
1674 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001675
1676 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1677 // the buffer to avoid leaking garbage memory.
1678 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1679 if (pipelineCacheSize < originalPipelineCacheSize)
1680 {
1681 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1682 originalPipelineCacheSize - pipelineCacheSize);
1683 }
1684
1685 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1686
Jamie Madill7c985f52018-11-29 18:16:17 -05001687 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001688}
1689
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001690angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1691 const vk::Semaphore **outSemaphore)
1692{
1693 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1694
1695 vk::SemaphoreHelper semaphore;
1696 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1697
1698 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1699 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1700
Jamie Madill7c985f52018-11-29 18:16:17 -05001701 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001702}
1703
1704const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1705{
1706 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1707
1708 // Return the semaphore to the pool (which will remain valid and unused until the
1709 // queue it's about to be waited on has finished execution). The caller is about
1710 // to wait on it.
1711 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1712
1713 return semaphore;
1714}
1715
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001716angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1717{
1718 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1719 // that seems impossible, so instead, we are going to make a small submission with just a
1720 // timestamp query. First, the disjoint timer query extension says:
1721 //
1722 // > This will return the GL time after all previous commands have reached the GL server but
1723 // have not yet necessarily executed.
1724 //
1725 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1726 // The wording allows us to make a submission to get the timestamp without performing a flush.
1727 //
1728 // Second:
1729 //
1730 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1731 // object target, applications can measure the latency between when commands reach the GL server
1732 // and when they are realized in the framebuffer.
1733 //
1734 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1735 // GPU bubble. This function directly generates a command buffer and submits it instead of
1736 // using the other member functions. This is to avoid changing any state, such as the queue
1737 // serial.
1738
1739 // Create a query used to receive the GPU timestamp
1740 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1741 vk::QueryHelper timestampQuery;
1742 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1743 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1744
1745 // Record the command buffer
1746 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1747 vk::CommandBuffer &commandBuffer = commandBatch.get();
1748
1749 VkCommandBufferAllocateInfo commandBufferInfo = {};
1750 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1751 commandBufferInfo.commandPool = mCommandPool.getHandle();
1752 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1753 commandBufferInfo.commandBufferCount = 1;
1754
Yuly Novikov27780292018-11-09 11:19:49 -05001755 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001756
1757 VkCommandBufferBeginInfo beginInfo = {};
1758 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1759 beginInfo.flags = 0;
1760 beginInfo.pInheritanceInfo = nullptr;
1761
Yuly Novikov27780292018-11-09 11:19:49 -05001762 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001763
1764 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1765 timestampQuery.getQuery(), 1);
1766 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1767 timestampQuery.getQueryPool()->getHandle(),
1768 timestampQuery.getQuery());
1769
Yuly Novikov27780292018-11-09 11:19:49 -05001770 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001771
1772 // Create fence for the submission
1773 VkFenceCreateInfo fenceInfo = {};
1774 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1775 fenceInfo.flags = 0;
1776
1777 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001778 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001779
1780 // Submit the command buffer
1781 VkSubmitInfo submitInfo = {};
1782 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1783 submitInfo.waitSemaphoreCount = 0;
1784 submitInfo.pWaitSemaphores = nullptr;
1785 submitInfo.pWaitDstStageMask = nullptr;
1786 submitInfo.commandBufferCount = 1;
1787 submitInfo.pCommandBuffers = commandBuffer.ptr();
1788 submitInfo.signalSemaphoreCount = 0;
1789 submitInfo.pSignalSemaphores = nullptr;
1790
1791 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1792
1793 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1794 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001795 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001796
1797 // Get the query results
1798 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1799
Yuly Novikov27780292018-11-09 11:19:49 -05001800 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1801 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1802 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001803
1804 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1805
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001806 // Convert results to nanoseconds.
1807 *timestampOut = static_cast<uint64_t>(
1808 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1809
Jamie Madill7c985f52018-11-29 18:16:17 -05001810 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001811}
1812
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001813// These functions look at the mandatory format for support, and fallback to querying the device (if
1814// necessary) to test the availability of the bits.
1815bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1816 const VkFormatFeatureFlags featureBits)
1817{
1818 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1819}
1820
1821bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1822 const VkFormatFeatureFlags featureBits)
1823{
1824 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1825}
1826
1827bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1828{
1829 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1830}
1831
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001832angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1833{
1834 ASSERT(mGpuEventsEnabled);
1835
1836 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1837 ASSERT(platform);
1838
1839 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1840 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1841 //
1842 // CPU GPU
1843 //
1844 // Record command buffer
1845 // with timestamp query
1846 //
1847 // Submit command buffer
1848 //
1849 // Post-submission work Begin execution
1850 //
Tobin Ehlis5546fb42019-01-17 12:25:54 -05001851 // ???? Write timestamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001852 //
1853 // ???? End execution
1854 //
1855 // ???? Return query results
1856 //
1857 // ????
1858 //
1859 // Get query results
1860 //
1861 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1862 // finished post-submission work while the GPU is executing in parallel. With no further work,
1863 // querying CPU timestamps before submission and after getting query results give the bounds to
1864 // Tgpu, which could be quite large.
1865 //
1866 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1867 // reduce this range. This function implements the following procedure:
1868 //
1869 // CPU GPU
1870 //
1871 // Record command buffer
1872 // with timestamp query
1873 //
1874 // Submit command buffer
1875 //
1876 // Post-submission work Begin execution
1877 //
1878 // ???? Set Event GPUReady
1879 //
1880 // Wait on Event GPUReady Wait on Event CPUReady
1881 //
1882 // Get CPU Time Ts Wait on Event CPUReady
1883 //
1884 // Set Event CPUReady Wait on Event CPUReady
1885 //
1886 // Get CPU Time Tcpu Get GPU Time Tgpu
1887 //
1888 // Wait on Event GPUDone Set Event GPUDone
1889 //
1890 // Get CPU Time Te End Execution
1891 //
1892 // Idle Return query results
1893 //
1894 // Get query results
1895 //
1896 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1897 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1898 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1899 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1900 // calibration.
1901 //
1902 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1903
1904 // Make sure nothing is running
1905 ASSERT(mCommandGraph.empty());
1906
1907 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1908
1909 // Create a query used to receive the GPU timestamp
1910 vk::QueryHelper timestampQuery;
1911 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1912
1913 // Create the three events
1914 VkEventCreateInfo eventCreateInfo = {};
1915 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1916 eventCreateInfo.flags = 0;
1917
1918 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001919 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1920 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1921 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001922
1923 constexpr uint32_t kRetries = 10;
1924
1925 // Time suffixes used are S for seconds and Cycles for cycles
1926 double tightestRangeS = 1e6f;
1927 double TcpuS = 0;
1928 uint64_t TgpuCycles = 0;
1929 for (uint32_t i = 0; i < kRetries; ++i)
1930 {
1931 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001932 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1933 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1934 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001935
1936 // Record the command buffer
1937 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1938 vk::CommandBuffer &commandBuffer = commandBatch.get();
1939
1940 VkCommandBufferAllocateInfo commandBufferInfo = {};
1941 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1942 commandBufferInfo.commandPool = mCommandPool.getHandle();
1943 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1944 commandBufferInfo.commandBufferCount = 1;
1945
Yuly Novikov27780292018-11-09 11:19:49 -05001946 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001947
1948 VkCommandBufferBeginInfo beginInfo = {};
1949 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1950 beginInfo.flags = 0;
1951 beginInfo.pInheritanceInfo = nullptr;
1952
Yuly Novikov27780292018-11-09 11:19:49 -05001953 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001954
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001955 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001956 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1957 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1958 nullptr);
1959
1960 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1961 timestampQuery.getQuery(), 1);
1962 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1963 timestampQuery.getQueryPool()->getHandle(),
1964 timestampQuery.getQuery());
1965
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001966 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001967
Yuly Novikov27780292018-11-09 11:19:49 -05001968 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001969
1970 // Submit the command buffer
1971 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1972 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1973 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1974
1975 VkSubmitInfo submitInfo = {};
1976 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1977 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1978 submitInfo.pWaitSemaphores = waitSemaphores.data();
1979 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1980 submitInfo.commandBufferCount = 1;
1981 submitInfo.pCommandBuffers = commandBuffer.ptr();
1982 submitInfo.signalSemaphoreCount = 0;
1983 submitInfo.pSignalSemaphores = nullptr;
1984
1985 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1986
1987 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001988 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001989 do
1990 {
Yuly Novikov27780292018-11-09 11:19:49 -05001991 result = gpuReady.get().getStatus(mDevice);
1992 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1993 {
1994 ANGLE_VK_TRY(context, result);
1995 }
1996 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001997
1998 double TsS = platform->monotonicallyIncreasingTime(platform);
1999
2000 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05002001 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002002 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
2003
2004 // Wait for GPU to be done. Another short busy wait.
2005 do
2006 {
Yuly Novikov27780292018-11-09 11:19:49 -05002007 result = gpuDone.get().getStatus(mDevice);
2008 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
2009 {
2010 ANGLE_VK_TRY(context, result);
2011 }
2012 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002013
2014 double TeS = platform->monotonicallyIncreasingTime(platform);
2015
2016 // Get the query results
2017 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
2018
2019 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
2020
2021 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002022 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
2023 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
2024 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002025
2026 // Use the first timestamp queried as origin.
2027 if (mGpuEventTimestampOrigin == 0)
2028 {
2029 mGpuEventTimestampOrigin = gpuTimestampCycles;
2030 }
2031
2032 // Take these CPU and GPU timestamps if there is better confidence.
2033 double confidenceRangeS = TeS - TsS;
2034 if (confidenceRangeS < tightestRangeS)
2035 {
2036 tightestRangeS = confidenceRangeS;
2037 TcpuS = cpuTimestampS;
2038 TgpuCycles = gpuTimestampCycles;
2039 }
2040 }
2041
2042 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
2043
2044 // timestampPeriod gives nanoseconds/cycle.
2045 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
2046 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
2047 1'000'000'000.0;
2048
2049 flushGpuEvents(TgpuS, TcpuS);
2050
2051 mGpuClockSync.gpuTimestampS = TgpuS;
2052 mGpuClockSync.cpuTimestampS = TcpuS;
2053
Jamie Madill7c985f52018-11-29 18:16:17 -05002054 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002055}
2056
2057angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
2058 vk::CommandBuffer *commandBuffer,
2059 char phase,
2060 const char *name)
2061{
2062 ASSERT(mGpuEventsEnabled);
2063
2064 GpuEventQuery event;
2065
2066 event.name = name;
2067 event.phase = phase;
2068 event.serial = mCurrentQueueSerial;
2069
2070 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
2071
2072 commandBuffer->resetQueryPool(
2073 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
2074 commandBuffer->writeTimestamp(
2075 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2076 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
2077
2078 mInFlightGpuEventQueries.push_back(std::move(event));
2079
Jamie Madill7c985f52018-11-29 18:16:17 -05002080 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002081}
2082
2083angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
2084{
2085 ASSERT(mGpuEventsEnabled);
2086
2087 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2088 ASSERT(platform);
2089
2090 int finishedCount = 0;
2091
2092 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2093 {
2094 // Only check the timestamp query if the submission has finished.
2095 if (eventQuery.serial > mLastCompletedQueueSerial)
2096 {
2097 break;
2098 }
2099
2100 // See if the results are available.
2101 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002102 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2103 ->getResults(mDevice, eventQuery.queryIndex, 1,
2104 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2105 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2106 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002107 {
2108 break;
2109 }
Yuly Novikov27780292018-11-09 11:19:49 -05002110 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002111
2112 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2113
2114 GpuEvent event;
2115 event.gpuTimestampCycles = gpuTimestampCycles;
2116 event.name = eventQuery.name;
2117 event.phase = eventQuery.phase;
2118
2119 mGpuEvents.emplace_back(event);
2120
2121 ++finishedCount;
2122 }
2123
2124 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2125 mInFlightGpuEventQueries.begin() + finishedCount);
2126
Jamie Madill7c985f52018-11-29 18:16:17 -05002127 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002128}
2129
2130void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2131{
2132 if (mGpuEvents.size() == 0)
2133 {
2134 return;
2135 }
2136
2137 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2138 ASSERT(platform);
2139
2140 // Find the slope of the clock drift for adjustment
2141 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2142 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2143 double gpuSyncDriftSlope = 0;
2144
2145 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2146 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2147
2148 // No gpu trace events should have been generated before the clock sync, so if there is no
2149 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2150 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2151 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2152
2153 gpuSyncDriftSlope =
2154 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2155
2156 for (const GpuEvent &event : mGpuEvents)
2157 {
2158 double gpuTimestampS =
2159 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2160 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2161
2162 // Account for clock drift.
2163 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2164
2165 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2166 // for.
2167 static long long eventId = 1;
2168 static const unsigned char *categoryEnabled =
2169 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2170 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2171 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2172 }
2173
2174 mGpuEvents.clear();
2175}
2176
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002177template <VkFormatFeatureFlags VkFormatProperties::*features>
2178bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2179{
2180 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2181 VkFormatProperties &deviceProperties = mFormatProperties[format];
2182
2183 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2184 {
2185 // If we don't have the actual device features, see if the requested features are mandatory.
2186 // If so, there's no need to query the device.
2187 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2188 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2189 {
2190 return true;
2191 }
2192
2193 // Otherwise query the format features and cache it.
2194 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2195 }
2196
2197 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2198}
2199
Jamie Madillaaca96e2018-06-12 10:19:48 -04002200uint32_t GetUniformBufferDescriptorCount()
2201{
2202 return kUniformBufferDescriptorsPerDescriptorSet;
2203}
2204
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002205} // namespace rx