blob: 42774c1c6d2f319db65eb2a5010c3dc9024ca618 [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
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500961 float zeroPriority = 0.0f;
Frank Henigman52047de2018-11-13 17:22:36 -0500962 VkDeviceQueueCreateInfo queueCreateInfo = {};
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500963 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
964 queueCreateInfo.flags = 0;
965 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
966 queueCreateInfo.queueCount = 1;
967 queueCreateInfo.pQueuePriorities = &zeroPriority;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500968
969 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400970 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500971
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500972 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
973 createInfo.flags = 0;
974 createInfo.queueCreateInfoCount = 1;
975 createInfo.pQueueCreateInfos = &queueCreateInfo;
976 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
Yuly Novikov1581ff02019-02-28 20:59:26 -05001216
1217 if (IsLinux() && IsIntel(mPhysicalDeviceProperties.vendorID))
1218 {
1219 mFeatures.disableFifoPresentMode = true;
1220 }
Jamie Madill12222072018-07-11 14:59:48 -04001221}
1222
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001223void RendererVk::initPipelineCacheVkKey()
1224{
1225 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1226 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1227 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1228 // there is no '\0' in the result.
1229 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1230 {
1231 hashStream << std::hex << c;
1232 }
1233 // Add the vendor and device id too for good measure.
1234 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1235 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1236
1237 const std::string &hashString = hashStream.str();
1238 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1239 hashString.length(), mPipelineCacheVkBlobKey.data());
1240}
1241
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001242angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001243{
1244 initPipelineCacheVkKey();
1245
1246 egl::BlobCache::Value initialData;
1247 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1248 mPipelineCacheVkBlobKey, &initialData);
1249
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001250 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001251
1252 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001253 pipelineCacheCreateInfo.flags = 0;
1254 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1255 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1256
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001257 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001258 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001259}
1260
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001261void RendererVk::getSubmitWaitSemaphores(
1262 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001263 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1264 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001265{
1266 if (mSubmitLastSignaledSemaphore.getSemaphore())
1267 {
1268 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001269 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001270
1271 // Return the semaphore to the pool (which will remain valid and unused until the
1272 // queue it's about to be waited on has finished execution).
1273 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1274 }
1275
1276 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1277 {
1278 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001279 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1280
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001281 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1282 }
1283 mSubmitWaitSemaphores.clear();
1284}
1285
Jamie Madillacccc6c2016-05-03 17:22:10 -04001286const gl::Caps &RendererVk::getNativeCaps() const
1287{
1288 ensureCapsInitialized();
1289 return mNativeCaps;
1290}
1291
1292const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1293{
1294 ensureCapsInitialized();
1295 return mNativeTextureCaps;
1296}
1297
1298const gl::Extensions &RendererVk::getNativeExtensions() const
1299{
1300 ensureCapsInitialized();
1301 return mNativeExtensions;
1302}
1303
1304const gl::Limitations &RendererVk::getNativeLimitations() const
1305{
1306 ensureCapsInitialized();
1307 return mNativeLimitations;
1308}
1309
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001310uint32_t RendererVk::getMaxActiveTextures()
1311{
1312 // TODO(lucferron): expose this limitation to GL in Context Caps
1313 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1314 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1315}
1316
Jamie Madill49ac74b2017-12-21 14:42:33 -05001317const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001318{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001319 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001320}
1321
Jamie Madill21061022018-07-12 23:56:30 -04001322angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001323{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001324 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001325 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001326 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1327
Luc Ferron1617e692018-07-11 11:08:19 -04001328 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1329 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001330
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001331 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001332 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1333 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001334
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001335 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001336 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001337 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1338 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001339 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001340 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001341 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001342 submitInfo.signalSemaphoreCount = 0;
1343 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001344
Jamie Madill21061022018-07-12 23:56:30 -04001345 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001346 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001347
Jamie Madill4c26fc22017-02-24 11:04:10 -05001348 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001349 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001350 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001351
1352 if (mGpuEventsEnabled)
1353 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001354 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001355 while (mInFlightGpuEventQueries.size() > 0)
1356 {
1357 ANGLE_TRY(checkCompletedGpuEvents(context));
1358 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001359 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1360 // synchronization if there is no event to be adjusted (happens when finish() gets called
1361 // multiple times towards the end of the application).
1362 if (mGpuEvents.size() > 0)
1363 {
1364 ANGLE_TRY(synchronizeCpuGpuTime(context));
1365 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001366 }
1367
Jamie Madill7c985f52018-11-29 18:16:17 -05001368 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001369}
1370
Jamie Madill0c0dc342017-03-24 14:18:51 -04001371void RendererVk::freeAllInFlightResources()
1372{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001373 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001374 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001375 // On device loss we need to wait for fence to be signaled before destroying it
1376 if (mDeviceLost)
1377 {
1378 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1379 // If wait times out, it is probably not possible to recover from lost device
1380 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1381 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001382 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001383 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001384 }
1385 mInFlightCommands.clear();
1386
1387 for (auto &garbage : mGarbage)
1388 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001389 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001390 }
1391 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001392
1393 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001394}
1395
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001396angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001397{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001398 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001399
Jamie Madill49ac74b2017-12-21 14:42:33 -05001400 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001401 {
Yuly Novikov27780292018-11-09 11:19:49 -05001402 VkResult result = batch.fence.getStatus(mDevice);
1403 if (result == VK_NOT_READY)
1404 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001405 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001406 }
1407 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001408
Jamie Madill49ac74b2017-12-21 14:42:33 -05001409 ASSERT(batch.serial > mLastCompletedQueueSerial);
1410 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001411
Jamie Madill49ac74b2017-12-21 14:42:33 -05001412 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001413 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001414 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001415 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001416 }
1417
Jamie Madill49ac74b2017-12-21 14:42:33 -05001418 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001419
1420 size_t freeIndex = 0;
1421 for (; freeIndex < mGarbage.size(); ++freeIndex)
1422 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001423 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001424 break;
1425 }
1426
1427 // Remove the entries from the garbage list - they should be ready to go.
1428 if (freeIndex > 0)
1429 {
1430 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001431 }
1432
Jamie Madill7c985f52018-11-29 18:16:17 -05001433 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001434}
1435
Jamie Madill21061022018-07-12 23:56:30 -04001436angle::Result RendererVk::submitFrame(vk::Context *context,
1437 const VkSubmitInfo &submitInfo,
1438 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001439{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001440 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001441 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001442 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1443 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001444
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001445 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001446 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001447 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001448
Jamie Madill21061022018-07-12 23:56:30 -04001449 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001450
1451 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001452 batch.commandPool = std::move(mCommandPool);
1453 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001454
Jamie Madillbea35a62018-07-05 11:54:10 -04001455 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001456
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001457 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1458 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001459 // so the limit is larger than the expected number of images. The
1460 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001461 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001462
Jamie Madill85ca1892019-01-16 13:27:15 -05001463 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001464
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001465 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001466
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001467 if (mGpuEventsEnabled)
1468 {
1469 ANGLE_TRY(checkCompletedGpuEvents(context));
1470 }
1471
Jamie Madill49ac74b2017-12-21 14:42:33 -05001472 // Simply null out the command buffer here - it was allocated using the command pool.
1473 commandBuffer.releaseHandle();
1474
1475 // Reallocate the command pool for next frame.
1476 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001477 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001478 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001479 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001480 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001481
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001482 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001483 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001484}
1485
Jamie Madill85ca1892019-01-16 13:27:15 -05001486void RendererVk::nextSerial()
1487{
1488 // Increment the queue serial. If this fails, we should restart ANGLE.
1489 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1490 mCurrentQueueSerial = mQueueSerialFactory.generate();
1491
1492 // Notify the Contexts that they should be starting new command buffers.
1493 // We use one command pool per serial/submit associated with this VkQueue. We can also
1494 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1495 // check for a new serial when starting a new command buffer. We just check that the current
1496 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1497 // using this VkQueue that they their current command buffer is no longer valid.
1498 for (gl::Context *context : mDisplay->getContextSet())
1499 {
1500 ContextVk *contextVk = vk::GetImpl(context);
1501 contextVk->onCommandBufferFinished();
1502 }
1503}
1504
Jamie Madillaaca96e2018-06-12 10:19:48 -04001505bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001506{
1507 return serial > mLastCompletedQueueSerial;
1508}
1509
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001510angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1511{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001512 bool timedOut = false;
1513 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1514
1515 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1516 if (timedOut)
1517 {
1518 result = angle::Result::Stop;
1519 }
1520 return result;
1521}
1522
1523angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1524 Serial serial,
1525 uint64_t timeout,
1526 bool *outTimedOut)
1527{
1528 *outTimedOut = false;
1529
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001530 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1531 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001532 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001533 }
1534
1535 // Find the first batch with serial equal to or bigger than given serial (note that
1536 // the batch serials are unique, otherwise upper-bound would have been necessary).
1537 size_t batchIndex = mInFlightCommands.size() - 1;
1538 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1539 {
1540 if (mInFlightCommands[i].serial >= serial)
1541 {
1542 batchIndex = i;
1543 break;
1544 }
1545 }
1546 const CommandBatch &batch = mInFlightCommands[batchIndex];
1547
1548 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001549 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1550
1551 // If timed out, report it as such.
1552 if (status == VK_TIMEOUT)
1553 {
1554 *outTimedOut = true;
1555 return angle::Result::Continue;
1556 }
1557
1558 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001559
1560 // Clean up finished batches.
1561 return checkCompletedCommands(context);
1562}
1563
Jamie Madill21061022018-07-12 23:56:30 -04001564angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1565 const vk::RenderPassDesc &desc,
1566 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001567{
Jamie Madill21061022018-07-12 23:56:30 -04001568 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001569 renderPassOut);
1570}
1571
Jamie Madill21061022018-07-12 23:56:30 -04001572angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1573 const vk::RenderPassDesc &desc,
1574 const vk::AttachmentOpsArray &ops,
1575 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001576{
Jamie Madill21061022018-07-12 23:56:30 -04001577 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001578 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001579}
1580
Jamie Madilla5e06072018-05-18 14:36:05 -04001581vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001582{
Jamie Madilla5e06072018-05-18 14:36:05 -04001583 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001584}
1585
Jamie Madill21061022018-07-12 23:56:30 -04001586angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001587{
Jamie Madill21061022018-07-12 23:56:30 -04001588 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001589 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001590}
1591
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001592angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001593{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001594 if (mCommandGraph.empty())
1595 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001596 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001597 }
1598
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001599 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1600
Jamie Madillbea35a62018-07-05 11:54:10 -04001601 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1602 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001603
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001604 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001605 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1606 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001607
1608 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1609 // will be waited on.
1610 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001611
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001612 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001613 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001614 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1615 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001616 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001617 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001618 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001619 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001620 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001621
Jamie Madill21061022018-07-12 23:56:30 -04001622 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001623
Jamie Madill7c985f52018-11-29 18:16:17 -05001624 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001625}
1626
Jamie Madill78feddc2018-04-27 11:45:05 -04001627Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001628{
Jamie Madill78feddc2018-04-27 11:45:05 -04001629 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001630}
1631
Jamie Madill21061022018-07-12 23:56:30 -04001632angle::Result RendererVk::getDescriptorSetLayout(
1633 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001634 const vk::DescriptorSetLayoutDesc &desc,
1635 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1636{
Jamie Madill21061022018-07-12 23:56:30 -04001637 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001638}
1639
Jamie Madill21061022018-07-12 23:56:30 -04001640angle::Result RendererVk::getPipelineLayout(
1641 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001642 const vk::PipelineLayoutDesc &desc,
1643 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1644 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1645{
Jamie Madill21061022018-07-12 23:56:30 -04001646 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001647 pipelineLayoutOut);
1648}
1649
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001650angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1651{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001652 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001653
1654 if (--mPipelineCacheVkUpdateTimeout > 0)
1655 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001656 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001657 }
1658
1659 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1660
1661 // Get the size of the cache.
1662 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001663 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001664 if (result != VK_INCOMPLETE)
1665 {
1666 ANGLE_VK_TRY(displayVk, result);
1667 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001668
1669 angle::MemoryBuffer *pipelineCacheData = nullptr;
1670 ANGLE_VK_CHECK_ALLOC(displayVk,
1671 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1672
1673 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001674 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001675 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1676 // was determined just above), so receiving it hints at an implementation bug we would want
1677 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001678 ASSERT(result != VK_INCOMPLETE);
1679 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001680
1681 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1682 // the buffer to avoid leaking garbage memory.
1683 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1684 if (pipelineCacheSize < originalPipelineCacheSize)
1685 {
1686 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1687 originalPipelineCacheSize - pipelineCacheSize);
1688 }
1689
1690 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1691
Jamie Madill7c985f52018-11-29 18:16:17 -05001692 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001693}
1694
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001695angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1696 const vk::Semaphore **outSemaphore)
1697{
1698 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1699
1700 vk::SemaphoreHelper semaphore;
1701 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1702
1703 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1704 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1705
Jamie Madill7c985f52018-11-29 18:16:17 -05001706 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001707}
1708
1709const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1710{
1711 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1712
1713 // Return the semaphore to the pool (which will remain valid and unused until the
1714 // queue it's about to be waited on has finished execution). The caller is about
1715 // to wait on it.
1716 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1717
1718 return semaphore;
1719}
1720
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001721angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1722{
1723 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1724 // that seems impossible, so instead, we are going to make a small submission with just a
1725 // timestamp query. First, the disjoint timer query extension says:
1726 //
1727 // > This will return the GL time after all previous commands have reached the GL server but
1728 // have not yet necessarily executed.
1729 //
1730 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1731 // The wording allows us to make a submission to get the timestamp without performing a flush.
1732 //
1733 // Second:
1734 //
1735 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1736 // object target, applications can measure the latency between when commands reach the GL server
1737 // and when they are realized in the framebuffer.
1738 //
1739 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1740 // GPU bubble. This function directly generates a command buffer and submits it instead of
1741 // using the other member functions. This is to avoid changing any state, such as the queue
1742 // serial.
1743
1744 // Create a query used to receive the GPU timestamp
1745 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1746 vk::QueryHelper timestampQuery;
1747 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1748 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1749
1750 // Record the command buffer
1751 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1752 vk::CommandBuffer &commandBuffer = commandBatch.get();
1753
1754 VkCommandBufferAllocateInfo commandBufferInfo = {};
1755 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1756 commandBufferInfo.commandPool = mCommandPool.getHandle();
1757 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1758 commandBufferInfo.commandBufferCount = 1;
1759
Yuly Novikov27780292018-11-09 11:19:49 -05001760 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001761
1762 VkCommandBufferBeginInfo beginInfo = {};
1763 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1764 beginInfo.flags = 0;
1765 beginInfo.pInheritanceInfo = nullptr;
1766
Yuly Novikov27780292018-11-09 11:19:49 -05001767 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001768
1769 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1770 timestampQuery.getQuery(), 1);
1771 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1772 timestampQuery.getQueryPool()->getHandle(),
1773 timestampQuery.getQuery());
1774
Yuly Novikov27780292018-11-09 11:19:49 -05001775 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001776
1777 // Create fence for the submission
1778 VkFenceCreateInfo fenceInfo = {};
1779 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1780 fenceInfo.flags = 0;
1781
1782 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001783 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001784
1785 // Submit the command buffer
1786 VkSubmitInfo submitInfo = {};
1787 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1788 submitInfo.waitSemaphoreCount = 0;
1789 submitInfo.pWaitSemaphores = nullptr;
1790 submitInfo.pWaitDstStageMask = nullptr;
1791 submitInfo.commandBufferCount = 1;
1792 submitInfo.pCommandBuffers = commandBuffer.ptr();
1793 submitInfo.signalSemaphoreCount = 0;
1794 submitInfo.pSignalSemaphores = nullptr;
1795
1796 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1797
1798 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1799 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001800 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001801
1802 // Get the query results
1803 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1804
Yuly Novikov27780292018-11-09 11:19:49 -05001805 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1806 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1807 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001808
1809 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1810
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001811 // Convert results to nanoseconds.
1812 *timestampOut = static_cast<uint64_t>(
1813 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1814
Jamie Madill7c985f52018-11-29 18:16:17 -05001815 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001816}
1817
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001818// These functions look at the mandatory format for support, and fallback to querying the device (if
1819// necessary) to test the availability of the bits.
1820bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1821 const VkFormatFeatureFlags featureBits)
1822{
1823 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1824}
1825
1826bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1827 const VkFormatFeatureFlags featureBits)
1828{
1829 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1830}
1831
1832bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1833{
1834 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1835}
1836
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001837angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1838{
1839 ASSERT(mGpuEventsEnabled);
1840
1841 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1842 ASSERT(platform);
1843
1844 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1845 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1846 //
1847 // CPU GPU
1848 //
1849 // Record command buffer
1850 // with timestamp query
1851 //
1852 // Submit command buffer
1853 //
1854 // Post-submission work Begin execution
1855 //
Tobin Ehlis5546fb42019-01-17 12:25:54 -05001856 // ???? Write timestamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001857 //
1858 // ???? End execution
1859 //
1860 // ???? Return query results
1861 //
1862 // ????
1863 //
1864 // Get query results
1865 //
1866 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1867 // finished post-submission work while the GPU is executing in parallel. With no further work,
1868 // querying CPU timestamps before submission and after getting query results give the bounds to
1869 // Tgpu, which could be quite large.
1870 //
1871 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1872 // reduce this range. This function implements the following procedure:
1873 //
1874 // CPU GPU
1875 //
1876 // Record command buffer
1877 // with timestamp query
1878 //
1879 // Submit command buffer
1880 //
1881 // Post-submission work Begin execution
1882 //
1883 // ???? Set Event GPUReady
1884 //
1885 // Wait on Event GPUReady Wait on Event CPUReady
1886 //
1887 // Get CPU Time Ts Wait on Event CPUReady
1888 //
1889 // Set Event CPUReady Wait on Event CPUReady
1890 //
1891 // Get CPU Time Tcpu Get GPU Time Tgpu
1892 //
1893 // Wait on Event GPUDone Set Event GPUDone
1894 //
1895 // Get CPU Time Te End Execution
1896 //
1897 // Idle Return query results
1898 //
1899 // Get query results
1900 //
1901 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1902 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1903 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1904 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1905 // calibration.
1906 //
1907 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1908
1909 // Make sure nothing is running
1910 ASSERT(mCommandGraph.empty());
1911
1912 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1913
1914 // Create a query used to receive the GPU timestamp
1915 vk::QueryHelper timestampQuery;
1916 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1917
1918 // Create the three events
1919 VkEventCreateInfo eventCreateInfo = {};
1920 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1921 eventCreateInfo.flags = 0;
1922
1923 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001924 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1925 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1926 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001927
1928 constexpr uint32_t kRetries = 10;
1929
1930 // Time suffixes used are S for seconds and Cycles for cycles
1931 double tightestRangeS = 1e6f;
1932 double TcpuS = 0;
1933 uint64_t TgpuCycles = 0;
1934 for (uint32_t i = 0; i < kRetries; ++i)
1935 {
1936 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001937 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1938 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1939 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001940
1941 // Record the command buffer
1942 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1943 vk::CommandBuffer &commandBuffer = commandBatch.get();
1944
1945 VkCommandBufferAllocateInfo commandBufferInfo = {};
1946 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1947 commandBufferInfo.commandPool = mCommandPool.getHandle();
1948 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1949 commandBufferInfo.commandBufferCount = 1;
1950
Yuly Novikov27780292018-11-09 11:19:49 -05001951 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001952
1953 VkCommandBufferBeginInfo beginInfo = {};
1954 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1955 beginInfo.flags = 0;
1956 beginInfo.pInheritanceInfo = nullptr;
1957
Yuly Novikov27780292018-11-09 11:19:49 -05001958 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001959
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001960 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001961 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1962 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1963 nullptr);
1964
1965 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1966 timestampQuery.getQuery(), 1);
1967 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1968 timestampQuery.getQueryPool()->getHandle(),
1969 timestampQuery.getQuery());
1970
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001971 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001972
Yuly Novikov27780292018-11-09 11:19:49 -05001973 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001974
1975 // Submit the command buffer
1976 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1977 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1978 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1979
1980 VkSubmitInfo submitInfo = {};
1981 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1982 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1983 submitInfo.pWaitSemaphores = waitSemaphores.data();
1984 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1985 submitInfo.commandBufferCount = 1;
1986 submitInfo.pCommandBuffers = commandBuffer.ptr();
1987 submitInfo.signalSemaphoreCount = 0;
1988 submitInfo.pSignalSemaphores = nullptr;
1989
1990 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1991
1992 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001993 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001994 do
1995 {
Yuly Novikov27780292018-11-09 11:19:49 -05001996 result = gpuReady.get().getStatus(mDevice);
1997 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1998 {
1999 ANGLE_VK_TRY(context, result);
2000 }
2001 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002002
2003 double TsS = platform->monotonicallyIncreasingTime(platform);
2004
2005 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05002006 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002007 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
2008
2009 // Wait for GPU to be done. Another short busy wait.
2010 do
2011 {
Yuly Novikov27780292018-11-09 11:19:49 -05002012 result = gpuDone.get().getStatus(mDevice);
2013 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
2014 {
2015 ANGLE_VK_TRY(context, result);
2016 }
2017 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002018
2019 double TeS = platform->monotonicallyIncreasingTime(platform);
2020
2021 // Get the query results
2022 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
2023
2024 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
2025
2026 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002027 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
2028 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
2029 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002030
2031 // Use the first timestamp queried as origin.
2032 if (mGpuEventTimestampOrigin == 0)
2033 {
2034 mGpuEventTimestampOrigin = gpuTimestampCycles;
2035 }
2036
2037 // Take these CPU and GPU timestamps if there is better confidence.
2038 double confidenceRangeS = TeS - TsS;
2039 if (confidenceRangeS < tightestRangeS)
2040 {
2041 tightestRangeS = confidenceRangeS;
2042 TcpuS = cpuTimestampS;
2043 TgpuCycles = gpuTimestampCycles;
2044 }
2045 }
2046
2047 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
2048
2049 // timestampPeriod gives nanoseconds/cycle.
2050 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
2051 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
2052 1'000'000'000.0;
2053
2054 flushGpuEvents(TgpuS, TcpuS);
2055
2056 mGpuClockSync.gpuTimestampS = TgpuS;
2057 mGpuClockSync.cpuTimestampS = TcpuS;
2058
Jamie Madill7c985f52018-11-29 18:16:17 -05002059 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002060}
2061
2062angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
2063 vk::CommandBuffer *commandBuffer,
2064 char phase,
2065 const char *name)
2066{
2067 ASSERT(mGpuEventsEnabled);
2068
2069 GpuEventQuery event;
2070
2071 event.name = name;
2072 event.phase = phase;
2073 event.serial = mCurrentQueueSerial;
2074
2075 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
2076
2077 commandBuffer->resetQueryPool(
2078 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
2079 commandBuffer->writeTimestamp(
2080 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2081 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
2082
2083 mInFlightGpuEventQueries.push_back(std::move(event));
2084
Jamie Madill7c985f52018-11-29 18:16:17 -05002085 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002086}
2087
2088angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
2089{
2090 ASSERT(mGpuEventsEnabled);
2091
2092 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2093 ASSERT(platform);
2094
2095 int finishedCount = 0;
2096
2097 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2098 {
2099 // Only check the timestamp query if the submission has finished.
2100 if (eventQuery.serial > mLastCompletedQueueSerial)
2101 {
2102 break;
2103 }
2104
2105 // See if the results are available.
2106 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002107 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2108 ->getResults(mDevice, eventQuery.queryIndex, 1,
2109 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2110 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2111 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002112 {
2113 break;
2114 }
Yuly Novikov27780292018-11-09 11:19:49 -05002115 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002116
2117 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2118
2119 GpuEvent event;
2120 event.gpuTimestampCycles = gpuTimestampCycles;
2121 event.name = eventQuery.name;
2122 event.phase = eventQuery.phase;
2123
2124 mGpuEvents.emplace_back(event);
2125
2126 ++finishedCount;
2127 }
2128
2129 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2130 mInFlightGpuEventQueries.begin() + finishedCount);
2131
Jamie Madill7c985f52018-11-29 18:16:17 -05002132 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002133}
2134
2135void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2136{
2137 if (mGpuEvents.size() == 0)
2138 {
2139 return;
2140 }
2141
2142 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2143 ASSERT(platform);
2144
2145 // Find the slope of the clock drift for adjustment
2146 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2147 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2148 double gpuSyncDriftSlope = 0;
2149
2150 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2151 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2152
2153 // No gpu trace events should have been generated before the clock sync, so if there is no
2154 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2155 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2156 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2157
2158 gpuSyncDriftSlope =
2159 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2160
2161 for (const GpuEvent &event : mGpuEvents)
2162 {
2163 double gpuTimestampS =
2164 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2165 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2166
2167 // Account for clock drift.
2168 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2169
2170 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2171 // for.
2172 static long long eventId = 1;
2173 static const unsigned char *categoryEnabled =
2174 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2175 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2176 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2177 }
2178
2179 mGpuEvents.clear();
2180}
2181
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002182template <VkFormatFeatureFlags VkFormatProperties::*features>
2183bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2184{
2185 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2186 VkFormatProperties &deviceProperties = mFormatProperties[format];
2187
2188 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2189 {
2190 // If we don't have the actual device features, see if the requested features are mandatory.
2191 // If so, there's no need to query the device.
2192 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2193 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2194 {
2195 return true;
2196 }
2197
2198 // Otherwise query the format features and cache it.
2199 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2200 }
2201
2202 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2203}
2204
Jamie Madillaaca96e2018-06-12 10:19:48 -04002205uint32_t GetUniformBufferDescriptorCount()
2206{
2207 return kUniformBufferDescriptorsPerDescriptorSet;
2208}
2209
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002210} // namespace rx