blob: de1f8dbc32a88ef267e49596ce5412ee907feacc [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 Ehlis134425c2019-03-15 17:02:17 -060044constexpr size_t kDefaultPoolAllocatorPageSize = 16 * 1024;
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070045} // anonymous namespace
46
Jamie Madill9e54b5a2016-05-25 12:57:39 -040047namespace rx
48{
49
Jamie Madille09bd5d2016-11-29 16:20:35 -050050namespace
51{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040052// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
53// one for the vertex shader.
54constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040055// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050056constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040057// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050058constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Ian Elliott356d26c2019-02-11 11:27:01 -070059// Per the Vulkan specification, as long as Vulkan 1.1+ is returned by vkEnumerateInstanceVersion,
60// ANGLE must indicate the highest version of Vulkan functionality that it uses. The Vulkan
61// validation layers will issue messages for any core functionality that requires a higher version.
62// This value must be increased whenever ANGLE starts using functionality from a newer core
63// version of Vulkan.
64constexpr uint32_t kPreferredVulkanAPIVersion = VK_API_VERSION_1_1;
Jamie Madille09bd5d2016-11-29 16:20:35 -050065
Omar El Sheikh26c61b22018-06-29 12:50:59 -060066bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
67{
68#if !defined(ANGLE_PLATFORM_ANDROID)
69 // Mock ICD does not currently run on Android
70 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
71 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
72 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
73#else
74 return false;
75#endif // !defined(ANGLE_PLATFORM_ANDROID)
76}
77
Frank Henigman52047de2018-11-13 17:22:36 -050078bool StrLess(const char *a, const char *b)
Jamie Madille09bd5d2016-11-29 16:20:35 -050079{
Frank Henigman52047de2018-11-13 17:22:36 -050080 return strcmp(a, b) < 0;
Jamie Madille09bd5d2016-11-29 16:20:35 -050081}
82
Frank Henigman52047de2018-11-13 17:22:36 -050083bool ExtensionFound(const char *needle, const RendererVk::ExtensionNameList &haystack)
84{
85 // NOTE: The list must be sorted.
86 return std::binary_search(haystack.begin(), haystack.end(), needle, StrLess);
Tobin Ehlis3a181e32018-08-29 15:17:05 -060087}
88
Yuly Novikovdbbdf562019-02-27 19:48:16 -050089VkResult VerifyExtensionsPresent(const RendererVk::ExtensionNameList &haystack,
90 const RendererVk::ExtensionNameList &needles)
91{
92 // NOTE: The lists must be sorted.
93 if (std::includes(haystack.begin(), haystack.end(), needles.begin(), needles.end(), StrLess))
94 {
95 return VK_SUCCESS;
96 }
97 for (const char *needle : needles)
98 {
99 if (!ExtensionFound(needle, haystack))
100 {
101 ERR() << "Extension not supported: " << needle;
102 }
103 }
104 return VK_ERROR_EXTENSION_NOT_PRESENT;
105}
106
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500107// Array of Validation error/warning messages that will be ignored, should include bugID
Jamie Madill00f43c92019-02-09 11:41:12 -0500108constexpr const char *kSkippedMessages[] = {
109 // http://anglebug.com/2866
110 "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500111 // http://anglebug.com/2796
Jamie Madill00f43c92019-02-09 11:41:12 -0500112 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing",
113};
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500114
115// Suppress validation errors that are known
116// return "true" if given code/prefix/message is known, else return "false"
117bool IsIgnoredDebugMessage(const char *message)
118{
Michael Spang25839802019-01-30 18:02:51 -0500119 if (!message)
120 {
121 return false;
122 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500123 for (const char *msg : kSkippedMessages)
124 {
125 if (strstr(message, msg) != nullptr)
126 {
127 return true;
128 }
129 }
130 return false;
131}
132
133const char *GetVkObjectTypeName(VkObjectType type)
134{
135 switch (type)
136 {
137 case VK_OBJECT_TYPE_UNKNOWN:
138 return "Unknown";
139 case VK_OBJECT_TYPE_INSTANCE:
140 return "Instance";
141 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
142 return "Physical Device";
143 case VK_OBJECT_TYPE_DEVICE:
144 return "Device";
145 case VK_OBJECT_TYPE_QUEUE:
146 return "Queue";
147 case VK_OBJECT_TYPE_SEMAPHORE:
148 return "Semaphore";
149 case VK_OBJECT_TYPE_COMMAND_BUFFER:
150 return "Command Buffer";
151 case VK_OBJECT_TYPE_FENCE:
152 return "Fence";
153 case VK_OBJECT_TYPE_DEVICE_MEMORY:
154 return "Device Memory";
155 case VK_OBJECT_TYPE_BUFFER:
156 return "Buffer";
157 case VK_OBJECT_TYPE_IMAGE:
158 return "Image";
159 case VK_OBJECT_TYPE_EVENT:
160 return "Event";
161 case VK_OBJECT_TYPE_QUERY_POOL:
162 return "Query Pool";
163 case VK_OBJECT_TYPE_BUFFER_VIEW:
164 return "Buffer View";
165 case VK_OBJECT_TYPE_IMAGE_VIEW:
166 return "Image View";
167 case VK_OBJECT_TYPE_SHADER_MODULE:
168 return "Shader Module";
169 case VK_OBJECT_TYPE_PIPELINE_CACHE:
170 return "Pipeline Cache";
171 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
172 return "Pipeline Layout";
173 case VK_OBJECT_TYPE_RENDER_PASS:
174 return "Render Pass";
175 case VK_OBJECT_TYPE_PIPELINE:
176 return "Pipeline";
177 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
178 return "Descriptor Set Layout";
179 case VK_OBJECT_TYPE_SAMPLER:
180 return "Sampler";
181 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
182 return "Descriptor Pool";
183 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
184 return "Descriptor Set";
185 case VK_OBJECT_TYPE_FRAMEBUFFER:
186 return "Framebuffer";
187 case VK_OBJECT_TYPE_COMMAND_POOL:
188 return "Command Pool";
189 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
190 return "Sampler YCbCr Conversion";
191 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
192 return "Descriptor Update Template";
193 case VK_OBJECT_TYPE_SURFACE_KHR:
194 return "Surface";
195 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
196 return "Swapchain";
197 case VK_OBJECT_TYPE_DISPLAY_KHR:
198 return "Display";
199 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
200 return "Display Mode";
201 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
202 return "Debug Report Callback";
203 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
204 return "Object Table";
205 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
206 return "Indirect Commands Layout";
207 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
208 return "Debug Utils Messenger";
209 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
210 return "Validation Cache";
Shahbaz Youssefi6f1a8522019-02-26 15:00:54 +0000211 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV:
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500212 return "Acceleration Structure";
213 default:
214 return "<Unrecognized>";
215 }
216}
217
218VKAPI_ATTR VkBool32 VKAPI_CALL
219DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
220 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
221 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
222 void *userData)
223{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500224 // See if it's an issue we are aware of and don't want to be spammed about.
225 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
226 {
227 return VK_FALSE;
228 }
229
230 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500231 if (callbackData->pMessageIdName)
232 {
233 log << "[ " << callbackData->pMessageIdName << " ] ";
234 }
235 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500236
237 // Aesthetic value based on length of the function name, line number, etc.
238 constexpr size_t kStartIndent = 28;
239
240 // Output the debug marker hierarchy under which this error has occured.
241 size_t indent = kStartIndent;
242 if (callbackData->queueLabelCount > 0)
243 {
244 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
245 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
246 {
247 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
248 << std::endl;
249 }
250 }
251 if (callbackData->cmdBufLabelCount > 0)
252 {
253 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
254 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
255 {
256 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
257 << std::endl;
258 }
259 }
260 // Output the objects involved in this error message.
261 if (callbackData->objectCount > 0)
262 {
263 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
264 {
265 const char *objectName = callbackData->pObjects[i].pObjectName;
266 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
267 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
268 log << std::string(indent, ' ') << "Object: ";
269 if (objectHandle == 0)
270 {
271 log << "VK_NULL_HANDLE";
272 }
273 else
274 {
275 log << "0x" << std::hex << objectHandle << std::dec;
276 }
277 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
278 if (objectName)
279 {
280 log << " [" << objectName << "]";
281 }
282 log << std::endl;
283 }
284 }
285
Jamie Madill54ed8f02019-02-11 12:32:04 -0500286 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
287 std::string msg = log.str();
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500288
289 if (isError)
290 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500291 ERR() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500292 }
293 else
294 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500295 WARN() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500296 }
297
298 return VK_FALSE;
299}
300
Yuly Novikov199f4292018-01-19 19:04:05 -0500301VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
302 VkDebugReportObjectTypeEXT objectType,
303 uint64_t object,
304 size_t location,
305 int32_t messageCode,
306 const char *layerPrefix,
307 const char *message,
308 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500309{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600310 if (IsIgnoredDebugMessage(message))
311 {
312 return VK_FALSE;
313 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500314 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
315 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500316 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500317#if !defined(NDEBUG)
318 // Abort the call in Debug builds.
319 return VK_TRUE;
320#endif
321 }
322 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
323 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500324 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500325 }
326 else
327 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500328 // Uncomment this if you want Vulkan spam.
329 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500330 }
331
332 return VK_FALSE;
333}
334
Yuly Novikov199f4292018-01-19 19:04:05 -0500335// If we're loading the validation layers, we could be running from any random directory.
336// Change to the executable directory so we can find the layers, then change back to the
337// previous directory to be safe we don't disrupt the application.
338class ScopedVkLoaderEnvironment : angle::NonCopyable
339{
340 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600341 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
342 : mEnableValidationLayers(enableValidationLayers),
343 mEnableMockICD(enableMockICD),
344 mChangedCWD(false),
345 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500346 {
347// Changing CWD and setting environment variables makes no sense on Android,
348// since this code is a part of Java application there.
349// Android Vulkan loader doesn't need this either.
Michael Spang229fc832019-01-21 18:09:15 -0500350#if !defined(ANGLE_PLATFORM_ANDROID) && !defined(ANGLE_PLATFORM_FUCHSIA)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600351 if (enableMockICD)
352 {
353 // Override environment variable to use built Mock ICD
354 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
355 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
356 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
357 if (!mChangedICDPath)
358 {
359 ERR() << "Error setting Path for Mock/Null Driver.";
360 mEnableMockICD = false;
361 }
362 }
Jamie Madill46848422018-08-09 10:46:06 -0400363 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500364 {
365 const auto &cwd = angle::GetCWD();
366 if (!cwd.valid())
367 {
368 ERR() << "Error getting CWD for Vulkan layers init.";
369 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400370 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500371 }
372 else
373 {
374 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500375 std::string exeDir = angle::GetExecutableDirectory();
376 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500377 if (!mChangedCWD)
378 {
379 ERR() << "Error setting CWD for Vulkan layers init.";
380 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400381 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500382 }
383 }
384 }
385
386 // Override environment variable to use the ANGLE layers.
387 if (mEnableValidationLayers)
388 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700389 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500390 {
391 ERR() << "Error setting environment for Vulkan layers init.";
392 mEnableValidationLayers = false;
393 }
394 }
395#endif // !defined(ANGLE_PLATFORM_ANDROID)
396 }
397
398 ~ScopedVkLoaderEnvironment()
399 {
400 if (mChangedCWD)
401 {
402#if !defined(ANGLE_PLATFORM_ANDROID)
403 ASSERT(mPreviousCWD.valid());
404 angle::SetCWD(mPreviousCWD.value().c_str());
405#endif // !defined(ANGLE_PLATFORM_ANDROID)
406 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600407 if (mChangedICDPath)
408 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600409 if (mPreviousICDPath.value().empty())
410 {
411 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
412 }
413 else
414 {
415 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
416 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600417 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500418 }
419
Jamie Madillaaca96e2018-06-12 10:19:48 -0400420 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500421
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600422 bool canEnableMockICD() const { return mEnableMockICD; }
423
Yuly Novikov199f4292018-01-19 19:04:05 -0500424 private:
425 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500427 bool mChangedCWD;
428 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600429 bool mChangedICDPath;
430 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500431};
432
Jamie Madill21061022018-07-12 23:56:30 -0400433void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
434 bool preferMockICD,
435 VkPhysicalDevice *physicalDeviceOut,
436 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
437{
438 ASSERT(!physicalDevices.empty());
439 if (preferMockICD)
440 {
441 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
442 {
443 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
444 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
445 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
446 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
447 {
448 *physicalDeviceOut = physicalDevice;
449 return;
450 }
451 }
452 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
453 "physicalDevice instead.";
454 }
455
456 // Fall back to first device.
457 *physicalDeviceOut = physicalDevices[0];
458 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
459}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400460
461// Initially dumping the command graphs is disabled.
462constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700463
Jamie Madille09bd5d2016-11-29 16:20:35 -0500464} // anonymous namespace
465
Jamie Madill49ac74b2017-12-21 14:42:33 -0500466// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400467RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500468
Jamie Madillaaca96e2018-06-12 10:19:48 -0400469RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500470
471RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -0500472{
473 *this = std::move(other);
474}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500475
476RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
477{
478 std::swap(commandPool, other.commandPool);
479 std::swap(fence, other.fence);
480 std::swap(serial, other.serial);
481 return *this;
482}
483
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000484void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400485{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000486 commandPool.destroy(device);
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -0500487 fence.reset(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400488}
489
Jamie Madill9f2a8612017-11-30 12:43:09 -0500490// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500491RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400492 : mDisplay(nullptr),
493 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700494 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500495 mInstance(VK_NULL_HANDLE),
496 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400497 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500498 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500499 mDebugReportCallback(VK_NULL_HANDLE),
500 mPhysicalDevice(VK_NULL_HANDLE),
501 mQueue(VK_NULL_HANDLE),
502 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
Frank Henigman52047de2018-11-13 17:22:36 -0500503 mMaxVertexAttribDivisor(1),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500504 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400505 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400506 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400507 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400508 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Tobin Ehlis134425c2019-03-15 17:02:17 -0600509 mPoolAllocator(kDefaultPoolAllocatorPageSize),
510 mCommandGraph(kEnableCommandGraphDiagnostics, &mPoolAllocator),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400511 mGpuEventsEnabled(false),
512 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
513 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500514{
515 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
516 mFormatProperties.fill(invalid);
517}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400518
Jamie Madillb980c562018-11-27 11:34:27 -0500519RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400520
521void RendererVk::onDestroy(vk::Context *context)
522{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500523 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500524 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500525 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400526 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500527 }
528
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100529 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500530
Jamie Madillc7918ce2018-06-13 13:25:31 -0400531 mPipelineLayoutCache.destroy(mDevice);
532 mDescriptorSetLayoutCache.destroy(mDevice);
533
Jamie Madill9f2a8612017-11-30 12:43:09 -0500534 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500535 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400536 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400537 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400538 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500539
Jamie Madill06ca6342018-07-12 15:56:53 -0400540 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500541
Jamie Madill5deea722017-02-16 10:44:46 -0500542 if (mCommandPool.valid())
543 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000544 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500545 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500546
547 if (mDevice)
548 {
549 vkDestroyDevice(mDevice, nullptr);
550 mDevice = VK_NULL_HANDLE;
551 }
552
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500553 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500554 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500555 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
556 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
557
558 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
559 }
560 else if (mDebugReportCallback)
561 {
562 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
563 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500564 }
565
Jamie Madill4d0bf552016-12-28 15:45:24 -0500566 if (mInstance)
567 {
568 vkDestroyInstance(mInstance, nullptr);
569 mInstance = VK_NULL_HANDLE;
570 }
571
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600572 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500573 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500574}
575
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400576void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400577{
578 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400579
580 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500581 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400582 freeAllInFlightResources();
583
584 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400585}
586
587bool RendererVk::isDeviceLost() const
588{
589 return mDeviceLost;
590}
591
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400592angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400593 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500594 const char *wsiExtension,
595 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500596{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400597 mDisplay = display;
598 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600599 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
600 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500601 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400602 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500603
Jamie Madill0448ec82016-12-23 13:41:47 -0500604 // Gather global layer properties.
605 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400606 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500607
608 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
609 if (instanceLayerCount > 0)
610 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400611 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
612 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500613 }
614
Michael Spang6c13c702019-02-06 15:59:44 -0500615 VulkanLayerVector enabledInstanceLayerNames;
616 if (mEnableValidationLayers)
617 {
618 bool layersRequested =
619 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
620 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
621 &enabledInstanceLayerNames);
622 }
623
624 if (wsiLayer)
625 {
626 enabledInstanceLayerNames.push_back(wsiLayer);
627 }
628
629 // Enumerate instance extensions that are provided by the vulkan
630 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500631 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400632 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400633 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500634
635 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
636 if (instanceExtensionCount > 0)
637 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400638 ANGLE_VK_TRY(displayVk,
639 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
640 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500641 }
642
Michael Spang6c13c702019-02-06 15:59:44 -0500643 // Enumerate instance extensions that are provided by explicit layers.
644 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500645 {
Michael Spang6c13c702019-02-06 15:59:44 -0500646 uint32_t previousExtensionCount = instanceExtensionProps.size();
647 uint32_t instanceLayerExtensionCount = 0;
648 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
649 layerName, &instanceLayerExtensionCount, nullptr));
650 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
651 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
652 layerName, &instanceLayerExtensionCount,
653 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500654 }
655
Frank Henigman52047de2018-11-13 17:22:36 -0500656 ExtensionNameList instanceExtensionNames;
657 if (!instanceExtensionProps.empty())
658 {
659 for (const VkExtensionProperties &i : instanceExtensionProps)
660 {
661 instanceExtensionNames.push_back(i.extensionName);
662 }
663 std::sort(instanceExtensionNames.begin(), instanceExtensionNames.end(), StrLess);
664 }
665
666 ExtensionNameList enabledInstanceExtensions;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500667 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500668 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500669
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500670 bool enableDebugUtils =
671 mEnableValidationLayers &&
Frank Henigman52047de2018-11-13 17:22:36 -0500672 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionNames);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500673 bool enableDebugReport =
674 mEnableValidationLayers && !enableDebugUtils &&
Frank Henigman52047de2018-11-13 17:22:36 -0500675 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionNames);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500676
677 if (enableDebugUtils)
678 {
679 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
680 }
681 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500682 {
683 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
684 }
685
Jamie Madille09bd5d2016-11-29 16:20:35 -0500686 // Verify the required extensions are in the extension names set. Fail if not.
Frank Henigman52047de2018-11-13 17:22:36 -0500687 std::sort(enabledInstanceExtensions.begin(), enabledInstanceExtensions.end(), StrLess);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400688 ANGLE_VK_TRY(displayVk,
Frank Henigman52047de2018-11-13 17:22:36 -0500689 VerifyExtensionsPresent(instanceExtensionNames, enabledInstanceExtensions));
690
691 // Enable VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME if available.
692 if (ExtensionFound(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
693 instanceExtensionNames))
694 {
695 enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
696 }
Jamie Madille09bd5d2016-11-29 16:20:35 -0500697
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400698 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500699 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500700 applicationInfo.pApplicationName = "ANGLE";
701 applicationInfo.applicationVersion = 1;
702 applicationInfo.pEngineName = "ANGLE";
703 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700704
705 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
706 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
707 if (!enumerateInstanceVersion)
708 {
709 applicationInfo.apiVersion = VK_API_VERSION_1_0;
710 }
711 else
712 {
713 uint32_t apiVersion = VK_API_VERSION_1_0;
714 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
715 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
716 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700717 // This is the highest version of core Vulkan functionality that ANGLE uses.
718 applicationInfo.apiVersion = kPreferredVulkanAPIVersion;
Ian Elliott899c5d22018-12-21 13:12:50 -0700719 }
720 else
721 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700722 // Since only 1.0 instance-level functionality is available, this must set to 1.0.
Ian Elliott899c5d22018-12-21 13:12:50 -0700723 applicationInfo.apiVersion = VK_API_VERSION_1_0;
724 }
725 }
Jamie Madill327ba852016-11-30 12:38:28 -0500726
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400727 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500728 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
729 instanceInfo.flags = 0;
730 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500731
Jamie Madille09bd5d2016-11-29 16:20:35 -0500732 // Enable requested layers and extensions.
733 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
734 instanceInfo.ppEnabledExtensionNames =
735 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500736 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
737 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500738
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400739 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500740
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500741 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500742 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500743 // Try to use the newer EXT_debug_utils if it exists.
744 InitDebugUtilsEXTFunctions(mInstance);
745
746 // Create the messenger callback.
747 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
748
Shahbaz Youssefi4d153382019-02-26 15:08:11 +0000749 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
750 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
751 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
752
753 constexpr VkDebugUtilsMessageTypeFlagsEXT kMessagesToLog =
754 VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
755 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
756 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
757
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500758 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
Shahbaz Youssefi4d153382019-02-26 15:08:11 +0000759 messengerInfo.messageSeverity = kSeveritiesToLog;
760 messengerInfo.messageType = kMessagesToLog;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500761 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
762 messengerInfo.pUserData = this;
763
764 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
765 &mDebugUtilsMessenger));
766 }
767 else if (enableDebugReport)
768 {
769 // Fallback to EXT_debug_report.
770 InitDebugReportEXTFunctions(mInstance);
771
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400772 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500773
774 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500775 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500776 debugReportInfo.pfnCallback = &DebugReportCallback;
777 debugReportInfo.pUserData = this;
778
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500779 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
780 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500781 }
782
Frank Henigman52047de2018-11-13 17:22:36 -0500783 if (std::find(enabledInstanceExtensions.begin(), enabledInstanceExtensions.end(),
784 VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) !=
785 enabledInstanceExtensions.end())
786 {
787 InitGetPhysicalDeviceProperties2KHRFunctions(mInstance);
788 ASSERT(vkGetPhysicalDeviceProperties2KHR);
789 }
790
Jamie Madill4d0bf552016-12-28 15:45:24 -0500791 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400792 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
793 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500794
795 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700796 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400797 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
798 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400799 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700800 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500801
Jamie Madill30b5d842018-08-31 17:19:12 -0400802 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
803
Jamie Madill4d0bf552016-12-28 15:45:24 -0500804 // Ensure we can find a graphics queue family.
805 uint32_t queueCount = 0;
806 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
807
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400808 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500809
810 mQueueFamilyProperties.resize(queueCount);
811 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
812 mQueueFamilyProperties.data());
813
Jamie Madillb980c562018-11-27 11:34:27 -0500814 size_t graphicsQueueFamilyCount = false;
815 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500816 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500817 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
818 {
819 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500820 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500821 {
822 ASSERT(queueInfo.queueCount > 0);
823 graphicsQueueFamilyCount++;
824 if (firstGraphicsQueueFamily == 0)
825 {
826 firstGraphicsQueueFamily = familyIndex;
827 }
828 break;
829 }
830 }
831
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400832 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500833
834 // If only one queue family, go ahead and initialize the device. If there is more than one
835 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
836 if (graphicsQueueFamilyCount == 1)
837 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400838 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500839 }
840
Jamie Madill035fd6b2017-10-03 15:43:22 -0400841 // Store the physical device memory properties so we can find the right memory pools.
842 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500843
Jamie Madill06ca6342018-07-12 15:56:53 -0400844 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500845
Jamie Madill6a89d222017-11-02 11:59:51 -0400846 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500847 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400848
Jamie Madill7c985f52018-11-29 18:16:17 -0500849 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400850}
851
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400852angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500853{
854 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400855 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400856 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500857
858 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
859 if (deviceLayerCount > 0)
860 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400861 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
862 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500863 }
864
Michael Spang6c13c702019-02-06 15:59:44 -0500865 VulkanLayerVector enabledDeviceLayerNames;
866 if (mEnableValidationLayers)
867 {
868 mEnableValidationLayers =
869 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
870 }
871
872 const char *wsiLayer = displayVk->getWSILayer();
873 if (wsiLayer)
874 {
875 enabledDeviceLayerNames.push_back(wsiLayer);
876 }
877
878 // Enumerate device extensions that are provided by the vulkan
879 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500880 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400881 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
882 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500883
884 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
885 if (deviceExtensionCount > 0)
886 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400887 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
888 &deviceExtensionCount,
889 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500890 }
891
Michael Spang6c13c702019-02-06 15:59:44 -0500892 // Enumerate device extensions that are provided by explicit layers.
893 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500894 {
Michael Spang6c13c702019-02-06 15:59:44 -0500895 uint32_t previousExtensionCount = deviceExtensionProps.size();
896 uint32_t deviceLayerExtensionCount = 0;
897 ANGLE_VK_TRY(displayVk,
898 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
899 &deviceLayerExtensionCount, nullptr));
900 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
901 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
902 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
903 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500904 }
905
Frank Henigman52047de2018-11-13 17:22:36 -0500906 ExtensionNameList deviceExtensionNames;
907 if (!deviceExtensionProps.empty())
908 {
909 ASSERT(deviceExtensionNames.size() <= deviceExtensionProps.size());
910 for (const VkExtensionProperties &prop : deviceExtensionProps)
911 {
912 deviceExtensionNames.push_back(prop.extensionName);
913 }
914 std::sort(deviceExtensionNames.begin(), deviceExtensionNames.end(), StrLess);
915 }
916
917 ExtensionNameList enabledDeviceExtensions;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500918 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
919
Frank Henigman52047de2018-11-13 17:22:36 -0500920 initFeatures(deviceExtensionNames);
Ian Elliottbcb78902018-12-19 11:46:29 -0700921 mFeaturesInitialized = true;
922
Luc Ferronbf6dc372018-06-28 15:24:19 -0400923 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700924 if ((getFeatures().flipViewportY) &&
925 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400926 {
927 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
928 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700929 if (getFeatures().supportsIncrementalPresent)
930 {
931 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
932 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400933
Geoff Lang009696c2019-01-31 14:47:07 -0500934#if defined(ANGLE_PLATFORM_ANDROID)
935 if (getFeatures().supportsAndroidHardwareBuffer)
936 {
937 enabledDeviceExtensions.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
938 enabledDeviceExtensions.push_back(
939 VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
940 InitExternalMemoryHardwareBufferANDROIDFunctions(mInstance);
941 }
942#else
943 ASSERT(!getFeatures().supportsAndroidHardwareBuffer);
944#endif
945
Frank Henigman52047de2018-11-13 17:22:36 -0500946 std::sort(enabledDeviceExtensions.begin(), enabledDeviceExtensions.end(), StrLess);
947 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionNames, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500948
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400949 // Select additional features to be enabled
Frank Henigman52047de2018-11-13 17:22:36 -0500950 VkPhysicalDeviceFeatures2KHR enabledFeatures = {};
951 enabledFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
952 enabledFeatures.features.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
953 enabledFeatures.features.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi962c2222019-02-20 15:43:41 -0500954 enabledFeatures.features.samplerAnisotropy = mPhysicalDeviceFeatures.samplerAnisotropy;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400955
Frank Henigman52047de2018-11-13 17:22:36 -0500956 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisorFeatures = {};
957 divisorFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT;
958 divisorFeatures.vertexAttributeInstanceRateDivisor = true;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500959
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500960 float zeroPriority = 0.0f;
Frank Henigman52047de2018-11-13 17:22:36 -0500961 VkDeviceQueueCreateInfo queueCreateInfo = {};
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500962 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
963 queueCreateInfo.flags = 0;
964 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
965 queueCreateInfo.queueCount = 1;
966 queueCreateInfo.pQueuePriorities = &zeroPriority;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500967
968 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400969 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500970
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500971 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
972 createInfo.flags = 0;
973 createInfo.queueCreateInfoCount = 1;
974 createInfo.pQueueCreateInfos = &queueCreateInfo;
975 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
976 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Frank Henigman52047de2018-11-13 17:22:36 -0500977
978 if (vkGetPhysicalDeviceProperties2KHR &&
979 ExtensionFound(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, deviceExtensionNames))
980 {
981 enabledDeviceExtensions.push_back(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME);
982 enabledFeatures.pNext = &divisorFeatures;
983
984 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT divisorProperties = {};
985 divisorProperties.sType =
986 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT;
987
988 VkPhysicalDeviceProperties2 deviceProperties = {};
989 deviceProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
990 deviceProperties.pNext = &divisorProperties;
991
992 vkGetPhysicalDeviceProperties2KHR(mPhysicalDevice, &deviceProperties);
993 mMaxVertexAttribDivisor = divisorProperties.maxVertexAttribDivisor;
994
995 createInfo.pNext = &enabledFeatures;
996 }
997 else
998 {
999 createInfo.pEnabledFeatures = &enabledFeatures.features;
1000 }
1001
Jamie Madill4d0bf552016-12-28 15:45:24 -05001002 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
1003 createInfo.ppEnabledExtensionNames =
1004 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -05001005
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001006 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001007
1008 mCurrentQueueFamilyIndex = queueFamilyIndex;
1009
1010 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
1011
1012 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001013 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001014 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1015 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
1016 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001017
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001018 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001019
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001020 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001021 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001022
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001023 // Initialize the submission semaphore pool.
1024 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
1025
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001026#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
1027 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1028 ASSERT(platform);
1029
1030 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
1031 // platform discovery.
1032 const unsigned char *gpuEventsEnabled =
1033 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
1034 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
1035#endif
1036
1037 if (mGpuEventsEnabled)
1038 {
1039 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
1040 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
1041 vk::kDefaultTimestampQueryPoolSize));
1042 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
1043 }
1044
Jamie Madill7c985f52018-11-29 18:16:17 -05001045 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001046}
1047
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001048angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -04001049 VkSurfaceKHR surface,
1050 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001051{
1052 // We've already initialized a device, and can't re-create it unless it's never been used.
1053 // TODO(jmadill): Handle the re-creation case if necessary.
1054 if (mDevice != VK_NULL_HANDLE)
1055 {
1056 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
1057
1058 // Check if the current device supports present on this surface.
1059 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001060 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -04001061 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -05001062 surface, &supportsPresent));
1063
Jamie Madill6cad7732018-07-11 09:01:17 -04001064 if (supportsPresent == VK_TRUE)
1065 {
1066 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -05001067 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -04001068 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001069 }
1070
1071 // Find a graphics and present queue.
1072 Optional<uint32_t> newPresentQueue;
1073 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001074 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001075 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
1076 {
1077 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001078 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001079 {
1080 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001081 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
1082 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001083
1084 if (supportsPresent == VK_TRUE)
1085 {
1086 newPresentQueue = queueIndex;
1087 break;
1088 }
1089 }
1090 }
1091
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001092 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1093 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001094
Jamie Madill6cad7732018-07-11 09:01:17 -04001095 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001096 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001097}
1098
1099std::string RendererVk::getVendorString() const
1100{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001101 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001102}
1103
Jamie Madille09bd5d2016-11-29 16:20:35 -05001104std::string RendererVk::getRendererDescription() const
1105{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001106 std::stringstream strstr;
1107
1108 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1109
1110 strstr << "Vulkan ";
1111 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1112 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1113 strstr << VK_VERSION_PATCH(apiVersion);
1114
Olli Etuahoc6a06182018-04-13 14:11:46 +03001115 strstr << "(";
1116
1117 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1118 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1119 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1120 // driver detection.
1121 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1122 {
1123 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1124 }
1125
Geoff Langa7af56b2018-12-14 14:20:28 -05001126 strstr << mPhysicalDeviceProperties.deviceName;
1127 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1128
1129 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001130
1131 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001132}
1133
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001134gl::Version RendererVk::getMaxSupportedESVersion() const
1135{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001136 // Current highest supported version
Shahbaz Youssefi9dc8eaf2019-02-11 11:04:54 -05001137 gl::Version maxVersion = gl::Version(3, 0);
1138
1139#if ANGLE_VULKAN_CONFORMANT_CONFIGS_ONLY
1140 // TODO: Disallow ES 3.0 until supported. http://crbug.com/angleproject/2950
1141 maxVersion = gl::Version(2, 0);
1142#endif
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001143
Geoff Lang0c2c9232019-01-14 16:01:38 -05001144 // Vulkan inherited queries are required to support any GL query type
1145 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001146 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001147 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001148 }
1149
Geoff Lang0c2c9232019-01-14 16:01:38 -05001150 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001151}
1152
Frank Henigman52047de2018-11-13 17:22:36 -05001153void RendererVk::initFeatures(const ExtensionNameList &deviceExtensionNames)
Jamie Madill12222072018-07-11 14:59:48 -04001154{
Jamie Madillb36a4812018-09-25 10:15:11 -04001155// Use OpenGL line rasterization rules by default.
1156// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1157#if defined(ANGLE_PLATFORM_ANDROID)
1158 mFeatures.basicGLLineRasterization = false;
1159#else
Jamie Madill12222072018-07-11 14:59:48 -04001160 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001161#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001162
Ian Elliott52f5da42018-12-21 09:02:09 -07001163 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
Frank Henigman52047de2018-11-13 17:22:36 -05001164 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionNames))
Ian Elliottd50521f2018-12-20 12:05:14 -07001165 {
1166 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1167 // investigation. http://anglebug.com/2728
1168 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1169 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001170
1171#ifdef ANGLE_PLATFORM_WINDOWS
1172 // http://anglebug.com/2838
1173 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001174
1175 // http://anglebug.com/3055
1176 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001177#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001178
1179 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1180 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001181
1182 // Work around incorrect NVIDIA point size range clamping.
1183 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1184 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1185 {
1186 mFeatures.clampPointSize = true;
1187 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001188
Jamie Madillfa7ca182019-01-15 11:20:58 -05001189 // We also need to clamp point size on several Android drivers.
1190 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1191 if (IsAndroid())
1192 {
1193 mFeatures.clampPointSize = true;
1194 }
1195
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001196#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001197 // Work around ineffective compute-graphics barriers on Nexus 5X.
1198 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1199 // http://anglebug.com/3019
1200 mFeatures.flushAfterVertexConversion =
1201 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001202#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001203
Frank Henigman52047de2018-11-13 17:22:36 -05001204 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionNames))
Ian Elliottbcb78902018-12-19 11:46:29 -07001205 {
1206 mFeatures.supportsIncrementalPresent = true;
1207 }
Geoff Lang009696c2019-01-31 14:47:07 -05001208
1209#if defined(ANGLE_PLATFORM_ANDROID)
Yuly Novikovdbbdf562019-02-27 19:48:16 -05001210 mFeatures.supportsAndroidHardwareBuffer =
1211 ExtensionFound(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME,
1212 deviceExtensionNames) &&
1213 ExtensionFound(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, deviceExtensionNames);
Geoff Lang009696c2019-01-31 14:47:07 -05001214#endif
Yuly Novikov1581ff02019-02-28 20:59:26 -05001215
1216 if (IsLinux() && IsIntel(mPhysicalDeviceProperties.vendorID))
1217 {
1218 mFeatures.disableFifoPresentMode = true;
1219 }
Jamie Madill12222072018-07-11 14:59:48 -04001220}
1221
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001222void RendererVk::initPipelineCacheVkKey()
1223{
1224 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1225 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1226 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1227 // there is no '\0' in the result.
1228 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1229 {
1230 hashStream << std::hex << c;
1231 }
1232 // Add the vendor and device id too for good measure.
1233 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1234 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1235
1236 const std::string &hashString = hashStream.str();
1237 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1238 hashString.length(), mPipelineCacheVkBlobKey.data());
1239}
1240
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001241angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001242{
1243 initPipelineCacheVkKey();
1244
1245 egl::BlobCache::Value initialData;
1246 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1247 mPipelineCacheVkBlobKey, &initialData);
1248
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001249 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001250
1251 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001252 pipelineCacheCreateInfo.flags = 0;
1253 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1254 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1255
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001256 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001257 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001258}
1259
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001260void RendererVk::getSubmitWaitSemaphores(
1261 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001262 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1263 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001264{
1265 if (mSubmitLastSignaledSemaphore.getSemaphore())
1266 {
1267 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001268 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001269
1270 // Return the semaphore to the pool (which will remain valid and unused until the
1271 // queue it's about to be waited on has finished execution).
1272 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1273 }
1274
1275 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1276 {
1277 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001278 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1279
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001280 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1281 }
1282 mSubmitWaitSemaphores.clear();
1283}
1284
Jamie Madillacccc6c2016-05-03 17:22:10 -04001285const gl::Caps &RendererVk::getNativeCaps() const
1286{
1287 ensureCapsInitialized();
1288 return mNativeCaps;
1289}
1290
1291const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1292{
1293 ensureCapsInitialized();
1294 return mNativeTextureCaps;
1295}
1296
1297const gl::Extensions &RendererVk::getNativeExtensions() const
1298{
1299 ensureCapsInitialized();
1300 return mNativeExtensions;
1301}
1302
1303const gl::Limitations &RendererVk::getNativeLimitations() const
1304{
1305 ensureCapsInitialized();
1306 return mNativeLimitations;
1307}
1308
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001309uint32_t RendererVk::getMaxActiveTextures()
1310{
1311 // TODO(lucferron): expose this limitation to GL in Context Caps
1312 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1313 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1314}
1315
Jamie Madill49ac74b2017-12-21 14:42:33 -05001316const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001317{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001319}
1320
Jamie Madill21061022018-07-12 23:56:30 -04001321angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001322{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001323 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001324 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001325 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1326
Luc Ferron1617e692018-07-11 11:08:19 -04001327 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1328 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001329
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001330 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001331 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1332 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001333
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001334 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001335 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001336 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1337 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001338 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001339 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001340 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001341 submitInfo.signalSemaphoreCount = 0;
1342 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001343
Jamie Madill21061022018-07-12 23:56:30 -04001344 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001345 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001346
Jamie Madill4c26fc22017-02-24 11:04:10 -05001347 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001348 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001349 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001350
1351 if (mGpuEventsEnabled)
1352 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001353 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001354 while (mInFlightGpuEventQueries.size() > 0)
1355 {
1356 ANGLE_TRY(checkCompletedGpuEvents(context));
1357 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001358 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1359 // synchronization if there is no event to be adjusted (happens when finish() gets called
1360 // multiple times towards the end of the application).
1361 if (mGpuEvents.size() > 0)
1362 {
1363 ANGLE_TRY(synchronizeCpuGpuTime(context));
1364 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001365 }
1366
Jamie Madill7c985f52018-11-29 18:16:17 -05001367 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001368}
1369
Jamie Madill0c0dc342017-03-24 14:18:51 -04001370void RendererVk::freeAllInFlightResources()
1371{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001372 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001373 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001374 // On device loss we need to wait for fence to be signaled before destroying it
1375 if (mDeviceLost)
1376 {
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001377 VkResult status = batch.fence.get().wait(mDevice, kMaxFenceWaitTimeNs);
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001378 // If wait times out, it is probably not possible to recover from lost device
1379 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1380 }
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001381 batch.commandPool.destroy(mDevice);
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001382 batch.fence.reset(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001383 }
1384 mInFlightCommands.clear();
1385
1386 for (auto &garbage : mGarbage)
1387 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001388 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001389 }
1390 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001391
1392 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001393}
1394
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001395angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001396{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001397 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001398
Jamie Madill49ac74b2017-12-21 14:42:33 -05001399 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001400 {
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001401 VkResult result = batch.fence.get().getStatus(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001402 if (result == VK_NOT_READY)
1403 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001404 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001405 }
1406 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001407
Jamie Madill49ac74b2017-12-21 14:42:33 -05001408 ASSERT(batch.serial > mLastCompletedQueueSerial);
1409 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001410
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001411 batch.fence.reset(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001412 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001413 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001414 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001415 }
1416
Jamie Madill49ac74b2017-12-21 14:42:33 -05001417 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001418
1419 size_t freeIndex = 0;
1420 for (; freeIndex < mGarbage.size(); ++freeIndex)
1421 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001422 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001423 break;
1424 }
1425
1426 // Remove the entries from the garbage list - they should be ready to go.
1427 if (freeIndex > 0)
1428 {
1429 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001430 }
1431
Jamie Madill7c985f52018-11-29 18:16:17 -05001432 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001433}
1434
Jamie Madill21061022018-07-12 23:56:30 -04001435angle::Result RendererVk::submitFrame(vk::Context *context,
1436 const VkSubmitInfo &submitInfo,
1437 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001438{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001439 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Jamie Madill49ac74b2017-12-21 14:42:33 -05001440
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001441 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001442 CommandBatch &batch = scopedBatch.get();
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001443 ANGLE_TRY(getSubmitFence(context, &batch.fence));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001444
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001445 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.get().getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001446
1447 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001448 batch.commandPool = std::move(mCommandPool);
1449 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001450
Jamie Madillbea35a62018-07-05 11:54:10 -04001451 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001452
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001453 // Make sure a new fence is created for the next submission.
1454 mSubmitFence.reset(mDevice);
1455
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001456 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1457 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001458 // so the limit is larger than the expected number of images.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001459 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001460
Jamie Madill85ca1892019-01-16 13:27:15 -05001461 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001462
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001463 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001464
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001465 if (mGpuEventsEnabled)
1466 {
1467 ANGLE_TRY(checkCompletedGpuEvents(context));
1468 }
1469
Jamie Madill49ac74b2017-12-21 14:42:33 -05001470 // Simply null out the command buffer here - it was allocated using the command pool.
1471 commandBuffer.releaseHandle();
1472
1473 // Reallocate the command pool for next frame.
1474 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001475 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001476 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001477 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001478 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001479
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001480 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001481 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001482}
1483
Jamie Madill85ca1892019-01-16 13:27:15 -05001484void RendererVk::nextSerial()
1485{
1486 // Increment the queue serial. If this fails, we should restart ANGLE.
1487 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1488 mCurrentQueueSerial = mQueueSerialFactory.generate();
1489
1490 // Notify the Contexts that they should be starting new command buffers.
1491 // We use one command pool per serial/submit associated with this VkQueue. We can also
1492 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1493 // check for a new serial when starting a new command buffer. We just check that the current
1494 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1495 // using this VkQueue that they their current command buffer is no longer valid.
1496 for (gl::Context *context : mDisplay->getContextSet())
1497 {
1498 ContextVk *contextVk = vk::GetImpl(context);
1499 contextVk->onCommandBufferFinished();
1500 }
1501}
1502
Jamie Madillaaca96e2018-06-12 10:19:48 -04001503bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001504{
1505 return serial > mLastCompletedQueueSerial;
1506}
1507
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001508angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1509{
1510 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1511 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001512 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001513 }
1514
1515 // Find the first batch with serial equal to or bigger than given serial (note that
1516 // the batch serials are unique, otherwise upper-bound would have been necessary).
1517 size_t batchIndex = mInFlightCommands.size() - 1;
1518 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1519 {
1520 if (mInFlightCommands[i].serial >= serial)
1521 {
1522 batchIndex = i;
1523 break;
1524 }
1525 }
1526 const CommandBatch &batch = mInFlightCommands[batchIndex];
1527
1528 // Wait for it finish
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001529 VkResult status = batch.fence.get().wait(mDevice, kMaxFenceWaitTimeNs);
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001530
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001531 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001532 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001533
1534 // Clean up finished batches.
1535 return checkCompletedCommands(context);
1536}
1537
Jamie Madill21061022018-07-12 23:56:30 -04001538angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1539 const vk::RenderPassDesc &desc,
1540 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001541{
Jamie Madill21061022018-07-12 23:56:30 -04001542 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001543 renderPassOut);
1544}
1545
Jamie Madill21061022018-07-12 23:56:30 -04001546angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1547 const vk::RenderPassDesc &desc,
1548 const vk::AttachmentOpsArray &ops,
1549 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001550{
Jamie Madill21061022018-07-12 23:56:30 -04001551 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001552 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001553}
1554
Jamie Madilla5e06072018-05-18 14:36:05 -04001555vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001556{
Jamie Madilla5e06072018-05-18 14:36:05 -04001557 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001558}
1559
Jamie Madill21061022018-07-12 23:56:30 -04001560angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001561{
Jamie Madill21061022018-07-12 23:56:30 -04001562 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001563 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001564}
1565
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001566angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001567{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001568 if (mCommandGraph.empty())
1569 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001570 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001571 }
1572
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001573 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1574
Jamie Madillbea35a62018-07-05 11:54:10 -04001575 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1576 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001577
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001578 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001579 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1580 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001581
1582 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1583 // will be waited on.
1584 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001585
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001586 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001587 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001588 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1589 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001590 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001591 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001592 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001593 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001594 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001595
Jamie Madill21061022018-07-12 23:56:30 -04001596 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001597
Jamie Madill7c985f52018-11-29 18:16:17 -05001598 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001599}
1600
Jamie Madill78feddc2018-04-27 11:45:05 -04001601Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001602{
Jamie Madill78feddc2018-04-27 11:45:05 -04001603 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001604}
1605
Jamie Madill21061022018-07-12 23:56:30 -04001606angle::Result RendererVk::getDescriptorSetLayout(
1607 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001608 const vk::DescriptorSetLayoutDesc &desc,
1609 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1610{
Jamie Madill21061022018-07-12 23:56:30 -04001611 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001612}
1613
Jamie Madill21061022018-07-12 23:56:30 -04001614angle::Result RendererVk::getPipelineLayout(
1615 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001616 const vk::PipelineLayoutDesc &desc,
1617 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1618 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1619{
Jamie Madill21061022018-07-12 23:56:30 -04001620 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001621 pipelineLayoutOut);
1622}
1623
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001624angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1625{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001626 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001627
1628 if (--mPipelineCacheVkUpdateTimeout > 0)
1629 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001630 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001631 }
1632
1633 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1634
1635 // Get the size of the cache.
1636 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001637 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001638 if (result != VK_INCOMPLETE)
1639 {
1640 ANGLE_VK_TRY(displayVk, result);
1641 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001642
1643 angle::MemoryBuffer *pipelineCacheData = nullptr;
1644 ANGLE_VK_CHECK_ALLOC(displayVk,
1645 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1646
1647 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001648 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001649 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1650 // was determined just above), so receiving it hints at an implementation bug we would want
1651 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001652 ASSERT(result != VK_INCOMPLETE);
1653 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001654
1655 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1656 // the buffer to avoid leaking garbage memory.
1657 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1658 if (pipelineCacheSize < originalPipelineCacheSize)
1659 {
1660 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1661 originalPipelineCacheSize - pipelineCacheSize);
1662 }
1663
1664 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1665
Jamie Madill7c985f52018-11-29 18:16:17 -05001666 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001667}
1668
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001669angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1670 const vk::Semaphore **outSemaphore)
1671{
1672 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1673
1674 vk::SemaphoreHelper semaphore;
1675 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1676
1677 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1678 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1679
Jamie Madill7c985f52018-11-29 18:16:17 -05001680 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001681}
1682
1683const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1684{
1685 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1686
1687 // Return the semaphore to the pool (which will remain valid and unused until the
1688 // queue it's about to be waited on has finished execution). The caller is about
1689 // to wait on it.
1690 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1691
1692 return semaphore;
1693}
1694
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001695angle::Result RendererVk::getSubmitFence(vk::Context *context,
1696 vk::Shared<vk::Fence> *sharedFenceOut)
1697{
1698 if (!mSubmitFence.isReferenced())
1699 {
1700 vk::Fence fence;
1701
1702 VkFenceCreateInfo fenceCreateInfo = {};
1703 fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1704 fenceCreateInfo.flags = 0;
1705
1706 ANGLE_VK_TRY(context, fence.init(mDevice, fenceCreateInfo));
1707
1708 mSubmitFence.assign(mDevice, std::move(fence));
1709 }
1710
1711 sharedFenceOut->copy(mDevice, mSubmitFence);
1712 return angle::Result::Continue;
1713}
1714
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001715angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1716{
1717 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1718 // that seems impossible, so instead, we are going to make a small submission with just a
1719 // timestamp query. First, the disjoint timer query extension says:
1720 //
1721 // > This will return the GL time after all previous commands have reached the GL server but
1722 // have not yet necessarily executed.
1723 //
1724 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1725 // The wording allows us to make a submission to get the timestamp without performing a flush.
1726 //
1727 // Second:
1728 //
1729 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1730 // object target, applications can measure the latency between when commands reach the GL server
1731 // and when they are realized in the framebuffer.
1732 //
1733 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1734 // GPU bubble. This function directly generates a command buffer and submits it instead of
1735 // using the other member functions. This is to avoid changing any state, such as the queue
1736 // serial.
1737
1738 // Create a query used to receive the GPU timestamp
1739 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1740 vk::QueryHelper timestampQuery;
1741 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1742 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1743
1744 // Record the command buffer
1745 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1746 vk::CommandBuffer &commandBuffer = commandBatch.get();
1747
1748 VkCommandBufferAllocateInfo commandBufferInfo = {};
1749 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1750 commandBufferInfo.commandPool = mCommandPool.getHandle();
1751 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1752 commandBufferInfo.commandBufferCount = 1;
1753
Yuly Novikov27780292018-11-09 11:19:49 -05001754 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001755
1756 VkCommandBufferBeginInfo beginInfo = {};
1757 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1758 beginInfo.flags = 0;
1759 beginInfo.pInheritanceInfo = nullptr;
1760
Yuly Novikov27780292018-11-09 11:19:49 -05001761 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001762
1763 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1764 timestampQuery.getQuery(), 1);
1765 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1766 timestampQuery.getQueryPool()->getHandle(),
1767 timestampQuery.getQuery());
1768
Yuly Novikov27780292018-11-09 11:19:49 -05001769 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001770
1771 // Create fence for the submission
1772 VkFenceCreateInfo fenceInfo = {};
1773 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1774 fenceInfo.flags = 0;
1775
1776 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001777 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001778
1779 // Submit the command buffer
1780 VkSubmitInfo submitInfo = {};
1781 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1782 submitInfo.waitSemaphoreCount = 0;
1783 submitInfo.pWaitSemaphores = nullptr;
1784 submitInfo.pWaitDstStageMask = nullptr;
1785 submitInfo.commandBufferCount = 1;
1786 submitInfo.pCommandBuffers = commandBuffer.ptr();
1787 submitInfo.signalSemaphoreCount = 0;
1788 submitInfo.pSignalSemaphores = nullptr;
1789
1790 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1791
1792 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1793 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001794 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001795
1796 // Get the query results
1797 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1798
Yuly Novikov27780292018-11-09 11:19:49 -05001799 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1800 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1801 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001802
1803 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1804
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001805 // Convert results to nanoseconds.
1806 *timestampOut = static_cast<uint64_t>(
1807 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1808
Jamie Madill7c985f52018-11-29 18:16:17 -05001809 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001810}
1811
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001812// These functions look at the mandatory format for support, and fallback to querying the device (if
1813// necessary) to test the availability of the bits.
1814bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1815 const VkFormatFeatureFlags featureBits)
1816{
1817 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1818}
1819
1820bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1821 const VkFormatFeatureFlags featureBits)
1822{
1823 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1824}
1825
1826bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1827{
1828 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1829}
1830
Shahbaz Youssefi4d153382019-02-26 15:08:11 +00001831void RendererVk::insertDebugMarker(GLenum source, GLuint id, std::string &&marker)
1832{
1833 mCommandGraph.insertDebugMarker(source, std::move(marker));
1834}
1835
1836void RendererVk::pushDebugMarker(GLenum source, GLuint id, std::string &&marker)
1837{
1838 mCommandGraph.pushDebugMarker(source, std::move(marker));
1839}
1840
1841void RendererVk::popDebugMarker()
1842{
1843 mCommandGraph.popDebugMarker();
1844}
1845
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001846angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1847{
1848 ASSERT(mGpuEventsEnabled);
1849
1850 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1851 ASSERT(platform);
1852
1853 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1854 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1855 //
1856 // CPU GPU
1857 //
1858 // Record command buffer
1859 // with timestamp query
1860 //
1861 // Submit command buffer
1862 //
1863 // Post-submission work Begin execution
1864 //
Tobin Ehlis5546fb42019-01-17 12:25:54 -05001865 // ???? Write timestamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001866 //
1867 // ???? End execution
1868 //
1869 // ???? Return query results
1870 //
1871 // ????
1872 //
1873 // Get query results
1874 //
1875 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1876 // finished post-submission work while the GPU is executing in parallel. With no further work,
1877 // querying CPU timestamps before submission and after getting query results give the bounds to
1878 // Tgpu, which could be quite large.
1879 //
1880 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1881 // reduce this range. This function implements the following procedure:
1882 //
1883 // CPU GPU
1884 //
1885 // Record command buffer
1886 // with timestamp query
1887 //
1888 // Submit command buffer
1889 //
1890 // Post-submission work Begin execution
1891 //
1892 // ???? Set Event GPUReady
1893 //
1894 // Wait on Event GPUReady Wait on Event CPUReady
1895 //
1896 // Get CPU Time Ts Wait on Event CPUReady
1897 //
1898 // Set Event CPUReady Wait on Event CPUReady
1899 //
1900 // Get CPU Time Tcpu Get GPU Time Tgpu
1901 //
1902 // Wait on Event GPUDone Set Event GPUDone
1903 //
1904 // Get CPU Time Te End Execution
1905 //
1906 // Idle Return query results
1907 //
1908 // Get query results
1909 //
1910 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1911 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1912 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1913 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1914 // calibration.
1915 //
1916 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1917
1918 // Make sure nothing is running
1919 ASSERT(mCommandGraph.empty());
1920
1921 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1922
1923 // Create a query used to receive the GPU timestamp
1924 vk::QueryHelper timestampQuery;
1925 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1926
1927 // Create the three events
1928 VkEventCreateInfo eventCreateInfo = {};
1929 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1930 eventCreateInfo.flags = 0;
1931
1932 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001933 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1934 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1935 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001936
1937 constexpr uint32_t kRetries = 10;
1938
1939 // Time suffixes used are S for seconds and Cycles for cycles
1940 double tightestRangeS = 1e6f;
1941 double TcpuS = 0;
1942 uint64_t TgpuCycles = 0;
1943 for (uint32_t i = 0; i < kRetries; ++i)
1944 {
1945 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001946 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1947 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1948 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001949
1950 // Record the command buffer
1951 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1952 vk::CommandBuffer &commandBuffer = commandBatch.get();
1953
1954 VkCommandBufferAllocateInfo commandBufferInfo = {};
1955 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1956 commandBufferInfo.commandPool = mCommandPool.getHandle();
1957 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1958 commandBufferInfo.commandBufferCount = 1;
1959
Yuly Novikov27780292018-11-09 11:19:49 -05001960 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001961
1962 VkCommandBufferBeginInfo beginInfo = {};
1963 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1964 beginInfo.flags = 0;
1965 beginInfo.pInheritanceInfo = nullptr;
1966
Yuly Novikov27780292018-11-09 11:19:49 -05001967 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001968
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001969 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001970 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1971 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1972 nullptr);
1973
1974 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1975 timestampQuery.getQuery(), 1);
1976 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1977 timestampQuery.getQueryPool()->getHandle(),
1978 timestampQuery.getQuery());
1979
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001980 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001981
Yuly Novikov27780292018-11-09 11:19:49 -05001982 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001983
1984 // Submit the command buffer
1985 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1986 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1987 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1988
1989 VkSubmitInfo submitInfo = {};
1990 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1991 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1992 submitInfo.pWaitSemaphores = waitSemaphores.data();
1993 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1994 submitInfo.commandBufferCount = 1;
1995 submitInfo.pCommandBuffers = commandBuffer.ptr();
1996 submitInfo.signalSemaphoreCount = 0;
1997 submitInfo.pSignalSemaphores = nullptr;
1998
1999 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
2000
2001 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05002002 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002003 do
2004 {
Yuly Novikov27780292018-11-09 11:19:49 -05002005 result = gpuReady.get().getStatus(mDevice);
2006 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
2007 {
2008 ANGLE_VK_TRY(context, result);
2009 }
2010 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002011
2012 double TsS = platform->monotonicallyIncreasingTime(platform);
2013
2014 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05002015 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002016 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
2017
2018 // Wait for GPU to be done. Another short busy wait.
2019 do
2020 {
Yuly Novikov27780292018-11-09 11:19:49 -05002021 result = gpuDone.get().getStatus(mDevice);
2022 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
2023 {
2024 ANGLE_VK_TRY(context, result);
2025 }
2026 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002027
2028 double TeS = platform->monotonicallyIncreasingTime(platform);
2029
2030 // Get the query results
2031 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
2032
2033 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
2034
2035 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002036 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
2037 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
2038 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002039
2040 // Use the first timestamp queried as origin.
2041 if (mGpuEventTimestampOrigin == 0)
2042 {
2043 mGpuEventTimestampOrigin = gpuTimestampCycles;
2044 }
2045
2046 // Take these CPU and GPU timestamps if there is better confidence.
2047 double confidenceRangeS = TeS - TsS;
2048 if (confidenceRangeS < tightestRangeS)
2049 {
2050 tightestRangeS = confidenceRangeS;
2051 TcpuS = cpuTimestampS;
2052 TgpuCycles = gpuTimestampCycles;
2053 }
2054 }
2055
2056 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
2057
2058 // timestampPeriod gives nanoseconds/cycle.
2059 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
2060 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
2061 1'000'000'000.0;
2062
2063 flushGpuEvents(TgpuS, TcpuS);
2064
2065 mGpuClockSync.gpuTimestampS = TgpuS;
2066 mGpuClockSync.cpuTimestampS = TcpuS;
2067
Jamie Madill7c985f52018-11-29 18:16:17 -05002068 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002069}
2070
2071angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
2072 vk::CommandBuffer *commandBuffer,
2073 char phase,
2074 const char *name)
2075{
2076 ASSERT(mGpuEventsEnabled);
2077
2078 GpuEventQuery event;
2079
2080 event.name = name;
2081 event.phase = phase;
2082 event.serial = mCurrentQueueSerial;
2083
2084 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
2085
2086 commandBuffer->resetQueryPool(
2087 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
2088 commandBuffer->writeTimestamp(
2089 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2090 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
2091
2092 mInFlightGpuEventQueries.push_back(std::move(event));
2093
Jamie Madill7c985f52018-11-29 18:16:17 -05002094 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002095}
2096
2097angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
2098{
2099 ASSERT(mGpuEventsEnabled);
2100
2101 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2102 ASSERT(platform);
2103
2104 int finishedCount = 0;
2105
2106 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2107 {
2108 // Only check the timestamp query if the submission has finished.
2109 if (eventQuery.serial > mLastCompletedQueueSerial)
2110 {
2111 break;
2112 }
2113
2114 // See if the results are available.
2115 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002116 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2117 ->getResults(mDevice, eventQuery.queryIndex, 1,
2118 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2119 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2120 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002121 {
2122 break;
2123 }
Yuly Novikov27780292018-11-09 11:19:49 -05002124 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002125
2126 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2127
2128 GpuEvent event;
2129 event.gpuTimestampCycles = gpuTimestampCycles;
2130 event.name = eventQuery.name;
2131 event.phase = eventQuery.phase;
2132
2133 mGpuEvents.emplace_back(event);
2134
2135 ++finishedCount;
2136 }
2137
2138 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2139 mInFlightGpuEventQueries.begin() + finishedCount);
2140
Jamie Madill7c985f52018-11-29 18:16:17 -05002141 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002142}
2143
2144void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2145{
2146 if (mGpuEvents.size() == 0)
2147 {
2148 return;
2149 }
2150
2151 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2152 ASSERT(platform);
2153
2154 // Find the slope of the clock drift for adjustment
2155 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2156 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2157 double gpuSyncDriftSlope = 0;
2158
2159 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2160 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2161
2162 // No gpu trace events should have been generated before the clock sync, so if there is no
2163 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2164 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2165 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2166
2167 gpuSyncDriftSlope =
2168 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2169
2170 for (const GpuEvent &event : mGpuEvents)
2171 {
2172 double gpuTimestampS =
2173 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2174 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2175
2176 // Account for clock drift.
2177 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2178
2179 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2180 // for.
2181 static long long eventId = 1;
2182 static const unsigned char *categoryEnabled =
2183 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2184 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2185 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2186 }
2187
2188 mGpuEvents.clear();
2189}
2190
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002191template <VkFormatFeatureFlags VkFormatProperties::*features>
2192bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2193{
2194 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2195 VkFormatProperties &deviceProperties = mFormatProperties[format];
2196
2197 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2198 {
2199 // If we don't have the actual device features, see if the requested features are mandatory.
2200 // If so, there's no need to query the device.
2201 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2202 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2203 {
2204 return true;
2205 }
2206
2207 // Otherwise query the format features and cache it.
2208 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2209 }
2210
2211 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2212}
2213
Jamie Madillaaca96e2018-06-12 10:19:48 -04002214uint32_t GetUniformBufferDescriptorCount()
2215{
2216 return kUniformBufferDescriptorsPerDescriptorSet;
2217}
2218
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002219} // namespace rx