blob: 9e14e4b7c39bf6b2e6a9bc76187c382c10dc1030 [file] [log] [blame]
Jamie Madill9e54b5a2016-05-25 12:57:39 -04001//
2// Copyright 2016 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6// RendererVk.cpp:
7// Implements the class methods for RendererVk.
8//
9
10#include "libANGLE/renderer/vulkan/RendererVk.h"
11
Jamie Madill4d0bf552016-12-28 15:45:24 -050012// Placing this first seems to solve an intellisense bug.
Jamie Madill3c424b42018-01-19 12:35:09 -050013#include "libANGLE/renderer/vulkan/vk_utils.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050014
Jamie Madille09bd5d2016-11-29 16:20:35 -050015#include <EGL/eglext.h>
16
Jamie Madill9e54b5a2016-05-25 12:57:39 -040017#include "common/debug.h"
Yuly Novikov5fe7c5b2019-01-17 12:16:34 -050018#include "common/platform.h"
Jamie Madilla66779f2017-01-06 10:43:44 -050019#include "common/system_utils.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050020#include "libANGLE/Context.h"
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040021#include "libANGLE/Display.h"
Jamie Madill4d0bf552016-12-28 15:45:24 -050022#include "libANGLE/renderer/driver_utils.h"
Jamie Madill1f46bc12018-02-20 16:09:43 -050023#include "libANGLE/renderer/vulkan/CommandGraph.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050024#include "libANGLE/renderer/vulkan/CompilerVk.h"
Jamie Madill85ca1892019-01-16 13:27:15 -050025#include "libANGLE/renderer/vulkan/ContextVk.h"
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040026#include "libANGLE/renderer/vulkan/DisplayVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050027#include "libANGLE/renderer/vulkan/FramebufferVk.h"
Jamie Madill8ecf7f92017-01-13 17:29:52 -050028#include "libANGLE/renderer/vulkan/GlslangWrapper.h"
Jamie Madillffa4cbb2018-01-23 13:04:07 -050029#include "libANGLE/renderer/vulkan/ProgramVk.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050030#include "libANGLE/renderer/vulkan/VertexArrayVk.h"
Luc Ferrone4741fd2018-01-25 13:25:27 -050031#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
Jamie Madill3c424b42018-01-19 12:35:09 -050032#include "libANGLE/renderer/vulkan/vk_format_utils.h"
Jamie Madille09bd5d2016-11-29 16:20:35 -050033#include "platform/Platform.h"
Shahbaz Youssefi61656022018-10-24 15:00:50 -040034#include "third_party/trace_event/trace_event.h"
35
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070036// Consts
37namespace
38{
Jamie Madill7c985f52018-11-29 18:16:17 -050039const uint32_t kMockVendorID = 0xba5eba11;
40const uint32_t kMockDeviceID = 0xf005ba11;
41constexpr char kMockDeviceName[] = "Vulkan Mock Device";
42constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050043constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070044} // anonymous namespace
45
Jamie Madill9e54b5a2016-05-25 12:57:39 -040046namespace rx
47{
48
Jamie Madille09bd5d2016-11-29 16:20:35 -050049namespace
50{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040051// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
52// one for the vertex shader.
53constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040054// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050055constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040056// Wait a maximum of 10s. If that times out, we declare it a failure.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -050057constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Ian Elliott356d26c2019-02-11 11:27:01 -070058// Per the Vulkan specification, as long as Vulkan 1.1+ is returned by vkEnumerateInstanceVersion,
59// ANGLE must indicate the highest version of Vulkan functionality that it uses. The Vulkan
60// validation layers will issue messages for any core functionality that requires a higher version.
61// This value must be increased whenever ANGLE starts using functionality from a newer core
62// version of Vulkan.
63constexpr uint32_t kPreferredVulkanAPIVersion = VK_API_VERSION_1_1;
Jamie Madille09bd5d2016-11-29 16:20:35 -050064
Omar El Sheikh26c61b22018-06-29 12:50:59 -060065bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
66{
67#if !defined(ANGLE_PLATFORM_ANDROID)
68 // Mock ICD does not currently run on Android
69 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
70 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
71 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
72#else
73 return false;
74#endif // !defined(ANGLE_PLATFORM_ANDROID)
75}
76
Frank Henigman52047de2018-11-13 17:22:36 -050077bool StrLess(const char *a, const char *b)
Jamie Madille09bd5d2016-11-29 16:20:35 -050078{
Frank Henigman52047de2018-11-13 17:22:36 -050079 return strcmp(a, b) < 0;
Jamie Madille09bd5d2016-11-29 16:20:35 -050080}
81
Frank Henigman52047de2018-11-13 17:22:36 -050082bool ExtensionFound(const char *needle, const RendererVk::ExtensionNameList &haystack)
83{
84 // NOTE: The list must be sorted.
85 return std::binary_search(haystack.begin(), haystack.end(), needle, StrLess);
Tobin Ehlis3a181e32018-08-29 15:17:05 -060086}
87
Yuly Novikovdbbdf562019-02-27 19:48:16 -050088VkResult VerifyExtensionsPresent(const RendererVk::ExtensionNameList &haystack,
89 const RendererVk::ExtensionNameList &needles)
90{
91 // NOTE: The lists must be sorted.
92 if (std::includes(haystack.begin(), haystack.end(), needles.begin(), needles.end(), StrLess))
93 {
94 return VK_SUCCESS;
95 }
96 for (const char *needle : needles)
97 {
98 if (!ExtensionFound(needle, haystack))
99 {
100 ERR() << "Extension not supported: " << needle;
101 }
102 }
103 return VK_ERROR_EXTENSION_NOT_PRESENT;
104}
105
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500106// Array of Validation error/warning messages that will be ignored, should include bugID
Jamie Madill00f43c92019-02-09 11:41:12 -0500107constexpr const char *kSkippedMessages[] = {
108 // http://anglebug.com/2866
109 "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500110 // http://anglebug.com/2796
Jamie Madill00f43c92019-02-09 11:41:12 -0500111 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing",
112};
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500113
114// Suppress validation errors that are known
115// return "true" if given code/prefix/message is known, else return "false"
116bool IsIgnoredDebugMessage(const char *message)
117{
Michael Spang25839802019-01-30 18:02:51 -0500118 if (!message)
119 {
120 return false;
121 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500122 for (const char *msg : kSkippedMessages)
123 {
124 if (strstr(message, msg) != nullptr)
125 {
126 return true;
127 }
128 }
129 return false;
130}
131
132const char *GetVkObjectTypeName(VkObjectType type)
133{
134 switch (type)
135 {
136 case VK_OBJECT_TYPE_UNKNOWN:
137 return "Unknown";
138 case VK_OBJECT_TYPE_INSTANCE:
139 return "Instance";
140 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
141 return "Physical Device";
142 case VK_OBJECT_TYPE_DEVICE:
143 return "Device";
144 case VK_OBJECT_TYPE_QUEUE:
145 return "Queue";
146 case VK_OBJECT_TYPE_SEMAPHORE:
147 return "Semaphore";
148 case VK_OBJECT_TYPE_COMMAND_BUFFER:
149 return "Command Buffer";
150 case VK_OBJECT_TYPE_FENCE:
151 return "Fence";
152 case VK_OBJECT_TYPE_DEVICE_MEMORY:
153 return "Device Memory";
154 case VK_OBJECT_TYPE_BUFFER:
155 return "Buffer";
156 case VK_OBJECT_TYPE_IMAGE:
157 return "Image";
158 case VK_OBJECT_TYPE_EVENT:
159 return "Event";
160 case VK_OBJECT_TYPE_QUERY_POOL:
161 return "Query Pool";
162 case VK_OBJECT_TYPE_BUFFER_VIEW:
163 return "Buffer View";
164 case VK_OBJECT_TYPE_IMAGE_VIEW:
165 return "Image View";
166 case VK_OBJECT_TYPE_SHADER_MODULE:
167 return "Shader Module";
168 case VK_OBJECT_TYPE_PIPELINE_CACHE:
169 return "Pipeline Cache";
170 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
171 return "Pipeline Layout";
172 case VK_OBJECT_TYPE_RENDER_PASS:
173 return "Render Pass";
174 case VK_OBJECT_TYPE_PIPELINE:
175 return "Pipeline";
176 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
177 return "Descriptor Set Layout";
178 case VK_OBJECT_TYPE_SAMPLER:
179 return "Sampler";
180 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
181 return "Descriptor Pool";
182 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
183 return "Descriptor Set";
184 case VK_OBJECT_TYPE_FRAMEBUFFER:
185 return "Framebuffer";
186 case VK_OBJECT_TYPE_COMMAND_POOL:
187 return "Command Pool";
188 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
189 return "Sampler YCbCr Conversion";
190 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
191 return "Descriptor Update Template";
192 case VK_OBJECT_TYPE_SURFACE_KHR:
193 return "Surface";
194 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
195 return "Swapchain";
196 case VK_OBJECT_TYPE_DISPLAY_KHR:
197 return "Display";
198 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
199 return "Display Mode";
200 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
201 return "Debug Report Callback";
202 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
203 return "Object Table";
204 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
205 return "Indirect Commands Layout";
206 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
207 return "Debug Utils Messenger";
208 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
209 return "Validation Cache";
Shahbaz Youssefi6f1a8522019-02-26 15:00:54 +0000210 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV:
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500211 return "Acceleration Structure";
212 default:
213 return "<Unrecognized>";
214 }
215}
216
217VKAPI_ATTR VkBool32 VKAPI_CALL
218DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
219 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
220 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
221 void *userData)
222{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500223 // See if it's an issue we are aware of and don't want to be spammed about.
224 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
225 {
226 return VK_FALSE;
227 }
228
229 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500230 if (callbackData->pMessageIdName)
231 {
232 log << "[ " << callbackData->pMessageIdName << " ] ";
233 }
234 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500235
236 // Aesthetic value based on length of the function name, line number, etc.
237 constexpr size_t kStartIndent = 28;
238
239 // Output the debug marker hierarchy under which this error has occured.
240 size_t indent = kStartIndent;
241 if (callbackData->queueLabelCount > 0)
242 {
243 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
244 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
245 {
246 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
247 << std::endl;
248 }
249 }
250 if (callbackData->cmdBufLabelCount > 0)
251 {
252 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
253 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
254 {
255 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
256 << std::endl;
257 }
258 }
259 // Output the objects involved in this error message.
260 if (callbackData->objectCount > 0)
261 {
262 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
263 {
264 const char *objectName = callbackData->pObjects[i].pObjectName;
265 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
266 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
267 log << std::string(indent, ' ') << "Object: ";
268 if (objectHandle == 0)
269 {
270 log << "VK_NULL_HANDLE";
271 }
272 else
273 {
274 log << "0x" << std::hex << objectHandle << std::dec;
275 }
276 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
277 if (objectName)
278 {
279 log << " [" << objectName << "]";
280 }
281 log << std::endl;
282 }
283 }
284
Jamie Madill54ed8f02019-02-11 12:32:04 -0500285 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
286 std::string msg = log.str();
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500287
288 if (isError)
289 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500290 ERR() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500291 }
292 else
293 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500294 WARN() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500295 }
296
297 return VK_FALSE;
298}
299
Yuly Novikov199f4292018-01-19 19:04:05 -0500300VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
301 VkDebugReportObjectTypeEXT objectType,
302 uint64_t object,
303 size_t location,
304 int32_t messageCode,
305 const char *layerPrefix,
306 const char *message,
307 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500308{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600309 if (IsIgnoredDebugMessage(message))
310 {
311 return VK_FALSE;
312 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500313 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
314 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500315 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500316#if !defined(NDEBUG)
317 // Abort the call in Debug builds.
318 return VK_TRUE;
319#endif
320 }
321 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
322 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500323 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500324 }
325 else
326 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500327 // Uncomment this if you want Vulkan spam.
328 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500329 }
330
331 return VK_FALSE;
332}
333
Yuly Novikov199f4292018-01-19 19:04:05 -0500334// If we're loading the validation layers, we could be running from any random directory.
335// Change to the executable directory so we can find the layers, then change back to the
336// previous directory to be safe we don't disrupt the application.
337class ScopedVkLoaderEnvironment : angle::NonCopyable
338{
339 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600340 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
341 : mEnableValidationLayers(enableValidationLayers),
342 mEnableMockICD(enableMockICD),
343 mChangedCWD(false),
344 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500345 {
346// Changing CWD and setting environment variables makes no sense on Android,
347// since this code is a part of Java application there.
348// Android Vulkan loader doesn't need this either.
Michael Spang229fc832019-01-21 18:09:15 -0500349#if !defined(ANGLE_PLATFORM_ANDROID) && !defined(ANGLE_PLATFORM_FUCHSIA)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600350 if (enableMockICD)
351 {
352 // Override environment variable to use built Mock ICD
353 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
354 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
355 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
356 if (!mChangedICDPath)
357 {
358 ERR() << "Error setting Path for Mock/Null Driver.";
359 mEnableMockICD = false;
360 }
361 }
Jamie Madill46848422018-08-09 10:46:06 -0400362 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500363 {
364 const auto &cwd = angle::GetCWD();
365 if (!cwd.valid())
366 {
367 ERR() << "Error getting CWD for Vulkan layers init.";
368 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400369 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500370 }
371 else
372 {
373 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500374 std::string exeDir = angle::GetExecutableDirectory();
375 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500376 if (!mChangedCWD)
377 {
378 ERR() << "Error setting CWD for Vulkan layers init.";
379 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400380 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500381 }
382 }
383 }
384
385 // Override environment variable to use the ANGLE layers.
386 if (mEnableValidationLayers)
387 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700388 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500389 {
390 ERR() << "Error setting environment for Vulkan layers init.";
391 mEnableValidationLayers = false;
392 }
393 }
394#endif // !defined(ANGLE_PLATFORM_ANDROID)
395 }
396
397 ~ScopedVkLoaderEnvironment()
398 {
399 if (mChangedCWD)
400 {
401#if !defined(ANGLE_PLATFORM_ANDROID)
402 ASSERT(mPreviousCWD.valid());
403 angle::SetCWD(mPreviousCWD.value().c_str());
404#endif // !defined(ANGLE_PLATFORM_ANDROID)
405 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600406 if (mChangedICDPath)
407 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600408 if (mPreviousICDPath.value().empty())
409 {
410 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
411 }
412 else
413 {
414 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
415 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600416 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500417 }
418
Jamie Madillaaca96e2018-06-12 10:19:48 -0400419 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500420
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600421 bool canEnableMockICD() const { return mEnableMockICD; }
422
Yuly Novikov199f4292018-01-19 19:04:05 -0500423 private:
424 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600425 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500426 bool mChangedCWD;
427 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600428 bool mChangedICDPath;
429 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500430};
431
Jamie Madill21061022018-07-12 23:56:30 -0400432void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
433 bool preferMockICD,
434 VkPhysicalDevice *physicalDeviceOut,
435 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
436{
437 ASSERT(!physicalDevices.empty());
438 if (preferMockICD)
439 {
440 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
441 {
442 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
443 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
444 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
445 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
446 {
447 *physicalDeviceOut = physicalDevice;
448 return;
449 }
450 }
451 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
452 "physicalDevice instead.";
453 }
454
455 // Fall back to first device.
456 *physicalDeviceOut = physicalDevices[0];
457 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
458}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400459
460// Initially dumping the command graphs is disabled.
461constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700462
Jamie Madille09bd5d2016-11-29 16:20:35 -0500463} // anonymous namespace
464
Jamie Madill49ac74b2017-12-21 14:42:33 -0500465// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400466RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500467
Jamie Madillaaca96e2018-06-12 10:19:48 -0400468RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500469
470RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -0500471{
472 *this = std::move(other);
473}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500474
475RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
476{
477 std::swap(commandPool, other.commandPool);
478 std::swap(fence, other.fence);
479 std::swap(serial, other.serial);
480 return *this;
481}
482
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000483void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400484{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000485 commandPool.destroy(device);
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -0500486 fence.reset(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400487}
488
Jamie Madill9f2a8612017-11-30 12:43:09 -0500489// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500490RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400491 : mDisplay(nullptr),
492 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700493 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500494 mInstance(VK_NULL_HANDLE),
495 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400496 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500497 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500498 mDebugReportCallback(VK_NULL_HANDLE),
499 mPhysicalDevice(VK_NULL_HANDLE),
500 mQueue(VK_NULL_HANDLE),
501 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
Frank Henigman52047de2018-11-13 17:22:36 -0500502 mMaxVertexAttribDivisor(1),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500503 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400504 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400505 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400506 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400507 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400508 mCommandGraph(kEnableCommandGraphDiagnostics),
509 mGpuEventsEnabled(false),
510 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
511 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500512{
513 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
514 mFormatProperties.fill(invalid);
515}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400516
Jamie Madillb980c562018-11-27 11:34:27 -0500517RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400518
519void RendererVk::onDestroy(vk::Context *context)
520{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500521 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500522 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500523 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400524 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500525 }
526
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100527 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500528
Jamie Madillc7918ce2018-06-13 13:25:31 -0400529 mPipelineLayoutCache.destroy(mDevice);
530 mDescriptorSetLayoutCache.destroy(mDevice);
531
Jamie Madill9f2a8612017-11-30 12:43:09 -0500532 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500533 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400534 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400535 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400536 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500537
Jamie Madill06ca6342018-07-12 15:56:53 -0400538 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500539
Jamie Madill5deea722017-02-16 10:44:46 -0500540 if (mCommandPool.valid())
541 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000542 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500543 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500544
545 if (mDevice)
546 {
547 vkDestroyDevice(mDevice, nullptr);
548 mDevice = VK_NULL_HANDLE;
549 }
550
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500551 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500552 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500553 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
554 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
555
556 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
557 }
558 else if (mDebugReportCallback)
559 {
560 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
561 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500562 }
563
Jamie Madill4d0bf552016-12-28 15:45:24 -0500564 if (mInstance)
565 {
566 vkDestroyInstance(mInstance, nullptr);
567 mInstance = VK_NULL_HANDLE;
568 }
569
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600570 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500571 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500572}
573
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400574void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400575{
576 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400577
578 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500579 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400580 freeAllInFlightResources();
581
582 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400583}
584
585bool RendererVk::isDeviceLost() const
586{
587 return mDeviceLost;
588}
589
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400590angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400591 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500592 const char *wsiExtension,
593 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500594{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400595 mDisplay = display;
596 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600597 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
598 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500599 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400600 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500601
Jamie Madill0448ec82016-12-23 13:41:47 -0500602 // Gather global layer properties.
603 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400604 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500605
606 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
607 if (instanceLayerCount > 0)
608 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400609 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
610 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500611 }
612
Michael Spang6c13c702019-02-06 15:59:44 -0500613 VulkanLayerVector enabledInstanceLayerNames;
614 if (mEnableValidationLayers)
615 {
616 bool layersRequested =
617 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
618 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
619 &enabledInstanceLayerNames);
620 }
621
622 if (wsiLayer)
623 {
624 enabledInstanceLayerNames.push_back(wsiLayer);
625 }
626
627 // Enumerate instance extensions that are provided by the vulkan
628 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500629 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400630 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400631 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500632
633 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
634 if (instanceExtensionCount > 0)
635 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400636 ANGLE_VK_TRY(displayVk,
637 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
638 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500639 }
640
Michael Spang6c13c702019-02-06 15:59:44 -0500641 // Enumerate instance extensions that are provided by explicit layers.
642 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500643 {
Michael Spang6c13c702019-02-06 15:59:44 -0500644 uint32_t previousExtensionCount = instanceExtensionProps.size();
645 uint32_t instanceLayerExtensionCount = 0;
646 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
647 layerName, &instanceLayerExtensionCount, nullptr));
648 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
649 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
650 layerName, &instanceLayerExtensionCount,
651 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500652 }
653
Frank Henigman52047de2018-11-13 17:22:36 -0500654 ExtensionNameList instanceExtensionNames;
655 if (!instanceExtensionProps.empty())
656 {
657 for (const VkExtensionProperties &i : instanceExtensionProps)
658 {
659 instanceExtensionNames.push_back(i.extensionName);
660 }
661 std::sort(instanceExtensionNames.begin(), instanceExtensionNames.end(), StrLess);
662 }
663
664 ExtensionNameList enabledInstanceExtensions;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500665 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500666 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500667
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500668 bool enableDebugUtils =
669 mEnableValidationLayers &&
Frank Henigman52047de2018-11-13 17:22:36 -0500670 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionNames);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500671 bool enableDebugReport =
672 mEnableValidationLayers && !enableDebugUtils &&
Frank Henigman52047de2018-11-13 17:22:36 -0500673 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionNames);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500674
675 if (enableDebugUtils)
676 {
677 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
678 }
679 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500680 {
681 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
682 }
683
Jamie Madille09bd5d2016-11-29 16:20:35 -0500684 // Verify the required extensions are in the extension names set. Fail if not.
Frank Henigman52047de2018-11-13 17:22:36 -0500685 std::sort(enabledInstanceExtensions.begin(), enabledInstanceExtensions.end(), StrLess);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400686 ANGLE_VK_TRY(displayVk,
Frank Henigman52047de2018-11-13 17:22:36 -0500687 VerifyExtensionsPresent(instanceExtensionNames, enabledInstanceExtensions));
688
689 // Enable VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME if available.
690 if (ExtensionFound(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME,
691 instanceExtensionNames))
692 {
693 enabledInstanceExtensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
694 }
Jamie Madille09bd5d2016-11-29 16:20:35 -0500695
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400696 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500697 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500698 applicationInfo.pApplicationName = "ANGLE";
699 applicationInfo.applicationVersion = 1;
700 applicationInfo.pEngineName = "ANGLE";
701 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700702
703 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
704 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
705 if (!enumerateInstanceVersion)
706 {
707 applicationInfo.apiVersion = VK_API_VERSION_1_0;
708 }
709 else
710 {
711 uint32_t apiVersion = VK_API_VERSION_1_0;
712 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
713 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
714 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700715 // This is the highest version of core Vulkan functionality that ANGLE uses.
716 applicationInfo.apiVersion = kPreferredVulkanAPIVersion;
Ian Elliott899c5d22018-12-21 13:12:50 -0700717 }
718 else
719 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700720 // Since only 1.0 instance-level functionality is available, this must set to 1.0.
Ian Elliott899c5d22018-12-21 13:12:50 -0700721 applicationInfo.apiVersion = VK_API_VERSION_1_0;
722 }
723 }
Jamie Madill327ba852016-11-30 12:38:28 -0500724
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400725 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500726 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
727 instanceInfo.flags = 0;
728 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500729
Jamie Madille09bd5d2016-11-29 16:20:35 -0500730 // Enable requested layers and extensions.
731 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
732 instanceInfo.ppEnabledExtensionNames =
733 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500734 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
735 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500736
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400737 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500738
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500739 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500740 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500741 // Try to use the newer EXT_debug_utils if it exists.
742 InitDebugUtilsEXTFunctions(mInstance);
743
744 // Create the messenger callback.
745 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
746
Shahbaz Youssefi4d153382019-02-26 15:08:11 +0000747 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
748 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
749 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
750
751 constexpr VkDebugUtilsMessageTypeFlagsEXT kMessagesToLog =
752 VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
753 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
754 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
755
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500756 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
Shahbaz Youssefi4d153382019-02-26 15:08:11 +0000757 messengerInfo.messageSeverity = kSeveritiesToLog;
758 messengerInfo.messageType = kMessagesToLog;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500759 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
760 messengerInfo.pUserData = this;
761
762 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
763 &mDebugUtilsMessenger));
764 }
765 else if (enableDebugReport)
766 {
767 // Fallback to EXT_debug_report.
768 InitDebugReportEXTFunctions(mInstance);
769
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400770 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500771
772 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500773 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500774 debugReportInfo.pfnCallback = &DebugReportCallback;
775 debugReportInfo.pUserData = this;
776
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500777 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
778 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500779 }
780
Frank Henigman52047de2018-11-13 17:22:36 -0500781 if (std::find(enabledInstanceExtensions.begin(), enabledInstanceExtensions.end(),
782 VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) !=
783 enabledInstanceExtensions.end())
784 {
785 InitGetPhysicalDeviceProperties2KHRFunctions(mInstance);
786 ASSERT(vkGetPhysicalDeviceProperties2KHR);
787 }
788
Jamie Madill4d0bf552016-12-28 15:45:24 -0500789 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400790 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
791 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500792
793 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700794 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400795 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
796 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400797 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700798 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500799
Jamie Madill30b5d842018-08-31 17:19:12 -0400800 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
801
Jamie Madill4d0bf552016-12-28 15:45:24 -0500802 // Ensure we can find a graphics queue family.
803 uint32_t queueCount = 0;
804 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
805
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400806 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500807
808 mQueueFamilyProperties.resize(queueCount);
809 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
810 mQueueFamilyProperties.data());
811
Jamie Madillb980c562018-11-27 11:34:27 -0500812 size_t graphicsQueueFamilyCount = false;
813 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500814 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500815 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
816 {
817 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500818 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500819 {
820 ASSERT(queueInfo.queueCount > 0);
821 graphicsQueueFamilyCount++;
822 if (firstGraphicsQueueFamily == 0)
823 {
824 firstGraphicsQueueFamily = familyIndex;
825 }
826 break;
827 }
828 }
829
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400830 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500831
832 // If only one queue family, go ahead and initialize the device. If there is more than one
833 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
834 if (graphicsQueueFamilyCount == 1)
835 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400836 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500837 }
838
Jamie Madill035fd6b2017-10-03 15:43:22 -0400839 // Store the physical device memory properties so we can find the right memory pools.
840 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500841
Jamie Madill06ca6342018-07-12 15:56:53 -0400842 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500843
Jamie Madill6a89d222017-11-02 11:59:51 -0400844 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500845 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400846
Jamie Madill7c985f52018-11-29 18:16:17 -0500847 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400848}
849
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400850angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500851{
852 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400853 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400854 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500855
856 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
857 if (deviceLayerCount > 0)
858 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400859 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
860 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500861 }
862
Michael Spang6c13c702019-02-06 15:59:44 -0500863 VulkanLayerVector enabledDeviceLayerNames;
864 if (mEnableValidationLayers)
865 {
866 mEnableValidationLayers =
867 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
868 }
869
870 const char *wsiLayer = displayVk->getWSILayer();
871 if (wsiLayer)
872 {
873 enabledDeviceLayerNames.push_back(wsiLayer);
874 }
875
876 // Enumerate device extensions that are provided by the vulkan
877 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500878 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400879 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
880 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500881
882 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
883 if (deviceExtensionCount > 0)
884 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400885 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
886 &deviceExtensionCount,
887 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500888 }
889
Michael Spang6c13c702019-02-06 15:59:44 -0500890 // Enumerate device extensions that are provided by explicit layers.
891 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500892 {
Michael Spang6c13c702019-02-06 15:59:44 -0500893 uint32_t previousExtensionCount = deviceExtensionProps.size();
894 uint32_t deviceLayerExtensionCount = 0;
895 ANGLE_VK_TRY(displayVk,
896 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
897 &deviceLayerExtensionCount, nullptr));
898 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
899 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
900 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
901 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500902 }
903
Frank Henigman52047de2018-11-13 17:22:36 -0500904 ExtensionNameList deviceExtensionNames;
905 if (!deviceExtensionProps.empty())
906 {
907 ASSERT(deviceExtensionNames.size() <= deviceExtensionProps.size());
908 for (const VkExtensionProperties &prop : deviceExtensionProps)
909 {
910 deviceExtensionNames.push_back(prop.extensionName);
911 }
912 std::sort(deviceExtensionNames.begin(), deviceExtensionNames.end(), StrLess);
913 }
914
915 ExtensionNameList enabledDeviceExtensions;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500916 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
917
Frank Henigman52047de2018-11-13 17:22:36 -0500918 initFeatures(deviceExtensionNames);
Ian Elliottbcb78902018-12-19 11:46:29 -0700919 mFeaturesInitialized = true;
920
Luc Ferronbf6dc372018-06-28 15:24:19 -0400921 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700922 if ((getFeatures().flipViewportY) &&
923 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400924 {
925 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
926 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700927 if (getFeatures().supportsIncrementalPresent)
928 {
929 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
930 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400931
Geoff Lang009696c2019-01-31 14:47:07 -0500932#if defined(ANGLE_PLATFORM_ANDROID)
933 if (getFeatures().supportsAndroidHardwareBuffer)
934 {
935 enabledDeviceExtensions.push_back(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
936 enabledDeviceExtensions.push_back(
937 VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
938 InitExternalMemoryHardwareBufferANDROIDFunctions(mInstance);
939 }
940#else
941 ASSERT(!getFeatures().supportsAndroidHardwareBuffer);
942#endif
943
Frank Henigman52047de2018-11-13 17:22:36 -0500944 std::sort(enabledDeviceExtensions.begin(), enabledDeviceExtensions.end(), StrLess);
945 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionNames, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500946
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400947 // Select additional features to be enabled
Frank Henigman52047de2018-11-13 17:22:36 -0500948 VkPhysicalDeviceFeatures2KHR enabledFeatures = {};
949 enabledFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
950 enabledFeatures.features.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
951 enabledFeatures.features.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi962c2222019-02-20 15:43:41 -0500952 enabledFeatures.features.samplerAnisotropy = mPhysicalDeviceFeatures.samplerAnisotropy;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400953
Frank Henigman52047de2018-11-13 17:22:36 -0500954 VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT divisorFeatures = {};
955 divisorFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT;
956 divisorFeatures.vertexAttributeInstanceRateDivisor = true;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500957
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500958 float zeroPriority = 0.0f;
Frank Henigman52047de2018-11-13 17:22:36 -0500959 VkDeviceQueueCreateInfo queueCreateInfo = {};
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500960 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
961 queueCreateInfo.flags = 0;
962 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
963 queueCreateInfo.queueCount = 1;
964 queueCreateInfo.pQueuePriorities = &zeroPriority;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500965
966 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400967 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500968
Shahbaz Youssefi76bd8482019-02-13 13:00:44 -0500969 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
970 createInfo.flags = 0;
971 createInfo.queueCreateInfoCount = 1;
972 createInfo.pQueueCreateInfos = &queueCreateInfo;
973 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
974 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Frank Henigman52047de2018-11-13 17:22:36 -0500975
976 if (vkGetPhysicalDeviceProperties2KHR &&
977 ExtensionFound(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME, deviceExtensionNames))
978 {
979 enabledDeviceExtensions.push_back(VK_EXT_VERTEX_ATTRIBUTE_DIVISOR_EXTENSION_NAME);
980 enabledFeatures.pNext = &divisorFeatures;
981
982 VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT divisorProperties = {};
983 divisorProperties.sType =
984 VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_PROPERTIES_EXT;
985
986 VkPhysicalDeviceProperties2 deviceProperties = {};
987 deviceProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
988 deviceProperties.pNext = &divisorProperties;
989
990 vkGetPhysicalDeviceProperties2KHR(mPhysicalDevice, &deviceProperties);
991 mMaxVertexAttribDivisor = divisorProperties.maxVertexAttribDivisor;
992
993 createInfo.pNext = &enabledFeatures;
994 }
995 else
996 {
997 createInfo.pEnabledFeatures = &enabledFeatures.features;
998 }
999
Jamie Madill4d0bf552016-12-28 15:45:24 -05001000 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
1001 createInfo.ppEnabledExtensionNames =
1002 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -05001003
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001004 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001005
1006 mCurrentQueueFamilyIndex = queueFamilyIndex;
1007
1008 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
1009
1010 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001011 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001012 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1013 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
1014 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001015
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001016 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001017
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001018 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001019 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001020
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001021 // Initialize the submission semaphore pool.
1022 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
1023
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001024#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
1025 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1026 ASSERT(platform);
1027
1028 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
1029 // platform discovery.
1030 const unsigned char *gpuEventsEnabled =
1031 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
1032 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
1033#endif
1034
1035 if (mGpuEventsEnabled)
1036 {
1037 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
1038 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
1039 vk::kDefaultTimestampQueryPoolSize));
1040 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
1041 }
1042
Jamie Madill7c985f52018-11-29 18:16:17 -05001043 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001044}
1045
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001046angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -04001047 VkSurfaceKHR surface,
1048 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001049{
1050 // We've already initialized a device, and can't re-create it unless it's never been used.
1051 // TODO(jmadill): Handle the re-creation case if necessary.
1052 if (mDevice != VK_NULL_HANDLE)
1053 {
1054 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
1055
1056 // Check if the current device supports present on this surface.
1057 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001058 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -04001059 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -05001060 surface, &supportsPresent));
1061
Jamie Madill6cad7732018-07-11 09:01:17 -04001062 if (supportsPresent == VK_TRUE)
1063 {
1064 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -05001065 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -04001066 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001067 }
1068
1069 // Find a graphics and present queue.
1070 Optional<uint32_t> newPresentQueue;
1071 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001072 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001073 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
1074 {
1075 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001076 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001077 {
1078 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001079 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
1080 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001081
1082 if (supportsPresent == VK_TRUE)
1083 {
1084 newPresentQueue = queueIndex;
1085 break;
1086 }
1087 }
1088 }
1089
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001090 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1091 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001092
Jamie Madill6cad7732018-07-11 09:01:17 -04001093 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001094 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001095}
1096
1097std::string RendererVk::getVendorString() const
1098{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001099 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001100}
1101
Jamie Madille09bd5d2016-11-29 16:20:35 -05001102std::string RendererVk::getRendererDescription() const
1103{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001104 std::stringstream strstr;
1105
1106 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1107
1108 strstr << "Vulkan ";
1109 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1110 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1111 strstr << VK_VERSION_PATCH(apiVersion);
1112
Olli Etuahoc6a06182018-04-13 14:11:46 +03001113 strstr << "(";
1114
1115 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1116 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1117 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1118 // driver detection.
1119 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1120 {
1121 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1122 }
1123
Geoff Langa7af56b2018-12-14 14:20:28 -05001124 strstr << mPhysicalDeviceProperties.deviceName;
1125 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1126
1127 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001128
1129 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001130}
1131
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001132gl::Version RendererVk::getMaxSupportedESVersion() const
1133{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001134 // Current highest supported version
Shahbaz Youssefi9dc8eaf2019-02-11 11:04:54 -05001135 gl::Version maxVersion = gl::Version(3, 0);
1136
1137#if ANGLE_VULKAN_CONFORMANT_CONFIGS_ONLY
1138 // TODO: Disallow ES 3.0 until supported. http://crbug.com/angleproject/2950
1139 maxVersion = gl::Version(2, 0);
1140#endif
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001141
Geoff Lang0c2c9232019-01-14 16:01:38 -05001142 // Vulkan inherited queries are required to support any GL query type
1143 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001144 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001145 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001146 }
1147
Geoff Lang0c2c9232019-01-14 16:01:38 -05001148 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001149}
1150
Frank Henigman52047de2018-11-13 17:22:36 -05001151void RendererVk::initFeatures(const ExtensionNameList &deviceExtensionNames)
Jamie Madill12222072018-07-11 14:59:48 -04001152{
Jamie Madillb36a4812018-09-25 10:15:11 -04001153// Use OpenGL line rasterization rules by default.
1154// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1155#if defined(ANGLE_PLATFORM_ANDROID)
1156 mFeatures.basicGLLineRasterization = false;
1157#else
Jamie Madill12222072018-07-11 14:59:48 -04001158 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001159#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001160
Ian Elliott52f5da42018-12-21 09:02:09 -07001161 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
Frank Henigman52047de2018-11-13 17:22:36 -05001162 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionNames))
Ian Elliottd50521f2018-12-20 12:05:14 -07001163 {
1164 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1165 // investigation. http://anglebug.com/2728
1166 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1167 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001168
1169#ifdef ANGLE_PLATFORM_WINDOWS
1170 // http://anglebug.com/2838
1171 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001172
1173 // http://anglebug.com/3055
1174 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001175#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001176
1177 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1178 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001179
1180 // Work around incorrect NVIDIA point size range clamping.
1181 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1182 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1183 {
1184 mFeatures.clampPointSize = true;
1185 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001186
Jamie Madillfa7ca182019-01-15 11:20:58 -05001187 // We also need to clamp point size on several Android drivers.
1188 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1189 if (IsAndroid())
1190 {
1191 mFeatures.clampPointSize = true;
1192 }
1193
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001194#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001195 // Work around ineffective compute-graphics barriers on Nexus 5X.
1196 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1197 // http://anglebug.com/3019
1198 mFeatures.flushAfterVertexConversion =
1199 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001200#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001201
Frank Henigman52047de2018-11-13 17:22:36 -05001202 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionNames))
Ian Elliottbcb78902018-12-19 11:46:29 -07001203 {
1204 mFeatures.supportsIncrementalPresent = true;
1205 }
Geoff Lang009696c2019-01-31 14:47:07 -05001206
1207#if defined(ANGLE_PLATFORM_ANDROID)
Yuly Novikovdbbdf562019-02-27 19:48:16 -05001208 mFeatures.supportsAndroidHardwareBuffer =
1209 ExtensionFound(VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME,
1210 deviceExtensionNames) &&
1211 ExtensionFound(VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME, deviceExtensionNames);
Geoff Lang009696c2019-01-31 14:47:07 -05001212#endif
Yuly Novikov1581ff02019-02-28 20:59:26 -05001213
1214 if (IsLinux() && IsIntel(mPhysicalDeviceProperties.vendorID))
1215 {
1216 mFeatures.disableFifoPresentMode = true;
1217 }
Jamie Madill12222072018-07-11 14:59:48 -04001218}
1219
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001220void RendererVk::initPipelineCacheVkKey()
1221{
1222 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1223 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1224 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1225 // there is no '\0' in the result.
1226 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1227 {
1228 hashStream << std::hex << c;
1229 }
1230 // Add the vendor and device id too for good measure.
1231 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1232 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1233
1234 const std::string &hashString = hashStream.str();
1235 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1236 hashString.length(), mPipelineCacheVkBlobKey.data());
1237}
1238
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001239angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001240{
1241 initPipelineCacheVkKey();
1242
1243 egl::BlobCache::Value initialData;
1244 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1245 mPipelineCacheVkBlobKey, &initialData);
1246
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001247 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001248
1249 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001250 pipelineCacheCreateInfo.flags = 0;
1251 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1252 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1253
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001254 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001255 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001256}
1257
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001258void RendererVk::getSubmitWaitSemaphores(
1259 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001260 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1261 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001262{
1263 if (mSubmitLastSignaledSemaphore.getSemaphore())
1264 {
1265 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001266 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001267
1268 // Return the semaphore to the pool (which will remain valid and unused until the
1269 // queue it's about to be waited on has finished execution).
1270 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1271 }
1272
1273 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1274 {
1275 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001276 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1277
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001278 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1279 }
1280 mSubmitWaitSemaphores.clear();
1281}
1282
Jamie Madillacccc6c2016-05-03 17:22:10 -04001283const gl::Caps &RendererVk::getNativeCaps() const
1284{
1285 ensureCapsInitialized();
1286 return mNativeCaps;
1287}
1288
1289const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1290{
1291 ensureCapsInitialized();
1292 return mNativeTextureCaps;
1293}
1294
1295const gl::Extensions &RendererVk::getNativeExtensions() const
1296{
1297 ensureCapsInitialized();
1298 return mNativeExtensions;
1299}
1300
1301const gl::Limitations &RendererVk::getNativeLimitations() const
1302{
1303 ensureCapsInitialized();
1304 return mNativeLimitations;
1305}
1306
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001307uint32_t RendererVk::getMaxActiveTextures()
1308{
1309 // TODO(lucferron): expose this limitation to GL in Context Caps
1310 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1311 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1312}
1313
Jamie Madill49ac74b2017-12-21 14:42:33 -05001314const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001315{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001316 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001317}
1318
Jamie Madill21061022018-07-12 23:56:30 -04001319angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001320{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001321 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001322 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001323 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1324
Luc Ferron1617e692018-07-11 11:08:19 -04001325 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1326 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001327
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001328 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001329 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1330 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001331
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001332 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001333 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001334 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1335 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001336 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001337 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001338 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001339 submitInfo.signalSemaphoreCount = 0;
1340 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001341
Jamie Madill21061022018-07-12 23:56:30 -04001342 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001343 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001344
Jamie Madill4c26fc22017-02-24 11:04:10 -05001345 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001346 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001347 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001348
1349 if (mGpuEventsEnabled)
1350 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001351 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001352 while (mInFlightGpuEventQueries.size() > 0)
1353 {
1354 ANGLE_TRY(checkCompletedGpuEvents(context));
1355 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001356 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1357 // synchronization if there is no event to be adjusted (happens when finish() gets called
1358 // multiple times towards the end of the application).
1359 if (mGpuEvents.size() > 0)
1360 {
1361 ANGLE_TRY(synchronizeCpuGpuTime(context));
1362 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001363 }
1364
Jamie Madill7c985f52018-11-29 18:16:17 -05001365 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001366}
1367
Jamie Madill0c0dc342017-03-24 14:18:51 -04001368void RendererVk::freeAllInFlightResources()
1369{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001370 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001371 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001372 // On device loss we need to wait for fence to be signaled before destroying it
1373 if (mDeviceLost)
1374 {
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001375 VkResult status = batch.fence.get().wait(mDevice, kMaxFenceWaitTimeNs);
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001376 // If wait times out, it is probably not possible to recover from lost device
1377 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1378 }
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001379 batch.commandPool.destroy(mDevice);
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001380 batch.fence.reset(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001381 }
1382 mInFlightCommands.clear();
1383
1384 for (auto &garbage : mGarbage)
1385 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001386 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001387 }
1388 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001389
1390 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001391}
1392
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001393angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001394{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001395 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001396
Jamie Madill49ac74b2017-12-21 14:42:33 -05001397 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001398 {
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001399 VkResult result = batch.fence.get().getStatus(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001400 if (result == VK_NOT_READY)
1401 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001402 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001403 }
1404 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001405
Jamie Madill49ac74b2017-12-21 14:42:33 -05001406 ASSERT(batch.serial > mLastCompletedQueueSerial);
1407 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001408
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001409 batch.fence.reset(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001410 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001411 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001412 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001413 }
1414
Jamie Madill49ac74b2017-12-21 14:42:33 -05001415 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001416
1417 size_t freeIndex = 0;
1418 for (; freeIndex < mGarbage.size(); ++freeIndex)
1419 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001420 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001421 break;
1422 }
1423
1424 // Remove the entries from the garbage list - they should be ready to go.
1425 if (freeIndex > 0)
1426 {
1427 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001428 }
1429
Jamie Madill7c985f52018-11-29 18:16:17 -05001430 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001431}
1432
Jamie Madill21061022018-07-12 23:56:30 -04001433angle::Result RendererVk::submitFrame(vk::Context *context,
1434 const VkSubmitInfo &submitInfo,
1435 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001436{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001437 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Jamie Madill49ac74b2017-12-21 14:42:33 -05001438
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001439 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001440 CommandBatch &batch = scopedBatch.get();
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001441 ANGLE_TRY(getSubmitFence(context, &batch.fence));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001442
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001443 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.get().getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001444
1445 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001446 batch.commandPool = std::move(mCommandPool);
1447 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001448
Jamie Madillbea35a62018-07-05 11:54:10 -04001449 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001450
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001451 // Make sure a new fence is created for the next submission.
1452 mSubmitFence.reset(mDevice);
1453
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001454 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1455 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001456 // so the limit is larger than the expected number of images.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001457 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001458
Jamie Madill85ca1892019-01-16 13:27:15 -05001459 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001460
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001461 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001462
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001463 if (mGpuEventsEnabled)
1464 {
1465 ANGLE_TRY(checkCompletedGpuEvents(context));
1466 }
1467
Jamie Madill49ac74b2017-12-21 14:42:33 -05001468 // Simply null out the command buffer here - it was allocated using the command pool.
1469 commandBuffer.releaseHandle();
1470
1471 // Reallocate the command pool for next frame.
1472 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001473 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001474 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001475 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001476 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001477
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001478 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001479 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001480}
1481
Jamie Madill85ca1892019-01-16 13:27:15 -05001482void RendererVk::nextSerial()
1483{
1484 // Increment the queue serial. If this fails, we should restart ANGLE.
1485 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1486 mCurrentQueueSerial = mQueueSerialFactory.generate();
1487
1488 // Notify the Contexts that they should be starting new command buffers.
1489 // We use one command pool per serial/submit associated with this VkQueue. We can also
1490 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1491 // check for a new serial when starting a new command buffer. We just check that the current
1492 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1493 // using this VkQueue that they their current command buffer is no longer valid.
1494 for (gl::Context *context : mDisplay->getContextSet())
1495 {
1496 ContextVk *contextVk = vk::GetImpl(context);
1497 contextVk->onCommandBufferFinished();
1498 }
1499}
1500
Jamie Madillaaca96e2018-06-12 10:19:48 -04001501bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001502{
1503 return serial > mLastCompletedQueueSerial;
1504}
1505
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001506angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1507{
1508 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1509 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001510 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001511 }
1512
1513 // Find the first batch with serial equal to or bigger than given serial (note that
1514 // the batch serials are unique, otherwise upper-bound would have been necessary).
1515 size_t batchIndex = mInFlightCommands.size() - 1;
1516 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1517 {
1518 if (mInFlightCommands[i].serial >= serial)
1519 {
1520 batchIndex = i;
1521 break;
1522 }
1523 }
1524 const CommandBatch &batch = mInFlightCommands[batchIndex];
1525
1526 // Wait for it finish
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001527 VkResult status = batch.fence.get().wait(mDevice, kMaxFenceWaitTimeNs);
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001528
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001529 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001530 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001531
1532 // Clean up finished batches.
1533 return checkCompletedCommands(context);
1534}
1535
Jamie Madill21061022018-07-12 23:56:30 -04001536angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1537 const vk::RenderPassDesc &desc,
1538 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001539{
Jamie Madill21061022018-07-12 23:56:30 -04001540 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001541 renderPassOut);
1542}
1543
Jamie Madill21061022018-07-12 23:56:30 -04001544angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1545 const vk::RenderPassDesc &desc,
1546 const vk::AttachmentOpsArray &ops,
1547 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001548{
Jamie Madill21061022018-07-12 23:56:30 -04001549 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001550 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001551}
1552
Jamie Madilla5e06072018-05-18 14:36:05 -04001553vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001554{
Jamie Madilla5e06072018-05-18 14:36:05 -04001555 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001556}
1557
Jamie Madill21061022018-07-12 23:56:30 -04001558angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001559{
Jamie Madill21061022018-07-12 23:56:30 -04001560 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001561 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001562}
1563
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001564angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001565{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001566 if (mCommandGraph.empty())
1567 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001568 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001569 }
1570
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001571 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1572
Jamie Madillbea35a62018-07-05 11:54:10 -04001573 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1574 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001575
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001576 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001577 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1578 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001579
1580 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1581 // will be waited on.
1582 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001583
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001584 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001585 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001586 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1587 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001588 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001589 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001590 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001591 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001592 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001593
Jamie Madill21061022018-07-12 23:56:30 -04001594 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001595
Jamie Madill7c985f52018-11-29 18:16:17 -05001596 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001597}
1598
Jamie Madill78feddc2018-04-27 11:45:05 -04001599Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001600{
Jamie Madill78feddc2018-04-27 11:45:05 -04001601 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001602}
1603
Jamie Madill21061022018-07-12 23:56:30 -04001604angle::Result RendererVk::getDescriptorSetLayout(
1605 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001606 const vk::DescriptorSetLayoutDesc &desc,
1607 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1608{
Jamie Madill21061022018-07-12 23:56:30 -04001609 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001610}
1611
Jamie Madill21061022018-07-12 23:56:30 -04001612angle::Result RendererVk::getPipelineLayout(
1613 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001614 const vk::PipelineLayoutDesc &desc,
1615 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1616 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1617{
Jamie Madill21061022018-07-12 23:56:30 -04001618 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001619 pipelineLayoutOut);
1620}
1621
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001622angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1623{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001624 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001625
1626 if (--mPipelineCacheVkUpdateTimeout > 0)
1627 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001628 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001629 }
1630
1631 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1632
1633 // Get the size of the cache.
1634 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001635 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001636 if (result != VK_INCOMPLETE)
1637 {
1638 ANGLE_VK_TRY(displayVk, result);
1639 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001640
1641 angle::MemoryBuffer *pipelineCacheData = nullptr;
1642 ANGLE_VK_CHECK_ALLOC(displayVk,
1643 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1644
1645 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001646 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001647 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1648 // was determined just above), so receiving it hints at an implementation bug we would want
1649 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001650 ASSERT(result != VK_INCOMPLETE);
1651 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001652
1653 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1654 // the buffer to avoid leaking garbage memory.
1655 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1656 if (pipelineCacheSize < originalPipelineCacheSize)
1657 {
1658 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1659 originalPipelineCacheSize - pipelineCacheSize);
1660 }
1661
1662 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1663
Jamie Madill7c985f52018-11-29 18:16:17 -05001664 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001665}
1666
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001667angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1668 const vk::Semaphore **outSemaphore)
1669{
1670 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1671
1672 vk::SemaphoreHelper semaphore;
1673 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1674
1675 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1676 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1677
Jamie Madill7c985f52018-11-29 18:16:17 -05001678 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001679}
1680
1681const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1682{
1683 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1684
1685 // Return the semaphore to the pool (which will remain valid and unused until the
1686 // queue it's about to be waited on has finished execution). The caller is about
1687 // to wait on it.
1688 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1689
1690 return semaphore;
1691}
1692
Shahbaz Youssefi20ae6812019-02-27 17:11:58 -05001693angle::Result RendererVk::getSubmitFence(vk::Context *context,
1694 vk::Shared<vk::Fence> *sharedFenceOut)
1695{
1696 if (!mSubmitFence.isReferenced())
1697 {
1698 vk::Fence fence;
1699
1700 VkFenceCreateInfo fenceCreateInfo = {};
1701 fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1702 fenceCreateInfo.flags = 0;
1703
1704 ANGLE_VK_TRY(context, fence.init(mDevice, fenceCreateInfo));
1705
1706 mSubmitFence.assign(mDevice, std::move(fence));
1707 }
1708
1709 sharedFenceOut->copy(mDevice, mSubmitFence);
1710 return angle::Result::Continue;
1711}
1712
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001713angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1714{
1715 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1716 // that seems impossible, so instead, we are going to make a small submission with just a
1717 // timestamp query. First, the disjoint timer query extension says:
1718 //
1719 // > This will return the GL time after all previous commands have reached the GL server but
1720 // have not yet necessarily executed.
1721 //
1722 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1723 // The wording allows us to make a submission to get the timestamp without performing a flush.
1724 //
1725 // Second:
1726 //
1727 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1728 // object target, applications can measure the latency between when commands reach the GL server
1729 // and when they are realized in the framebuffer.
1730 //
1731 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1732 // GPU bubble. This function directly generates a command buffer and submits it instead of
1733 // using the other member functions. This is to avoid changing any state, such as the queue
1734 // serial.
1735
1736 // Create a query used to receive the GPU timestamp
1737 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1738 vk::QueryHelper timestampQuery;
1739 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1740 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1741
1742 // Record the command buffer
1743 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1744 vk::CommandBuffer &commandBuffer = commandBatch.get();
1745
1746 VkCommandBufferAllocateInfo commandBufferInfo = {};
1747 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1748 commandBufferInfo.commandPool = mCommandPool.getHandle();
1749 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1750 commandBufferInfo.commandBufferCount = 1;
1751
Yuly Novikov27780292018-11-09 11:19:49 -05001752 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001753
1754 VkCommandBufferBeginInfo beginInfo = {};
1755 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1756 beginInfo.flags = 0;
1757 beginInfo.pInheritanceInfo = nullptr;
1758
Yuly Novikov27780292018-11-09 11:19:49 -05001759 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001760
1761 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1762 timestampQuery.getQuery(), 1);
1763 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1764 timestampQuery.getQueryPool()->getHandle(),
1765 timestampQuery.getQuery());
1766
Yuly Novikov27780292018-11-09 11:19:49 -05001767 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001768
1769 // Create fence for the submission
1770 VkFenceCreateInfo fenceInfo = {};
1771 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1772 fenceInfo.flags = 0;
1773
1774 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001775 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001776
1777 // Submit the command buffer
1778 VkSubmitInfo submitInfo = {};
1779 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1780 submitInfo.waitSemaphoreCount = 0;
1781 submitInfo.pWaitSemaphores = nullptr;
1782 submitInfo.pWaitDstStageMask = nullptr;
1783 submitInfo.commandBufferCount = 1;
1784 submitInfo.pCommandBuffers = commandBuffer.ptr();
1785 submitInfo.signalSemaphoreCount = 0;
1786 submitInfo.pSignalSemaphores = nullptr;
1787
1788 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1789
1790 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1791 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001792 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001793
1794 // Get the query results
1795 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1796
Yuly Novikov27780292018-11-09 11:19:49 -05001797 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1798 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1799 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001800
1801 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1802
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001803 // Convert results to nanoseconds.
1804 *timestampOut = static_cast<uint64_t>(
1805 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1806
Jamie Madill7c985f52018-11-29 18:16:17 -05001807 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001808}
1809
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001810// These functions look at the mandatory format for support, and fallback to querying the device (if
1811// necessary) to test the availability of the bits.
1812bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1813 const VkFormatFeatureFlags featureBits)
1814{
1815 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1816}
1817
1818bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1819 const VkFormatFeatureFlags featureBits)
1820{
1821 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1822}
1823
1824bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1825{
1826 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1827}
1828
Shahbaz Youssefi4d153382019-02-26 15:08:11 +00001829void RendererVk::insertDebugMarker(GLenum source, GLuint id, std::string &&marker)
1830{
1831 mCommandGraph.insertDebugMarker(source, std::move(marker));
1832}
1833
1834void RendererVk::pushDebugMarker(GLenum source, GLuint id, std::string &&marker)
1835{
1836 mCommandGraph.pushDebugMarker(source, std::move(marker));
1837}
1838
1839void RendererVk::popDebugMarker()
1840{
1841 mCommandGraph.popDebugMarker();
1842}
1843
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001844angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1845{
1846 ASSERT(mGpuEventsEnabled);
1847
1848 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1849 ASSERT(platform);
1850
1851 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1852 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1853 //
1854 // CPU GPU
1855 //
1856 // Record command buffer
1857 // with timestamp query
1858 //
1859 // Submit command buffer
1860 //
1861 // Post-submission work Begin execution
1862 //
Tobin Ehlis5546fb42019-01-17 12:25:54 -05001863 // ???? Write timestamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001864 //
1865 // ???? End execution
1866 //
1867 // ???? Return query results
1868 //
1869 // ????
1870 //
1871 // Get query results
1872 //
1873 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1874 // finished post-submission work while the GPU is executing in parallel. With no further work,
1875 // querying CPU timestamps before submission and after getting query results give the bounds to
1876 // Tgpu, which could be quite large.
1877 //
1878 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1879 // reduce this range. This function implements the following procedure:
1880 //
1881 // CPU GPU
1882 //
1883 // Record command buffer
1884 // with timestamp query
1885 //
1886 // Submit command buffer
1887 //
1888 // Post-submission work Begin execution
1889 //
1890 // ???? Set Event GPUReady
1891 //
1892 // Wait on Event GPUReady Wait on Event CPUReady
1893 //
1894 // Get CPU Time Ts Wait on Event CPUReady
1895 //
1896 // Set Event CPUReady Wait on Event CPUReady
1897 //
1898 // Get CPU Time Tcpu Get GPU Time Tgpu
1899 //
1900 // Wait on Event GPUDone Set Event GPUDone
1901 //
1902 // Get CPU Time Te End Execution
1903 //
1904 // Idle Return query results
1905 //
1906 // Get query results
1907 //
1908 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1909 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1910 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1911 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1912 // calibration.
1913 //
1914 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1915
1916 // Make sure nothing is running
1917 ASSERT(mCommandGraph.empty());
1918
1919 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1920
1921 // Create a query used to receive the GPU timestamp
1922 vk::QueryHelper timestampQuery;
1923 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1924
1925 // Create the three events
1926 VkEventCreateInfo eventCreateInfo = {};
1927 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1928 eventCreateInfo.flags = 0;
1929
1930 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001931 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1932 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1933 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001934
1935 constexpr uint32_t kRetries = 10;
1936
1937 // Time suffixes used are S for seconds and Cycles for cycles
1938 double tightestRangeS = 1e6f;
1939 double TcpuS = 0;
1940 uint64_t TgpuCycles = 0;
1941 for (uint32_t i = 0; i < kRetries; ++i)
1942 {
1943 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001944 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1945 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1946 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001947
1948 // Record the command buffer
1949 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1950 vk::CommandBuffer &commandBuffer = commandBatch.get();
1951
1952 VkCommandBufferAllocateInfo commandBufferInfo = {};
1953 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1954 commandBufferInfo.commandPool = mCommandPool.getHandle();
1955 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1956 commandBufferInfo.commandBufferCount = 1;
1957
Yuly Novikov27780292018-11-09 11:19:49 -05001958 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001959
1960 VkCommandBufferBeginInfo beginInfo = {};
1961 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1962 beginInfo.flags = 0;
1963 beginInfo.pInheritanceInfo = nullptr;
1964
Yuly Novikov27780292018-11-09 11:19:49 -05001965 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001966
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001967 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001968 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1969 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1970 nullptr);
1971
1972 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1973 timestampQuery.getQuery(), 1);
1974 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1975 timestampQuery.getQueryPool()->getHandle(),
1976 timestampQuery.getQuery());
1977
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001978 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001979
Yuly Novikov27780292018-11-09 11:19:49 -05001980 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001981
1982 // Submit the command buffer
1983 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1984 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1985 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1986
1987 VkSubmitInfo submitInfo = {};
1988 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1989 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1990 submitInfo.pWaitSemaphores = waitSemaphores.data();
1991 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1992 submitInfo.commandBufferCount = 1;
1993 submitInfo.pCommandBuffers = commandBuffer.ptr();
1994 submitInfo.signalSemaphoreCount = 0;
1995 submitInfo.pSignalSemaphores = nullptr;
1996
1997 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1998
1999 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05002000 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002001 do
2002 {
Yuly Novikov27780292018-11-09 11:19:49 -05002003 result = gpuReady.get().getStatus(mDevice);
2004 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
2005 {
2006 ANGLE_VK_TRY(context, result);
2007 }
2008 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002009
2010 double TsS = platform->monotonicallyIncreasingTime(platform);
2011
2012 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05002013 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002014 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
2015
2016 // Wait for GPU to be done. Another short busy wait.
2017 do
2018 {
Yuly Novikov27780292018-11-09 11:19:49 -05002019 result = gpuDone.get().getStatus(mDevice);
2020 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
2021 {
2022 ANGLE_VK_TRY(context, result);
2023 }
2024 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002025
2026 double TeS = platform->monotonicallyIncreasingTime(platform);
2027
2028 // Get the query results
2029 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
2030
2031 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
2032
2033 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002034 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
2035 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
2036 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002037
2038 // Use the first timestamp queried as origin.
2039 if (mGpuEventTimestampOrigin == 0)
2040 {
2041 mGpuEventTimestampOrigin = gpuTimestampCycles;
2042 }
2043
2044 // Take these CPU and GPU timestamps if there is better confidence.
2045 double confidenceRangeS = TeS - TsS;
2046 if (confidenceRangeS < tightestRangeS)
2047 {
2048 tightestRangeS = confidenceRangeS;
2049 TcpuS = cpuTimestampS;
2050 TgpuCycles = gpuTimestampCycles;
2051 }
2052 }
2053
2054 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
2055
2056 // timestampPeriod gives nanoseconds/cycle.
2057 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
2058 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
2059 1'000'000'000.0;
2060
2061 flushGpuEvents(TgpuS, TcpuS);
2062
2063 mGpuClockSync.gpuTimestampS = TgpuS;
2064 mGpuClockSync.cpuTimestampS = TcpuS;
2065
Jamie Madill7c985f52018-11-29 18:16:17 -05002066 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002067}
2068
2069angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
2070 vk::CommandBuffer *commandBuffer,
2071 char phase,
2072 const char *name)
2073{
2074 ASSERT(mGpuEventsEnabled);
2075
2076 GpuEventQuery event;
2077
2078 event.name = name;
2079 event.phase = phase;
2080 event.serial = mCurrentQueueSerial;
2081
2082 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
2083
2084 commandBuffer->resetQueryPool(
2085 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
2086 commandBuffer->writeTimestamp(
2087 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2088 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
2089
2090 mInFlightGpuEventQueries.push_back(std::move(event));
2091
Jamie Madill7c985f52018-11-29 18:16:17 -05002092 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002093}
2094
2095angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
2096{
2097 ASSERT(mGpuEventsEnabled);
2098
2099 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2100 ASSERT(platform);
2101
2102 int finishedCount = 0;
2103
2104 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2105 {
2106 // Only check the timestamp query if the submission has finished.
2107 if (eventQuery.serial > mLastCompletedQueueSerial)
2108 {
2109 break;
2110 }
2111
2112 // See if the results are available.
2113 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002114 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2115 ->getResults(mDevice, eventQuery.queryIndex, 1,
2116 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2117 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2118 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002119 {
2120 break;
2121 }
Yuly Novikov27780292018-11-09 11:19:49 -05002122 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002123
2124 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2125
2126 GpuEvent event;
2127 event.gpuTimestampCycles = gpuTimestampCycles;
2128 event.name = eventQuery.name;
2129 event.phase = eventQuery.phase;
2130
2131 mGpuEvents.emplace_back(event);
2132
2133 ++finishedCount;
2134 }
2135
2136 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2137 mInFlightGpuEventQueries.begin() + finishedCount);
2138
Jamie Madill7c985f52018-11-29 18:16:17 -05002139 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002140}
2141
2142void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2143{
2144 if (mGpuEvents.size() == 0)
2145 {
2146 return;
2147 }
2148
2149 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2150 ASSERT(platform);
2151
2152 // Find the slope of the clock drift for adjustment
2153 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2154 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2155 double gpuSyncDriftSlope = 0;
2156
2157 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2158 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2159
2160 // No gpu trace events should have been generated before the clock sync, so if there is no
2161 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2162 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2163 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2164
2165 gpuSyncDriftSlope =
2166 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2167
2168 for (const GpuEvent &event : mGpuEvents)
2169 {
2170 double gpuTimestampS =
2171 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2172 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2173
2174 // Account for clock drift.
2175 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2176
2177 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2178 // for.
2179 static long long eventId = 1;
2180 static const unsigned char *categoryEnabled =
2181 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2182 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2183 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2184 }
2185
2186 mGpuEvents.clear();
2187}
2188
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002189template <VkFormatFeatureFlags VkFormatProperties::*features>
2190bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2191{
2192 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2193 VkFormatProperties &deviceProperties = mFormatProperties[format];
2194
2195 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2196 {
2197 // If we don't have the actual device features, see if the requested features are mandatory.
2198 // If so, there's no need to query the device.
2199 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2200 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2201 {
2202 return true;
2203 }
2204
2205 // Otherwise query the format features and cache it.
2206 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2207 }
2208
2209 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2210}
2211
Jamie Madillaaca96e2018-06-12 10:19:48 -04002212uint32_t GetUniformBufferDescriptorCount()
2213{
2214 return kUniformBufferDescriptorsPerDescriptorSet;
2215}
2216
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002217} // namespace rx