blob: ae34ca81e4eff6171d189b1bd0182406d22aad14 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Shahbaz Youssefi61656022018-10-24 15:00:50 -040034#include "third_party/trace_event/trace_event.h"
35
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070036// Consts
37namespace
38{
Jamie Madill7c985f52018-11-29 18:16:17 -050039const uint32_t kMockVendorID = 0xba5eba11;
40const uint32_t kMockDeviceID = 0xf005ba11;
41constexpr char kMockDeviceName[] = "Vulkan Mock Device";
42constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050043constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070044} // anonymous namespace
45
Jamie Madill9e54b5a2016-05-25 12:57:39 -040046namespace rx
47{
48
Jamie Madille09bd5d2016-11-29 16:20:35 -050049namespace
50{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040051// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
52// one for the vertex shader.
53constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040054// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050055constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040056// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050057constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Ian Elliott356d26c2019-02-11 11:27:01 -070058// Per the Vulkan specification, as long as Vulkan 1.1+ is returned by vkEnumerateInstanceVersion,
59// ANGLE must indicate the highest version of Vulkan functionality that it uses. The Vulkan
60// validation layers will issue messages for any core functionality that requires a higher version.
61// This value must be increased whenever ANGLE starts using functionality from a newer core
62// version of Vulkan.
63constexpr uint32_t kPreferredVulkanAPIVersion = VK_API_VERSION_1_1;
Jamie Madille09bd5d2016-11-29 16:20:35 -050064
Omar El Sheikh26c61b22018-06-29 12:50:59 -060065bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
66{
67#if !defined(ANGLE_PLATFORM_ANDROID)
68 // Mock ICD does not currently run on Android
69 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
70 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
71 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
72#else
73 return false;
74#endif // !defined(ANGLE_PLATFORM_ANDROID)
75}
76
Jamie Madille09bd5d2016-11-29 16:20:35 -050077VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
78 const std::vector<const char *> &enabledExtensionNames)
79{
80 // Compile the extensions names into a set.
81 std::set<std::string> extensionNames;
82 for (const auto &extensionProp : extensionProps)
83 {
84 extensionNames.insert(extensionProp.extensionName);
85 }
86
Jamie Madillacf2f3a2017-11-21 19:22:44 -050087 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050088 {
89 if (extensionNames.count(extensionName) == 0)
90 {
91 return VK_ERROR_EXTENSION_NOT_PRESENT;
92 }
93 }
94
95 return VK_SUCCESS;
96}
97
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050098bool ExtensionFound(const char *extensionName,
99 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600100{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500101 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600102 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500103 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600104 {
105 return true;
106 }
107 }
108 return false;
109}
110
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500111// Array of Validation error/warning messages that will be ignored, should include bugID
Jamie Madill00f43c92019-02-09 11:41:12 -0500112constexpr const char *kSkippedMessages[] = {
113 // http://anglebug.com/2866
114 "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500115 // http://anglebug.com/2796
Jamie Madill00f43c92019-02-09 11:41:12 -0500116 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing",
117};
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500118
119// Suppress validation errors that are known
120// return "true" if given code/prefix/message is known, else return "false"
121bool IsIgnoredDebugMessage(const char *message)
122{
Michael Spang25839802019-01-30 18:02:51 -0500123 if (!message)
124 {
125 return false;
126 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500127 for (const char *msg : kSkippedMessages)
128 {
129 if (strstr(message, msg) != nullptr)
130 {
131 return true;
132 }
133 }
134 return false;
135}
136
137const char *GetVkObjectTypeName(VkObjectType type)
138{
139 switch (type)
140 {
141 case VK_OBJECT_TYPE_UNKNOWN:
142 return "Unknown";
143 case VK_OBJECT_TYPE_INSTANCE:
144 return "Instance";
145 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
146 return "Physical Device";
147 case VK_OBJECT_TYPE_DEVICE:
148 return "Device";
149 case VK_OBJECT_TYPE_QUEUE:
150 return "Queue";
151 case VK_OBJECT_TYPE_SEMAPHORE:
152 return "Semaphore";
153 case VK_OBJECT_TYPE_COMMAND_BUFFER:
154 return "Command Buffer";
155 case VK_OBJECT_TYPE_FENCE:
156 return "Fence";
157 case VK_OBJECT_TYPE_DEVICE_MEMORY:
158 return "Device Memory";
159 case VK_OBJECT_TYPE_BUFFER:
160 return "Buffer";
161 case VK_OBJECT_TYPE_IMAGE:
162 return "Image";
163 case VK_OBJECT_TYPE_EVENT:
164 return "Event";
165 case VK_OBJECT_TYPE_QUERY_POOL:
166 return "Query Pool";
167 case VK_OBJECT_TYPE_BUFFER_VIEW:
168 return "Buffer View";
169 case VK_OBJECT_TYPE_IMAGE_VIEW:
170 return "Image View";
171 case VK_OBJECT_TYPE_SHADER_MODULE:
172 return "Shader Module";
173 case VK_OBJECT_TYPE_PIPELINE_CACHE:
174 return "Pipeline Cache";
175 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
176 return "Pipeline Layout";
177 case VK_OBJECT_TYPE_RENDER_PASS:
178 return "Render Pass";
179 case VK_OBJECT_TYPE_PIPELINE:
180 return "Pipeline";
181 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
182 return "Descriptor Set Layout";
183 case VK_OBJECT_TYPE_SAMPLER:
184 return "Sampler";
185 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
186 return "Descriptor Pool";
187 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
188 return "Descriptor Set";
189 case VK_OBJECT_TYPE_FRAMEBUFFER:
190 return "Framebuffer";
191 case VK_OBJECT_TYPE_COMMAND_POOL:
192 return "Command Pool";
193 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
194 return "Sampler YCbCr Conversion";
195 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
196 return "Descriptor Update Template";
197 case VK_OBJECT_TYPE_SURFACE_KHR:
198 return "Surface";
199 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
200 return "Swapchain";
201 case VK_OBJECT_TYPE_DISPLAY_KHR:
202 return "Display";
203 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
204 return "Display Mode";
205 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
206 return "Debug Report Callback";
207 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
208 return "Object Table";
209 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
210 return "Indirect Commands Layout";
211 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
212 return "Debug Utils Messenger";
213 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
214 return "Validation Cache";
215 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
216 return "Acceleration Structure";
217 default:
218 return "<Unrecognized>";
219 }
220}
221
222VKAPI_ATTR VkBool32 VKAPI_CALL
223DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
224 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
225 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
226 void *userData)
227{
228 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
229 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
230 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
231
232 // Check if we even care about this message.
233 if ((messageSeverity & kSeveritiesToLog) == 0)
234 {
235 return VK_FALSE;
236 }
237
238 // See if it's an issue we are aware of and don't want to be spammed about.
239 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
240 {
241 return VK_FALSE;
242 }
243
244 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500245 if (callbackData->pMessageIdName)
246 {
247 log << "[ " << callbackData->pMessageIdName << " ] ";
248 }
249 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500250
251 // Aesthetic value based on length of the function name, line number, etc.
252 constexpr size_t kStartIndent = 28;
253
254 // Output the debug marker hierarchy under which this error has occured.
255 size_t indent = kStartIndent;
256 if (callbackData->queueLabelCount > 0)
257 {
258 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
259 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
260 {
261 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
262 << std::endl;
263 }
264 }
265 if (callbackData->cmdBufLabelCount > 0)
266 {
267 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
268 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
269 {
270 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
271 << std::endl;
272 }
273 }
274 // Output the objects involved in this error message.
275 if (callbackData->objectCount > 0)
276 {
277 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
278 {
279 const char *objectName = callbackData->pObjects[i].pObjectName;
280 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
281 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
282 log << std::string(indent, ' ') << "Object: ";
283 if (objectHandle == 0)
284 {
285 log << "VK_NULL_HANDLE";
286 }
287 else
288 {
289 log << "0x" << std::hex << objectHandle << std::dec;
290 }
291 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
292 if (objectName)
293 {
294 log << " [" << objectName << "]";
295 }
296 log << std::endl;
297 }
298 }
299
Jamie Madill54ed8f02019-02-11 12:32:04 -0500300 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
301 std::string msg = log.str();
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500302
303 if (isError)
304 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500305 ERR() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500306 }
307 else
308 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500309 WARN() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500310 }
311
312 return VK_FALSE;
313}
314
Yuly Novikov199f4292018-01-19 19:04:05 -0500315VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
316 VkDebugReportObjectTypeEXT objectType,
317 uint64_t object,
318 size_t location,
319 int32_t messageCode,
320 const char *layerPrefix,
321 const char *message,
322 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500323{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600324 if (IsIgnoredDebugMessage(message))
325 {
326 return VK_FALSE;
327 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500328 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
329 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500330 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500331#if !defined(NDEBUG)
332 // Abort the call in Debug builds.
333 return VK_TRUE;
334#endif
335 }
336 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
337 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500338 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500339 }
340 else
341 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500342 // Uncomment this if you want Vulkan spam.
343 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500344 }
345
346 return VK_FALSE;
347}
348
Yuly Novikov199f4292018-01-19 19:04:05 -0500349// If we're loading the validation layers, we could be running from any random directory.
350// Change to the executable directory so we can find the layers, then change back to the
351// previous directory to be safe we don't disrupt the application.
352class ScopedVkLoaderEnvironment : angle::NonCopyable
353{
354 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600355 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
356 : mEnableValidationLayers(enableValidationLayers),
357 mEnableMockICD(enableMockICD),
358 mChangedCWD(false),
359 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500360 {
361// Changing CWD and setting environment variables makes no sense on Android,
362// since this code is a part of Java application there.
363// Android Vulkan loader doesn't need this either.
Jamie Madill3f0ff402019-02-12 03:08:51 +0000364#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600365 if (enableMockICD)
366 {
367 // Override environment variable to use built Mock ICD
368 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
369 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
370 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
371 if (!mChangedICDPath)
372 {
373 ERR() << "Error setting Path for Mock/Null Driver.";
374 mEnableMockICD = false;
375 }
376 }
Jamie Madill46848422018-08-09 10:46:06 -0400377 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500378 {
379 const auto &cwd = angle::GetCWD();
380 if (!cwd.valid())
381 {
382 ERR() << "Error getting CWD for Vulkan layers init.";
383 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400384 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500385 }
386 else
387 {
388 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500389 std::string exeDir = angle::GetExecutableDirectory();
390 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500391 if (!mChangedCWD)
392 {
393 ERR() << "Error setting CWD for Vulkan layers init.";
394 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400395 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500396 }
397 }
398 }
399
400 // Override environment variable to use the ANGLE layers.
401 if (mEnableValidationLayers)
402 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700403 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500404 {
405 ERR() << "Error setting environment for Vulkan layers init.";
406 mEnableValidationLayers = false;
407 }
408 }
409#endif // !defined(ANGLE_PLATFORM_ANDROID)
410 }
411
412 ~ScopedVkLoaderEnvironment()
413 {
414 if (mChangedCWD)
415 {
416#if !defined(ANGLE_PLATFORM_ANDROID)
417 ASSERT(mPreviousCWD.valid());
418 angle::SetCWD(mPreviousCWD.value().c_str());
419#endif // !defined(ANGLE_PLATFORM_ANDROID)
420 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600421 if (mChangedICDPath)
422 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600423 if (mPreviousICDPath.value().empty())
424 {
425 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
426 }
427 else
428 {
429 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
430 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600431 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500432 }
433
Jamie Madillaaca96e2018-06-12 10:19:48 -0400434 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500435
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600436 bool canEnableMockICD() const { return mEnableMockICD; }
437
Yuly Novikov199f4292018-01-19 19:04:05 -0500438 private:
439 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600440 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500441 bool mChangedCWD;
442 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600443 bool mChangedICDPath;
444 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500445};
446
Jamie Madill21061022018-07-12 23:56:30 -0400447void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
448 bool preferMockICD,
449 VkPhysicalDevice *physicalDeviceOut,
450 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
451{
452 ASSERT(!physicalDevices.empty());
453 if (preferMockICD)
454 {
455 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
456 {
457 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
458 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
459 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
460 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
461 {
462 *physicalDeviceOut = physicalDevice;
463 return;
464 }
465 }
466 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
467 "physicalDevice instead.";
468 }
469
470 // Fall back to first device.
471 *physicalDeviceOut = physicalDevices[0];
472 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
473}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400474
475// Initially dumping the command graphs is disabled.
476constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700477
Jamie Madille09bd5d2016-11-29 16:20:35 -0500478} // anonymous namespace
479
Jamie Madill49ac74b2017-12-21 14:42:33 -0500480// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400481RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500482
Jamie Madillaaca96e2018-06-12 10:19:48 -0400483RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500484
485RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000486 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500487{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500488
489RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
490{
491 std::swap(commandPool, other.commandPool);
492 std::swap(fence, other.fence);
493 std::swap(serial, other.serial);
494 return *this;
495}
496
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000497void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400498{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000499 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400500 fence.destroy(device);
501}
502
Jamie Madill9f2a8612017-11-30 12:43:09 -0500503// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500504RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400505 : mDisplay(nullptr),
506 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700507 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500508 mInstance(VK_NULL_HANDLE),
509 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400510 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500511 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500512 mDebugReportCallback(VK_NULL_HANDLE),
513 mPhysicalDevice(VK_NULL_HANDLE),
514 mQueue(VK_NULL_HANDLE),
515 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
516 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400517 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400518 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400519 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400520 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400521 mCommandGraph(kEnableCommandGraphDiagnostics),
522 mGpuEventsEnabled(false),
523 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
524 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500525{
526 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
527 mFormatProperties.fill(invalid);
528}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400529
Jamie Madillb980c562018-11-27 11:34:27 -0500530RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400531
532void RendererVk::onDestroy(vk::Context *context)
533{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500534 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500535 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500536 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400537 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500538 }
539
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100540 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500541
Jamie Madillc7918ce2018-06-13 13:25:31 -0400542 mPipelineLayoutCache.destroy(mDevice);
543 mDescriptorSetLayoutCache.destroy(mDevice);
544
Jamie Madill9f2a8612017-11-30 12:43:09 -0500545 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500546 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400547 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400548 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400549 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500550
Jamie Madill06ca6342018-07-12 15:56:53 -0400551 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500552
Jamie Madill5deea722017-02-16 10:44:46 -0500553 if (mCommandPool.valid())
554 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000555 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500556 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500557
558 if (mDevice)
559 {
560 vkDestroyDevice(mDevice, nullptr);
561 mDevice = VK_NULL_HANDLE;
562 }
563
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500564 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500565 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500566 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
567 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
568
569 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
570 }
571 else if (mDebugReportCallback)
572 {
573 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
574 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500575 }
576
Jamie Madill4d0bf552016-12-28 15:45:24 -0500577 if (mInstance)
578 {
579 vkDestroyInstance(mInstance, nullptr);
580 mInstance = VK_NULL_HANDLE;
581 }
582
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600583 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500584 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500585}
586
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400587void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400588{
589 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400590
591 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500592 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400593 freeAllInFlightResources();
594
595 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400596}
597
598bool RendererVk::isDeviceLost() const
599{
600 return mDeviceLost;
601}
602
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400603angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400604 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500605 const char *wsiExtension,
606 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500607{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400608 mDisplay = display;
609 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600610 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
611 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500612 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400613 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500614
Jamie Madill0448ec82016-12-23 13:41:47 -0500615 // Gather global layer properties.
616 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400617 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500618
619 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
620 if (instanceLayerCount > 0)
621 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400622 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
623 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500624 }
625
Michael Spang6c13c702019-02-06 15:59:44 -0500626 VulkanLayerVector enabledInstanceLayerNames;
627 if (mEnableValidationLayers)
628 {
629 bool layersRequested =
630 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
631 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
632 &enabledInstanceLayerNames);
633 }
634
635 if (wsiLayer)
636 {
637 enabledInstanceLayerNames.push_back(wsiLayer);
638 }
639
640 // Enumerate instance extensions that are provided by the vulkan
641 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500642 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400643 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400644 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500645
646 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
647 if (instanceExtensionCount > 0)
648 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400649 ANGLE_VK_TRY(displayVk,
650 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
651 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500652 }
653
Michael Spang6c13c702019-02-06 15:59:44 -0500654 // Enumerate instance extensions that are provided by explicit layers.
655 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500656 {
Michael Spang6c13c702019-02-06 15:59:44 -0500657 uint32_t previousExtensionCount = instanceExtensionProps.size();
658 uint32_t instanceLayerExtensionCount = 0;
659 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
660 layerName, &instanceLayerExtensionCount, nullptr));
661 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
662 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
663 layerName, &instanceLayerExtensionCount,
664 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500665 }
666
Jamie Madille09bd5d2016-11-29 16:20:35 -0500667 std::vector<const char *> enabledInstanceExtensions;
668 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500669 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500670
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500671 bool enableDebugUtils =
672 mEnableValidationLayers &&
673 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
674 bool enableDebugReport =
675 mEnableValidationLayers && !enableDebugUtils &&
676 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
677
678 if (enableDebugUtils)
679 {
680 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
681 }
682 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500683 {
684 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
685 }
686
Jamie Madille09bd5d2016-11-29 16:20:35 -0500687 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400688 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400689 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500690
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400691 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500692 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500693 applicationInfo.pApplicationName = "ANGLE";
694 applicationInfo.applicationVersion = 1;
695 applicationInfo.pEngineName = "ANGLE";
696 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700697
698 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
699 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
700 if (!enumerateInstanceVersion)
701 {
702 applicationInfo.apiVersion = VK_API_VERSION_1_0;
703 }
704 else
705 {
706 uint32_t apiVersion = VK_API_VERSION_1_0;
707 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
708 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
709 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700710 // This is the highest version of core Vulkan functionality that ANGLE uses.
711 applicationInfo.apiVersion = kPreferredVulkanAPIVersion;
Ian Elliott899c5d22018-12-21 13:12:50 -0700712 }
713 else
714 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700715 // Since only 1.0 instance-level functionality is available, this must set to 1.0.
Ian Elliott899c5d22018-12-21 13:12:50 -0700716 applicationInfo.apiVersion = VK_API_VERSION_1_0;
717 }
718 }
Jamie Madill327ba852016-11-30 12:38:28 -0500719
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400720 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500721 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
722 instanceInfo.flags = 0;
723 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500724
Jamie Madille09bd5d2016-11-29 16:20:35 -0500725 // Enable requested layers and extensions.
726 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
727 instanceInfo.ppEnabledExtensionNames =
728 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500729 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
730 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500731
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400732 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500733
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500734 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500735 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500736 // Try to use the newer EXT_debug_utils if it exists.
737 InitDebugUtilsEXTFunctions(mInstance);
738
739 // Create the messenger callback.
740 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
741
742 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
743 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
744 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
745 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
746 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
747 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
748 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
749 messengerInfo.pUserData = this;
750
751 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
752 &mDebugUtilsMessenger));
753 }
754 else if (enableDebugReport)
755 {
756 // Fallback to EXT_debug_report.
757 InitDebugReportEXTFunctions(mInstance);
758
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400759 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500760
761 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500762 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500763 debugReportInfo.pfnCallback = &DebugReportCallback;
764 debugReportInfo.pUserData = this;
765
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500766 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
767 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500768 }
769
Jamie Madill4d0bf552016-12-28 15:45:24 -0500770 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400771 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
772 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500773
774 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700775 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400776 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
777 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400778 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700779 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500780
Jamie Madill30b5d842018-08-31 17:19:12 -0400781 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
782
Jamie Madill4d0bf552016-12-28 15:45:24 -0500783 // Ensure we can find a graphics queue family.
784 uint32_t queueCount = 0;
785 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
786
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400787 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500788
789 mQueueFamilyProperties.resize(queueCount);
790 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
791 mQueueFamilyProperties.data());
792
Jamie Madillb980c562018-11-27 11:34:27 -0500793 size_t graphicsQueueFamilyCount = false;
794 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500795 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500796 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
797 {
798 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500799 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500800 {
801 ASSERT(queueInfo.queueCount > 0);
802 graphicsQueueFamilyCount++;
803 if (firstGraphicsQueueFamily == 0)
804 {
805 firstGraphicsQueueFamily = familyIndex;
806 }
807 break;
808 }
809 }
810
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400811 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500812
813 // If only one queue family, go ahead and initialize the device. If there is more than one
814 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
815 if (graphicsQueueFamilyCount == 1)
816 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400817 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500818 }
819
Jamie Madill035fd6b2017-10-03 15:43:22 -0400820 // Store the physical device memory properties so we can find the right memory pools.
821 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500822
Jamie Madill06ca6342018-07-12 15:56:53 -0400823 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500824
Jamie Madill6a89d222017-11-02 11:59:51 -0400825 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500826 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400827
Jamie Madill7c985f52018-11-29 18:16:17 -0500828 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400829}
830
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400831angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500832{
833 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400834 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400835 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500836
837 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
838 if (deviceLayerCount > 0)
839 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400840 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
841 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500842 }
843
Michael Spang6c13c702019-02-06 15:59:44 -0500844 VulkanLayerVector enabledDeviceLayerNames;
845 if (mEnableValidationLayers)
846 {
847 mEnableValidationLayers =
848 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
849 }
850
851 const char *wsiLayer = displayVk->getWSILayer();
852 if (wsiLayer)
853 {
854 enabledDeviceLayerNames.push_back(wsiLayer);
855 }
856
857 // Enumerate device extensions that are provided by the vulkan
858 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500859 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400860 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
861 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862
863 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
864 if (deviceExtensionCount > 0)
865 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400866 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
867 &deviceExtensionCount,
868 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500869 }
870
Michael Spang6c13c702019-02-06 15:59:44 -0500871 // Enumerate device extensions that are provided by explicit layers.
872 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873 {
Michael Spang6c13c702019-02-06 15:59:44 -0500874 uint32_t previousExtensionCount = deviceExtensionProps.size();
875 uint32_t deviceLayerExtensionCount = 0;
876 ANGLE_VK_TRY(displayVk,
877 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
878 &deviceLayerExtensionCount, nullptr));
879 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
880 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
881 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
882 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500883 }
884
885 std::vector<const char *> enabledDeviceExtensions;
886 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
887
Ian Elliottbcb78902018-12-19 11:46:29 -0700888 initFeatures(deviceExtensionProps);
889 mFeaturesInitialized = true;
890
Luc Ferronbf6dc372018-06-28 15:24:19 -0400891 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700892 if ((getFeatures().flipViewportY) &&
893 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400894 {
895 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
896 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700897 if (getFeatures().supportsIncrementalPresent)
898 {
899 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
900 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400901
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400902 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500903
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400904 // Select additional features to be enabled
905 VkPhysicalDeviceFeatures enabledFeatures = {};
906 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500907 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400908
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400909 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500910
911 float zeroPriority = 0.0f;
912
913 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500914 queueCreateInfo.flags = 0;
915 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
916 queueCreateInfo.queueCount = 1;
917 queueCreateInfo.pQueuePriorities = &zeroPriority;
918
919 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400920 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500921
Jamie Madill50cf2be2018-06-15 09:46:57 -0400922 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400923 createInfo.flags = 0;
924 createInfo.queueCreateInfoCount = 1;
925 createInfo.pQueueCreateInfos = &queueCreateInfo;
Michael Spang6c13c702019-02-06 15:59:44 -0500926 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
927 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500928 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
929 createInfo.ppEnabledExtensionNames =
930 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400931 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500932
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400933 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500934
935 mCurrentQueueFamilyIndex = queueFamilyIndex;
936
937 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
938
939 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400940 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500941 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
942 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
943 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500944
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000945 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400946
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400947 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500948 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500949
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400950 // Initialize the submission semaphore pool.
951 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
952
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400953#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
954 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
955 ASSERT(platform);
956
957 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
958 // platform discovery.
959 const unsigned char *gpuEventsEnabled =
960 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
961 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
962#endif
963
964 if (mGpuEventsEnabled)
965 {
966 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
967 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
968 vk::kDefaultTimestampQueryPoolSize));
969 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
970 }
971
Jamie Madill7c985f52018-11-29 18:16:17 -0500972 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500973}
974
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400975angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400976 VkSurfaceKHR surface,
977 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500978{
979 // We've already initialized a device, and can't re-create it unless it's never been used.
980 // TODO(jmadill): Handle the re-creation case if necessary.
981 if (mDevice != VK_NULL_HANDLE)
982 {
983 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
984
985 // Check if the current device supports present on this surface.
986 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400987 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400988 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500989 surface, &supportsPresent));
990
Jamie Madill6cad7732018-07-11 09:01:17 -0400991 if (supportsPresent == VK_TRUE)
992 {
993 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500994 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400995 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500996 }
997
998 // Find a graphics and present queue.
999 Optional<uint32_t> newPresentQueue;
1000 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001001 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001002 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
1003 {
1004 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001005 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001006 {
1007 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001008 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
1009 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001010
1011 if (supportsPresent == VK_TRUE)
1012 {
1013 newPresentQueue = queueIndex;
1014 break;
1015 }
1016 }
1017 }
1018
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001019 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1020 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001021
Jamie Madill6cad7732018-07-11 09:01:17 -04001022 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001023 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001024}
1025
1026std::string RendererVk::getVendorString() const
1027{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001028 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001029}
1030
Jamie Madille09bd5d2016-11-29 16:20:35 -05001031std::string RendererVk::getRendererDescription() const
1032{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001033 std::stringstream strstr;
1034
1035 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1036
1037 strstr << "Vulkan ";
1038 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1039 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1040 strstr << VK_VERSION_PATCH(apiVersion);
1041
Olli Etuahoc6a06182018-04-13 14:11:46 +03001042 strstr << "(";
1043
1044 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1045 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1046 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1047 // driver detection.
1048 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1049 {
1050 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1051 }
1052
Geoff Langa7af56b2018-12-14 14:20:28 -05001053 strstr << mPhysicalDeviceProperties.deviceName;
1054 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1055
1056 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001057
1058 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001059}
1060
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001061gl::Version RendererVk::getMaxSupportedESVersion() const
1062{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001063 // Current highest supported version
1064 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1065 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001066
Geoff Lang0c2c9232019-01-14 16:01:38 -05001067 // Vulkan inherited queries are required to support any GL query type
1068 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001069 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001070 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001071 }
1072
Geoff Lang0c2c9232019-01-14 16:01:38 -05001073 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001074}
1075
Ian Elliottbcb78902018-12-19 11:46:29 -07001076void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001077{
Jamie Madillb36a4812018-09-25 10:15:11 -04001078// Use OpenGL line rasterization rules by default.
1079// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1080#if defined(ANGLE_PLATFORM_ANDROID)
1081 mFeatures.basicGLLineRasterization = false;
1082#else
Jamie Madill12222072018-07-11 14:59:48 -04001083 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001084#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001085
Ian Elliott52f5da42018-12-21 09:02:09 -07001086 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1087 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001088 {
1089 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1090 // investigation. http://anglebug.com/2728
1091 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1092 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001093
1094#ifdef ANGLE_PLATFORM_WINDOWS
1095 // http://anglebug.com/2838
1096 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001097
1098 // http://anglebug.com/3055
1099 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001100#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001101
1102 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1103 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001104
1105 // Work around incorrect NVIDIA point size range clamping.
1106 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1107 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1108 {
1109 mFeatures.clampPointSize = true;
1110 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001111
Jamie Madillfa7ca182019-01-15 11:20:58 -05001112 // We also need to clamp point size on several Android drivers.
1113 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1114 if (IsAndroid())
1115 {
1116 mFeatures.clampPointSize = true;
1117 }
1118
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001119#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001120 // Work around ineffective compute-graphics barriers on Nexus 5X.
1121 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1122 // http://anglebug.com/3019
1123 mFeatures.flushAfterVertexConversion =
1124 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001125#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001126
1127 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1128 {
1129 mFeatures.supportsIncrementalPresent = true;
1130 }
Jamie Madill12222072018-07-11 14:59:48 -04001131}
1132
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001133void RendererVk::initPipelineCacheVkKey()
1134{
1135 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1136 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1137 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1138 // there is no '\0' in the result.
1139 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1140 {
1141 hashStream << std::hex << c;
1142 }
1143 // Add the vendor and device id too for good measure.
1144 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1145 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1146
1147 const std::string &hashString = hashStream.str();
1148 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1149 hashString.length(), mPipelineCacheVkBlobKey.data());
1150}
1151
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001152angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001153{
1154 initPipelineCacheVkKey();
1155
1156 egl::BlobCache::Value initialData;
1157 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1158 mPipelineCacheVkBlobKey, &initialData);
1159
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001160 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001161
1162 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001163 pipelineCacheCreateInfo.flags = 0;
1164 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1165 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1166
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001167 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001168 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001169}
1170
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001171void RendererVk::getSubmitWaitSemaphores(
1172 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001173 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1174 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001175{
1176 if (mSubmitLastSignaledSemaphore.getSemaphore())
1177 {
1178 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001179 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001180
1181 // Return the semaphore to the pool (which will remain valid and unused until the
1182 // queue it's about to be waited on has finished execution).
1183 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1184 }
1185
1186 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1187 {
1188 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001189 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1190
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001191 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1192 }
1193 mSubmitWaitSemaphores.clear();
1194}
1195
Jamie Madillacccc6c2016-05-03 17:22:10 -04001196const gl::Caps &RendererVk::getNativeCaps() const
1197{
1198 ensureCapsInitialized();
1199 return mNativeCaps;
1200}
1201
1202const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1203{
1204 ensureCapsInitialized();
1205 return mNativeTextureCaps;
1206}
1207
1208const gl::Extensions &RendererVk::getNativeExtensions() const
1209{
1210 ensureCapsInitialized();
1211 return mNativeExtensions;
1212}
1213
1214const gl::Limitations &RendererVk::getNativeLimitations() const
1215{
1216 ensureCapsInitialized();
1217 return mNativeLimitations;
1218}
1219
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001220uint32_t RendererVk::getMaxActiveTextures()
1221{
1222 // TODO(lucferron): expose this limitation to GL in Context Caps
1223 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1224 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1225}
1226
Jamie Madill49ac74b2017-12-21 14:42:33 -05001227const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001228{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001229 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001230}
1231
Jamie Madill21061022018-07-12 23:56:30 -04001232angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001233{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001234 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001235 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001236 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1237
Luc Ferron1617e692018-07-11 11:08:19 -04001238 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1239 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001240
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001241 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001242 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1243 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001244
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001245 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001246 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001247 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1248 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001249 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001250 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001251 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001252 submitInfo.signalSemaphoreCount = 0;
1253 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001254
Jamie Madill21061022018-07-12 23:56:30 -04001255 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001256 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001257
Jamie Madill4c26fc22017-02-24 11:04:10 -05001258 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001259 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001260 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001261
1262 if (mGpuEventsEnabled)
1263 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001264 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001265 while (mInFlightGpuEventQueries.size() > 0)
1266 {
1267 ANGLE_TRY(checkCompletedGpuEvents(context));
1268 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001269 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1270 // synchronization if there is no event to be adjusted (happens when finish() gets called
1271 // multiple times towards the end of the application).
1272 if (mGpuEvents.size() > 0)
1273 {
1274 ANGLE_TRY(synchronizeCpuGpuTime(context));
1275 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001276 }
1277
Jamie Madill7c985f52018-11-29 18:16:17 -05001278 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001279}
1280
Jamie Madill0c0dc342017-03-24 14:18:51 -04001281void RendererVk::freeAllInFlightResources()
1282{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001283 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001284 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001285 // On device loss we need to wait for fence to be signaled before destroying it
1286 if (mDeviceLost)
1287 {
1288 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1289 // If wait times out, it is probably not possible to recover from lost device
1290 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1291 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001292 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001293 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001294 }
1295 mInFlightCommands.clear();
1296
1297 for (auto &garbage : mGarbage)
1298 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001299 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001300 }
1301 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001302
1303 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001304}
1305
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001306angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001307{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001308 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001309
Jamie Madill49ac74b2017-12-21 14:42:33 -05001310 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001311 {
Yuly Novikov27780292018-11-09 11:19:49 -05001312 VkResult result = batch.fence.getStatus(mDevice);
1313 if (result == VK_NOT_READY)
1314 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001315 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001316 }
1317 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318
Jamie Madill49ac74b2017-12-21 14:42:33 -05001319 ASSERT(batch.serial > mLastCompletedQueueSerial);
1320 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001321
Jamie Madill49ac74b2017-12-21 14:42:33 -05001322 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001323 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001324 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001325 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001326 }
1327
Jamie Madill49ac74b2017-12-21 14:42:33 -05001328 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001329
1330 size_t freeIndex = 0;
1331 for (; freeIndex < mGarbage.size(); ++freeIndex)
1332 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001333 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001334 break;
1335 }
1336
1337 // Remove the entries from the garbage list - they should be ready to go.
1338 if (freeIndex > 0)
1339 {
1340 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001341 }
1342
Jamie Madill7c985f52018-11-29 18:16:17 -05001343 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001344}
1345
Jamie Madill21061022018-07-12 23:56:30 -04001346angle::Result RendererVk::submitFrame(vk::Context *context,
1347 const VkSubmitInfo &submitInfo,
1348 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001349{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001350 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001351 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001352 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1353 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001354
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001355 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001356 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001357 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001358
Jamie Madill21061022018-07-12 23:56:30 -04001359 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001360
1361 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001362 batch.commandPool = std::move(mCommandPool);
1363 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001364
Jamie Madillbea35a62018-07-05 11:54:10 -04001365 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001366
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001367 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1368 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001369 // so the limit is larger than the expected number of images. The
1370 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001371 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001372
Jamie Madill85ca1892019-01-16 13:27:15 -05001373 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001374
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001375 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001376
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001377 if (mGpuEventsEnabled)
1378 {
1379 ANGLE_TRY(checkCompletedGpuEvents(context));
1380 }
1381
Jamie Madill49ac74b2017-12-21 14:42:33 -05001382 // Simply null out the command buffer here - it was allocated using the command pool.
1383 commandBuffer.releaseHandle();
1384
1385 // Reallocate the command pool for next frame.
1386 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001387 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001388 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001389 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001390 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001391
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001392 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001393 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001394}
1395
Jamie Madill85ca1892019-01-16 13:27:15 -05001396void RendererVk::nextSerial()
1397{
1398 // Increment the queue serial. If this fails, we should restart ANGLE.
1399 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1400 mCurrentQueueSerial = mQueueSerialFactory.generate();
1401
1402 // Notify the Contexts that they should be starting new command buffers.
1403 // We use one command pool per serial/submit associated with this VkQueue. We can also
1404 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1405 // check for a new serial when starting a new command buffer. We just check that the current
1406 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1407 // using this VkQueue that they their current command buffer is no longer valid.
1408 for (gl::Context *context : mDisplay->getContextSet())
1409 {
1410 ContextVk *contextVk = vk::GetImpl(context);
1411 contextVk->onCommandBufferFinished();
1412 }
1413}
1414
Jamie Madillaaca96e2018-06-12 10:19:48 -04001415bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001416{
1417 return serial > mLastCompletedQueueSerial;
1418}
1419
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001420angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1421{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001422 bool timedOut = false;
1423 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1424
1425 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1426 if (timedOut)
1427 {
1428 result = angle::Result::Stop;
1429 }
1430 return result;
1431}
1432
1433angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1434 Serial serial,
1435 uint64_t timeout,
1436 bool *outTimedOut)
1437{
1438 *outTimedOut = false;
1439
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001440 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1441 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001442 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001443 }
1444
1445 // Find the first batch with serial equal to or bigger than given serial (note that
1446 // the batch serials are unique, otherwise upper-bound would have been necessary).
1447 size_t batchIndex = mInFlightCommands.size() - 1;
1448 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1449 {
1450 if (mInFlightCommands[i].serial >= serial)
1451 {
1452 batchIndex = i;
1453 break;
1454 }
1455 }
1456 const CommandBatch &batch = mInFlightCommands[batchIndex];
1457
1458 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001459 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1460
1461 // If timed out, report it as such.
1462 if (status == VK_TIMEOUT)
1463 {
1464 *outTimedOut = true;
1465 return angle::Result::Continue;
1466 }
1467
1468 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001469
1470 // Clean up finished batches.
1471 return checkCompletedCommands(context);
1472}
1473
Jamie Madill21061022018-07-12 23:56:30 -04001474angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1475 const vk::RenderPassDesc &desc,
1476 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001477{
Jamie Madill21061022018-07-12 23:56:30 -04001478 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001479 renderPassOut);
1480}
1481
Jamie Madill21061022018-07-12 23:56:30 -04001482angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1483 const vk::RenderPassDesc &desc,
1484 const vk::AttachmentOpsArray &ops,
1485 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001486{
Jamie Madill21061022018-07-12 23:56:30 -04001487 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001488 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001489}
1490
Jamie Madilla5e06072018-05-18 14:36:05 -04001491vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001492{
Jamie Madilla5e06072018-05-18 14:36:05 -04001493 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001494}
1495
Jamie Madill21061022018-07-12 23:56:30 -04001496angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001497{
Jamie Madill21061022018-07-12 23:56:30 -04001498 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001499 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001500}
1501
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001502angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001503{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001504 if (mCommandGraph.empty())
1505 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001506 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001507 }
1508
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001509 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1510
Jamie Madillbea35a62018-07-05 11:54:10 -04001511 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1512 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001513
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001514 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001515 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1516 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001517
1518 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1519 // will be waited on.
1520 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001521
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001522 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001523 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001524 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1525 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001526 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001527 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001528 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001529 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001530 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001531
Jamie Madill21061022018-07-12 23:56:30 -04001532 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001533
Jamie Madill7c985f52018-11-29 18:16:17 -05001534 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001535}
1536
Jamie Madill78feddc2018-04-27 11:45:05 -04001537Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001538{
Jamie Madill78feddc2018-04-27 11:45:05 -04001539 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001540}
1541
Jamie Madill21061022018-07-12 23:56:30 -04001542angle::Result RendererVk::getDescriptorSetLayout(
1543 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001544 const vk::DescriptorSetLayoutDesc &desc,
1545 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1546{
Jamie Madill21061022018-07-12 23:56:30 -04001547 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001548}
1549
Jamie Madill21061022018-07-12 23:56:30 -04001550angle::Result RendererVk::getPipelineLayout(
1551 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001552 const vk::PipelineLayoutDesc &desc,
1553 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1554 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1555{
Jamie Madill21061022018-07-12 23:56:30 -04001556 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001557 pipelineLayoutOut);
1558}
1559
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001560angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1561{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001562 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001563
1564 if (--mPipelineCacheVkUpdateTimeout > 0)
1565 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001566 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001567 }
1568
1569 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1570
1571 // Get the size of the cache.
1572 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001573 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001574 if (result != VK_INCOMPLETE)
1575 {
1576 ANGLE_VK_TRY(displayVk, result);
1577 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001578
1579 angle::MemoryBuffer *pipelineCacheData = nullptr;
1580 ANGLE_VK_CHECK_ALLOC(displayVk,
1581 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1582
1583 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001584 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001585 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1586 // was determined just above), so receiving it hints at an implementation bug we would want
1587 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001588 ASSERT(result != VK_INCOMPLETE);
1589 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001590
1591 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1592 // the buffer to avoid leaking garbage memory.
1593 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1594 if (pipelineCacheSize < originalPipelineCacheSize)
1595 {
1596 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1597 originalPipelineCacheSize - pipelineCacheSize);
1598 }
1599
1600 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1601
Jamie Madill7c985f52018-11-29 18:16:17 -05001602 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001603}
1604
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001605angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1606 const vk::Semaphore **outSemaphore)
1607{
1608 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1609
1610 vk::SemaphoreHelper semaphore;
1611 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1612
1613 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1614 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1615
Jamie Madill7c985f52018-11-29 18:16:17 -05001616 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001617}
1618
1619const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1620{
1621 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1622
1623 // Return the semaphore to the pool (which will remain valid and unused until the
1624 // queue it's about to be waited on has finished execution). The caller is about
1625 // to wait on it.
1626 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1627
1628 return semaphore;
1629}
1630
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001631angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1632{
1633 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1634 // that seems impossible, so instead, we are going to make a small submission with just a
1635 // timestamp query. First, the disjoint timer query extension says:
1636 //
1637 // > This will return the GL time after all previous commands have reached the GL server but
1638 // have not yet necessarily executed.
1639 //
1640 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1641 // The wording allows us to make a submission to get the timestamp without performing a flush.
1642 //
1643 // Second:
1644 //
1645 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1646 // object target, applications can measure the latency between when commands reach the GL server
1647 // and when they are realized in the framebuffer.
1648 //
1649 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1650 // GPU bubble. This function directly generates a command buffer and submits it instead of
1651 // using the other member functions. This is to avoid changing any state, such as the queue
1652 // serial.
1653
1654 // Create a query used to receive the GPU timestamp
1655 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1656 vk::QueryHelper timestampQuery;
1657 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1658 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1659
1660 // Record the command buffer
1661 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1662 vk::CommandBuffer &commandBuffer = commandBatch.get();
1663
1664 VkCommandBufferAllocateInfo commandBufferInfo = {};
1665 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1666 commandBufferInfo.commandPool = mCommandPool.getHandle();
1667 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1668 commandBufferInfo.commandBufferCount = 1;
1669
Yuly Novikov27780292018-11-09 11:19:49 -05001670 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001671
1672 VkCommandBufferBeginInfo beginInfo = {};
1673 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1674 beginInfo.flags = 0;
1675 beginInfo.pInheritanceInfo = nullptr;
1676
Yuly Novikov27780292018-11-09 11:19:49 -05001677 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001678
1679 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1680 timestampQuery.getQuery(), 1);
1681 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1682 timestampQuery.getQueryPool()->getHandle(),
1683 timestampQuery.getQuery());
1684
Yuly Novikov27780292018-11-09 11:19:49 -05001685 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001686
1687 // Create fence for the submission
1688 VkFenceCreateInfo fenceInfo = {};
1689 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1690 fenceInfo.flags = 0;
1691
1692 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001693 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001694
1695 // Submit the command buffer
1696 VkSubmitInfo submitInfo = {};
1697 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1698 submitInfo.waitSemaphoreCount = 0;
1699 submitInfo.pWaitSemaphores = nullptr;
1700 submitInfo.pWaitDstStageMask = nullptr;
1701 submitInfo.commandBufferCount = 1;
1702 submitInfo.pCommandBuffers = commandBuffer.ptr();
1703 submitInfo.signalSemaphoreCount = 0;
1704 submitInfo.pSignalSemaphores = nullptr;
1705
1706 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1707
1708 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1709 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001710 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001711
1712 // Get the query results
1713 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1714
Yuly Novikov27780292018-11-09 11:19:49 -05001715 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1716 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1717 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001718
1719 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1720
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001721 // Convert results to nanoseconds.
1722 *timestampOut = static_cast<uint64_t>(
1723 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1724
Jamie Madill7c985f52018-11-29 18:16:17 -05001725 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001726}
1727
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001728// These functions look at the mandatory format for support, and fallback to querying the device (if
1729// necessary) to test the availability of the bits.
1730bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1731 const VkFormatFeatureFlags featureBits)
1732{
1733 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1734}
1735
1736bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1737 const VkFormatFeatureFlags featureBits)
1738{
1739 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1740}
1741
1742bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1743{
1744 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1745}
1746
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001747angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1748{
1749 ASSERT(mGpuEventsEnabled);
1750
1751 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1752 ASSERT(platform);
1753
1754 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1755 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1756 //
1757 // CPU GPU
1758 //
1759 // Record command buffer
1760 // with timestamp query
1761 //
1762 // Submit command buffer
1763 //
1764 // Post-submission work Begin execution
1765 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001766 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001767 //
1768 // ???? End execution
1769 //
1770 // ???? Return query results
1771 //
1772 // ????
1773 //
1774 // Get query results
1775 //
1776 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1777 // finished post-submission work while the GPU is executing in parallel. With no further work,
1778 // querying CPU timestamps before submission and after getting query results give the bounds to
1779 // Tgpu, which could be quite large.
1780 //
1781 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1782 // reduce this range. This function implements the following procedure:
1783 //
1784 // CPU GPU
1785 //
1786 // Record command buffer
1787 // with timestamp query
1788 //
1789 // Submit command buffer
1790 //
1791 // Post-submission work Begin execution
1792 //
1793 // ???? Set Event GPUReady
1794 //
1795 // Wait on Event GPUReady Wait on Event CPUReady
1796 //
1797 // Get CPU Time Ts Wait on Event CPUReady
1798 //
1799 // Set Event CPUReady Wait on Event CPUReady
1800 //
1801 // Get CPU Time Tcpu Get GPU Time Tgpu
1802 //
1803 // Wait on Event GPUDone Set Event GPUDone
1804 //
1805 // Get CPU Time Te End Execution
1806 //
1807 // Idle Return query results
1808 //
1809 // Get query results
1810 //
1811 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1812 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1813 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1814 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1815 // calibration.
1816 //
1817 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1818
1819 // Make sure nothing is running
1820 ASSERT(mCommandGraph.empty());
1821
1822 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1823
1824 // Create a query used to receive the GPU timestamp
1825 vk::QueryHelper timestampQuery;
1826 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1827
1828 // Create the three events
1829 VkEventCreateInfo eventCreateInfo = {};
1830 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1831 eventCreateInfo.flags = 0;
1832
1833 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001834 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1835 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1836 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001837
1838 constexpr uint32_t kRetries = 10;
1839
1840 // Time suffixes used are S for seconds and Cycles for cycles
1841 double tightestRangeS = 1e6f;
1842 double TcpuS = 0;
1843 uint64_t TgpuCycles = 0;
1844 for (uint32_t i = 0; i < kRetries; ++i)
1845 {
1846 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001847 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1848 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1849 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001850
1851 // Record the command buffer
1852 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1853 vk::CommandBuffer &commandBuffer = commandBatch.get();
1854
1855 VkCommandBufferAllocateInfo commandBufferInfo = {};
1856 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1857 commandBufferInfo.commandPool = mCommandPool.getHandle();
1858 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1859 commandBufferInfo.commandBufferCount = 1;
1860
Yuly Novikov27780292018-11-09 11:19:49 -05001861 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001862
1863 VkCommandBufferBeginInfo beginInfo = {};
1864 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1865 beginInfo.flags = 0;
1866 beginInfo.pInheritanceInfo = nullptr;
1867
Yuly Novikov27780292018-11-09 11:19:49 -05001868 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001869
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001870 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001871 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1872 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1873 nullptr);
1874
1875 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1876 timestampQuery.getQuery(), 1);
1877 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1878 timestampQuery.getQueryPool()->getHandle(),
1879 timestampQuery.getQuery());
1880
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001881 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001882
Yuly Novikov27780292018-11-09 11:19:49 -05001883 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001884
1885 // Submit the command buffer
1886 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1887 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1888 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1889
1890 VkSubmitInfo submitInfo = {};
1891 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1892 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1893 submitInfo.pWaitSemaphores = waitSemaphores.data();
1894 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1895 submitInfo.commandBufferCount = 1;
1896 submitInfo.pCommandBuffers = commandBuffer.ptr();
1897 submitInfo.signalSemaphoreCount = 0;
1898 submitInfo.pSignalSemaphores = nullptr;
1899
1900 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1901
1902 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001903 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001904 do
1905 {
Yuly Novikov27780292018-11-09 11:19:49 -05001906 result = gpuReady.get().getStatus(mDevice);
1907 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1908 {
1909 ANGLE_VK_TRY(context, result);
1910 }
1911 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001912
1913 double TsS = platform->monotonicallyIncreasingTime(platform);
1914
1915 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001916 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001917 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1918
1919 // Wait for GPU to be done. Another short busy wait.
1920 do
1921 {
Yuly Novikov27780292018-11-09 11:19:49 -05001922 result = gpuDone.get().getStatus(mDevice);
1923 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1924 {
1925 ANGLE_VK_TRY(context, result);
1926 }
1927 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001928
1929 double TeS = platform->monotonicallyIncreasingTime(platform);
1930
1931 // Get the query results
1932 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1933
1934 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1935
1936 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001937 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1938 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1939 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001940
1941 // Use the first timestamp queried as origin.
1942 if (mGpuEventTimestampOrigin == 0)
1943 {
1944 mGpuEventTimestampOrigin = gpuTimestampCycles;
1945 }
1946
1947 // Take these CPU and GPU timestamps if there is better confidence.
1948 double confidenceRangeS = TeS - TsS;
1949 if (confidenceRangeS < tightestRangeS)
1950 {
1951 tightestRangeS = confidenceRangeS;
1952 TcpuS = cpuTimestampS;
1953 TgpuCycles = gpuTimestampCycles;
1954 }
1955 }
1956
1957 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1958
1959 // timestampPeriod gives nanoseconds/cycle.
1960 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1961 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1962 1'000'000'000.0;
1963
1964 flushGpuEvents(TgpuS, TcpuS);
1965
1966 mGpuClockSync.gpuTimestampS = TgpuS;
1967 mGpuClockSync.cpuTimestampS = TcpuS;
1968
Jamie Madill7c985f52018-11-29 18:16:17 -05001969 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001970}
1971
1972angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1973 vk::CommandBuffer *commandBuffer,
1974 char phase,
1975 const char *name)
1976{
1977 ASSERT(mGpuEventsEnabled);
1978
1979 GpuEventQuery event;
1980
1981 event.name = name;
1982 event.phase = phase;
1983 event.serial = mCurrentQueueSerial;
1984
1985 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1986
1987 commandBuffer->resetQueryPool(
1988 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1989 commandBuffer->writeTimestamp(
1990 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1991 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1992
1993 mInFlightGpuEventQueries.push_back(std::move(event));
1994
Jamie Madill7c985f52018-11-29 18:16:17 -05001995 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001996}
1997
1998angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1999{
2000 ASSERT(mGpuEventsEnabled);
2001
2002 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2003 ASSERT(platform);
2004
2005 int finishedCount = 0;
2006
2007 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2008 {
2009 // Only check the timestamp query if the submission has finished.
2010 if (eventQuery.serial > mLastCompletedQueueSerial)
2011 {
2012 break;
2013 }
2014
2015 // See if the results are available.
2016 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002017 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2018 ->getResults(mDevice, eventQuery.queryIndex, 1,
2019 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2020 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2021 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002022 {
2023 break;
2024 }
Yuly Novikov27780292018-11-09 11:19:49 -05002025 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002026
2027 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2028
2029 GpuEvent event;
2030 event.gpuTimestampCycles = gpuTimestampCycles;
2031 event.name = eventQuery.name;
2032 event.phase = eventQuery.phase;
2033
2034 mGpuEvents.emplace_back(event);
2035
2036 ++finishedCount;
2037 }
2038
2039 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2040 mInFlightGpuEventQueries.begin() + finishedCount);
2041
Jamie Madill7c985f52018-11-29 18:16:17 -05002042 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002043}
2044
2045void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2046{
2047 if (mGpuEvents.size() == 0)
2048 {
2049 return;
2050 }
2051
2052 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2053 ASSERT(platform);
2054
2055 // Find the slope of the clock drift for adjustment
2056 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2057 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2058 double gpuSyncDriftSlope = 0;
2059
2060 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2061 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2062
2063 // No gpu trace events should have been generated before the clock sync, so if there is no
2064 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2065 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2066 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2067
2068 gpuSyncDriftSlope =
2069 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2070
2071 for (const GpuEvent &event : mGpuEvents)
2072 {
2073 double gpuTimestampS =
2074 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2075 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2076
2077 // Account for clock drift.
2078 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2079
2080 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2081 // for.
2082 static long long eventId = 1;
2083 static const unsigned char *categoryEnabled =
2084 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2085 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2086 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2087 }
2088
2089 mGpuEvents.clear();
2090}
2091
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002092template <VkFormatFeatureFlags VkFormatProperties::*features>
2093bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2094{
2095 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2096 VkFormatProperties &deviceProperties = mFormatProperties[format];
2097
2098 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2099 {
2100 // If we don't have the actual device features, see if the requested features are mandatory.
2101 // If so, there's no need to query the device.
2102 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2103 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2104 {
2105 return true;
2106 }
2107
2108 // Otherwise query the format features and cache it.
2109 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2110 }
2111
2112 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2113}
2114
Jamie Madillaaca96e2018-06-12 10:19:48 -04002115uint32_t GetUniformBufferDescriptorCount()
2116{
2117 return kUniformBufferDescriptorsPerDescriptorSet;
2118}
2119
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002120} // namespace rx