blob: 6b85a821bc42f685296296a10c34e4b73e157875 [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
Shahbaz Youssefi341304d2019-02-12 20:58:54 +000077VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
78 const std::vector<const char *> &enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050079{
Shahbaz Youssefi341304d2019-02-12 20:58:54 +000080 // Compile the extensions names into a set.
81 std::set<std::string> extensionNames;
82 for (const auto &extensionProp : extensionProps)
83 {
84 extensionNames.insert(extensionProp.extensionName);
85 }
86
87 for (const char *extensionName : enabledExtensionNames)
88 {
89 if (extensionNames.count(extensionName) == 0)
90 {
91 return VK_ERROR_EXTENSION_NOT_PRESENT;
92 }
93 }
94
95 return VK_SUCCESS;
Jamie Madille09bd5d2016-11-29 16:20:35 -050096}
97
Shahbaz Youssefi341304d2019-02-12 20:58:54 +000098bool ExtensionFound(const char *extensionName,
99 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600100{
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000101 for (const auto &extensionProp : extensionProps)
102 {
103 if (strcmp(extensionProp.extensionName, extensionName) == 0)
104 {
105 return true;
106 }
107 }
108 return false;
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600109}
110
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500111// Array of Validation error/warning messages that will be ignored, should include bugID
Jamie Madill00f43c92019-02-09 11:41:12 -0500112constexpr const char *kSkippedMessages[] = {
113 // http://anglebug.com/2866
114 "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500115 // http://anglebug.com/2796
Jamie Madill00f43c92019-02-09 11:41:12 -0500116 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing",
117};
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500118
119// Suppress validation errors that are known
120// return "true" if given code/prefix/message is known, else return "false"
121bool IsIgnoredDebugMessage(const char *message)
122{
Michael Spang25839802019-01-30 18:02:51 -0500123 if (!message)
124 {
125 return false;
126 }
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500127 for (const char *msg : kSkippedMessages)
128 {
129 if (strstr(message, msg) != nullptr)
130 {
131 return true;
132 }
133 }
134 return false;
135}
136
137const char *GetVkObjectTypeName(VkObjectType type)
138{
139 switch (type)
140 {
141 case VK_OBJECT_TYPE_UNKNOWN:
142 return "Unknown";
143 case VK_OBJECT_TYPE_INSTANCE:
144 return "Instance";
145 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
146 return "Physical Device";
147 case VK_OBJECT_TYPE_DEVICE:
148 return "Device";
149 case VK_OBJECT_TYPE_QUEUE:
150 return "Queue";
151 case VK_OBJECT_TYPE_SEMAPHORE:
152 return "Semaphore";
153 case VK_OBJECT_TYPE_COMMAND_BUFFER:
154 return "Command Buffer";
155 case VK_OBJECT_TYPE_FENCE:
156 return "Fence";
157 case VK_OBJECT_TYPE_DEVICE_MEMORY:
158 return "Device Memory";
159 case VK_OBJECT_TYPE_BUFFER:
160 return "Buffer";
161 case VK_OBJECT_TYPE_IMAGE:
162 return "Image";
163 case VK_OBJECT_TYPE_EVENT:
164 return "Event";
165 case VK_OBJECT_TYPE_QUERY_POOL:
166 return "Query Pool";
167 case VK_OBJECT_TYPE_BUFFER_VIEW:
168 return "Buffer View";
169 case VK_OBJECT_TYPE_IMAGE_VIEW:
170 return "Image View";
171 case VK_OBJECT_TYPE_SHADER_MODULE:
172 return "Shader Module";
173 case VK_OBJECT_TYPE_PIPELINE_CACHE:
174 return "Pipeline Cache";
175 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
176 return "Pipeline Layout";
177 case VK_OBJECT_TYPE_RENDER_PASS:
178 return "Render Pass";
179 case VK_OBJECT_TYPE_PIPELINE:
180 return "Pipeline";
181 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
182 return "Descriptor Set Layout";
183 case VK_OBJECT_TYPE_SAMPLER:
184 return "Sampler";
185 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
186 return "Descriptor Pool";
187 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
188 return "Descriptor Set";
189 case VK_OBJECT_TYPE_FRAMEBUFFER:
190 return "Framebuffer";
191 case VK_OBJECT_TYPE_COMMAND_POOL:
192 return "Command Pool";
193 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
194 return "Sampler YCbCr Conversion";
195 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
196 return "Descriptor Update Template";
197 case VK_OBJECT_TYPE_SURFACE_KHR:
198 return "Surface";
199 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
200 return "Swapchain";
201 case VK_OBJECT_TYPE_DISPLAY_KHR:
202 return "Display";
203 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
204 return "Display Mode";
205 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
206 return "Debug Report Callback";
207 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
208 return "Object Table";
209 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
210 return "Indirect Commands Layout";
211 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
212 return "Debug Utils Messenger";
213 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
214 return "Validation Cache";
Shahbaz Youssefi38051222019-02-13 21:21:13 +0000215 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500216 return "Acceleration Structure";
217 default:
218 return "<Unrecognized>";
219 }
220}
221
222VKAPI_ATTR VkBool32 VKAPI_CALL
223DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
224 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
225 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
226 void *userData)
227{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500228 // See if it's an issue we are aware of and don't want to be spammed about.
229 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
230 {
231 return VK_FALSE;
232 }
233
234 std::ostringstream log;
Michael Spang25839802019-01-30 18:02:51 -0500235 if (callbackData->pMessageIdName)
236 {
237 log << "[ " << callbackData->pMessageIdName << " ] ";
238 }
239 log << callbackData->pMessage << std::endl;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500240
241 // Aesthetic value based on length of the function name, line number, etc.
242 constexpr size_t kStartIndent = 28;
243
244 // Output the debug marker hierarchy under which this error has occured.
245 size_t indent = kStartIndent;
246 if (callbackData->queueLabelCount > 0)
247 {
248 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
249 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
250 {
251 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
252 << std::endl;
253 }
254 }
255 if (callbackData->cmdBufLabelCount > 0)
256 {
257 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
258 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
259 {
260 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
261 << std::endl;
262 }
263 }
264 // Output the objects involved in this error message.
265 if (callbackData->objectCount > 0)
266 {
267 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
268 {
269 const char *objectName = callbackData->pObjects[i].pObjectName;
270 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
271 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
272 log << std::string(indent, ' ') << "Object: ";
273 if (objectHandle == 0)
274 {
275 log << "VK_NULL_HANDLE";
276 }
277 else
278 {
279 log << "0x" << std::hex << objectHandle << std::dec;
280 }
281 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
282 if (objectName)
283 {
284 log << " [" << objectName << "]";
285 }
286 log << std::endl;
287 }
288 }
289
Jamie Madill54ed8f02019-02-11 12:32:04 -0500290 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
291 std::string msg = log.str();
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500292
293 if (isError)
294 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500295 ERR() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500296 }
297 else
298 {
Jamie Madill54ed8f02019-02-11 12:32:04 -0500299 WARN() << msg;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500300 }
301
302 return VK_FALSE;
303}
304
Yuly Novikov199f4292018-01-19 19:04:05 -0500305VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
306 VkDebugReportObjectTypeEXT objectType,
307 uint64_t object,
308 size_t location,
309 int32_t messageCode,
310 const char *layerPrefix,
311 const char *message,
312 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500313{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600314 if (IsIgnoredDebugMessage(message))
315 {
316 return VK_FALSE;
317 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500318 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
319 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500320 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500321#if !defined(NDEBUG)
322 // Abort the call in Debug builds.
323 return VK_TRUE;
324#endif
325 }
326 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
327 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500328 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500329 }
330 else
331 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500332 // Uncomment this if you want Vulkan spam.
333 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500334 }
335
336 return VK_FALSE;
337}
338
Yuly Novikov199f4292018-01-19 19:04:05 -0500339// If we're loading the validation layers, we could be running from any random directory.
340// Change to the executable directory so we can find the layers, then change back to the
341// previous directory to be safe we don't disrupt the application.
342class ScopedVkLoaderEnvironment : angle::NonCopyable
343{
344 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600345 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
346 : mEnableValidationLayers(enableValidationLayers),
347 mEnableMockICD(enableMockICD),
348 mChangedCWD(false),
349 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500350 {
351// Changing CWD and setting environment variables makes no sense on Android,
352// since this code is a part of Java application there.
353// Android Vulkan loader doesn't need this either.
Michael Spang229fc832019-01-21 18:09:15 -0500354#if !defined(ANGLE_PLATFORM_ANDROID) && !defined(ANGLE_PLATFORM_FUCHSIA)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600355 if (enableMockICD)
356 {
357 // Override environment variable to use built Mock ICD
358 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
359 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
360 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
361 if (!mChangedICDPath)
362 {
363 ERR() << "Error setting Path for Mock/Null Driver.";
364 mEnableMockICD = false;
365 }
366 }
Jamie Madill46848422018-08-09 10:46:06 -0400367 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500368 {
369 const auto &cwd = angle::GetCWD();
370 if (!cwd.valid())
371 {
372 ERR() << "Error getting CWD for Vulkan layers init.";
373 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400374 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500375 }
376 else
377 {
378 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500379 std::string exeDir = angle::GetExecutableDirectory();
380 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500381 if (!mChangedCWD)
382 {
383 ERR() << "Error setting CWD for Vulkan layers init.";
384 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400385 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500386 }
387 }
388 }
389
390 // Override environment variable to use the ANGLE layers.
391 if (mEnableValidationLayers)
392 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700393 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500394 {
395 ERR() << "Error setting environment for Vulkan layers init.";
396 mEnableValidationLayers = false;
397 }
398 }
399#endif // !defined(ANGLE_PLATFORM_ANDROID)
400 }
401
402 ~ScopedVkLoaderEnvironment()
403 {
404 if (mChangedCWD)
405 {
406#if !defined(ANGLE_PLATFORM_ANDROID)
407 ASSERT(mPreviousCWD.valid());
408 angle::SetCWD(mPreviousCWD.value().c_str());
409#endif // !defined(ANGLE_PLATFORM_ANDROID)
410 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600411 if (mChangedICDPath)
412 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600413 if (mPreviousICDPath.value().empty())
414 {
415 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
416 }
417 else
418 {
419 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
420 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600421 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500422 }
423
Jamie Madillaaca96e2018-06-12 10:19:48 -0400424 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500425
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool canEnableMockICD() const { return mEnableMockICD; }
427
Yuly Novikov199f4292018-01-19 19:04:05 -0500428 private:
429 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600430 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500431 bool mChangedCWD;
432 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600433 bool mChangedICDPath;
434 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500435};
436
Jamie Madill21061022018-07-12 23:56:30 -0400437void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
438 bool preferMockICD,
439 VkPhysicalDevice *physicalDeviceOut,
440 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
441{
442 ASSERT(!physicalDevices.empty());
443 if (preferMockICD)
444 {
445 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
446 {
447 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
448 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
449 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
450 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
451 {
452 *physicalDeviceOut = physicalDevice;
453 return;
454 }
455 }
456 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
457 "physicalDevice instead.";
458 }
459
460 // Fall back to first device.
461 *physicalDeviceOut = physicalDevices[0];
462 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
463}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400464
465// Initially dumping the command graphs is disabled.
466constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700467
Jamie Madille09bd5d2016-11-29 16:20:35 -0500468} // anonymous namespace
469
Jamie Madill49ac74b2017-12-21 14:42:33 -0500470// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400471RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500472
Jamie Madillaaca96e2018-06-12 10:19:48 -0400473RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500474
475RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000476 : commandPool(std::move(other.commandPool)), fence(std::move(other.fence)), serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500477{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500478
479RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
480{
481 std::swap(commandPool, other.commandPool);
482 std::swap(fence, other.fence);
483 std::swap(serial, other.serial);
484 return *this;
485}
486
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000487void RendererVk::CommandBatch::destroy(VkDevice device)
Jamie Madillbea35a62018-07-05 11:54:10 -0400488{
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000489 commandPool.destroy(device);
Jamie Madillbea35a62018-07-05 11:54:10 -0400490 fence.destroy(device);
491}
492
Jamie Madill9f2a8612017-11-30 12:43:09 -0500493// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500494RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400495 : mDisplay(nullptr),
496 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700497 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500498 mInstance(VK_NULL_HANDLE),
499 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400500 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500501 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500502 mDebugReportCallback(VK_NULL_HANDLE),
503 mPhysicalDevice(VK_NULL_HANDLE),
504 mQueue(VK_NULL_HANDLE),
505 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
506 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400507 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400508 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400509 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400510 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400511 mCommandGraph(kEnableCommandGraphDiagnostics),
512 mGpuEventsEnabled(false),
513 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
514 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500515{
516 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
517 mFormatProperties.fill(invalid);
518}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400519
Jamie Madillb980c562018-11-27 11:34:27 -0500520RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400521
522void RendererVk::onDestroy(vk::Context *context)
523{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500524 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500525 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500526 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400527 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500528 }
529
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100530 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500531
Jamie Madillc7918ce2018-06-13 13:25:31 -0400532 mPipelineLayoutCache.destroy(mDevice);
533 mDescriptorSetLayoutCache.destroy(mDevice);
534
Jamie Madill9f2a8612017-11-30 12:43:09 -0500535 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500536 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400537 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400538 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400539 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500540
Jamie Madill06ca6342018-07-12 15:56:53 -0400541 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500542
Jamie Madill5deea722017-02-16 10:44:46 -0500543 if (mCommandPool.valid())
544 {
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000545 mCommandPool.destroy(mDevice);
Jamie Madill5deea722017-02-16 10:44:46 -0500546 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500547
548 if (mDevice)
549 {
550 vkDestroyDevice(mDevice, nullptr);
551 mDevice = VK_NULL_HANDLE;
552 }
553
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500554 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500555 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500556 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
557 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
558
559 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
560 }
561 else if (mDebugReportCallback)
562 {
563 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
564 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500565 }
566
Jamie Madill4d0bf552016-12-28 15:45:24 -0500567 if (mInstance)
568 {
569 vkDestroyInstance(mInstance, nullptr);
570 mInstance = VK_NULL_HANDLE;
571 }
572
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600573 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500574 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500575}
576
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400577void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400578{
579 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400580
581 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500582 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400583 freeAllInFlightResources();
584
585 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400586}
587
588bool RendererVk::isDeviceLost() const
589{
590 return mDeviceLost;
591}
592
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400593angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400594 egl::Display *display,
Michael Spang740db7f2019-02-06 09:40:13 -0500595 const char *wsiExtension,
596 const char *wsiLayer)
Jamie Madill327ba852016-11-30 12:38:28 -0500597{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400598 mDisplay = display;
599 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600600 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
601 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500602 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400603 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500604
Jamie Madill0448ec82016-12-23 13:41:47 -0500605 // Gather global layer properties.
606 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400607 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500608
609 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
610 if (instanceLayerCount > 0)
611 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400612 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
613 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500614 }
615
Michael Spang6c13c702019-02-06 15:59:44 -0500616 VulkanLayerVector enabledInstanceLayerNames;
617 if (mEnableValidationLayers)
618 {
619 bool layersRequested =
620 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
621 mEnableValidationLayers = GetAvailableValidationLayers(instanceLayerProps, layersRequested,
622 &enabledInstanceLayerNames);
623 }
624
625 if (wsiLayer)
626 {
627 enabledInstanceLayerNames.push_back(wsiLayer);
628 }
629
630 // Enumerate instance extensions that are provided by the vulkan
631 // implementation and implicit layers.
Jamie Madille09bd5d2016-11-29 16:20:35 -0500632 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400633 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400634 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500635
636 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
637 if (instanceExtensionCount > 0)
638 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400639 ANGLE_VK_TRY(displayVk,
640 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
641 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500642 }
643
Michael Spang6c13c702019-02-06 15:59:44 -0500644 // Enumerate instance extensions that are provided by explicit layers.
645 for (const char *layerName : enabledInstanceLayerNames)
Jamie Madill0448ec82016-12-23 13:41:47 -0500646 {
Michael Spang6c13c702019-02-06 15:59:44 -0500647 uint32_t previousExtensionCount = instanceExtensionProps.size();
648 uint32_t instanceLayerExtensionCount = 0;
649 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
650 layerName, &instanceLayerExtensionCount, nullptr));
651 instanceExtensionProps.resize(previousExtensionCount + instanceLayerExtensionCount);
652 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceExtensionProperties(
653 layerName, &instanceLayerExtensionCount,
654 instanceExtensionProps.data() + previousExtensionCount));
Jamie Madill0448ec82016-12-23 13:41:47 -0500655 }
656
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000657 std::vector<const char *> enabledInstanceExtensions;
Jamie Madille09bd5d2016-11-29 16:20:35 -0500658 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Michael Spang740db7f2019-02-06 09:40:13 -0500659 enabledInstanceExtensions.push_back(wsiExtension);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500660
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500661 bool enableDebugUtils =
662 mEnableValidationLayers &&
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000663 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500664 bool enableDebugReport =
665 mEnableValidationLayers && !enableDebugUtils &&
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000666 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500667
668 if (enableDebugUtils)
669 {
670 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
671 }
672 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500673 {
674 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
675 }
676
Jamie Madille09bd5d2016-11-29 16:20:35 -0500677 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400678 ANGLE_VK_TRY(displayVk,
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000679 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500680
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400681 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500682 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500683 applicationInfo.pApplicationName = "ANGLE";
684 applicationInfo.applicationVersion = 1;
685 applicationInfo.pEngineName = "ANGLE";
686 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700687
688 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
689 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
690 if (!enumerateInstanceVersion)
691 {
692 applicationInfo.apiVersion = VK_API_VERSION_1_0;
693 }
694 else
695 {
696 uint32_t apiVersion = VK_API_VERSION_1_0;
697 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
698 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
699 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700700 // This is the highest version of core Vulkan functionality that ANGLE uses.
701 applicationInfo.apiVersion = kPreferredVulkanAPIVersion;
Ian Elliott899c5d22018-12-21 13:12:50 -0700702 }
703 else
704 {
Ian Elliott356d26c2019-02-11 11:27:01 -0700705 // Since only 1.0 instance-level functionality is available, this must set to 1.0.
Ian Elliott899c5d22018-12-21 13:12:50 -0700706 applicationInfo.apiVersion = VK_API_VERSION_1_0;
707 }
708 }
Jamie Madill327ba852016-11-30 12:38:28 -0500709
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400710 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500711 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
712 instanceInfo.flags = 0;
713 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500714
Jamie Madille09bd5d2016-11-29 16:20:35 -0500715 // Enable requested layers and extensions.
716 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
717 instanceInfo.ppEnabledExtensionNames =
718 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Michael Spang6c13c702019-02-06 15:59:44 -0500719 instanceInfo.enabledLayerCount = enabledInstanceLayerNames.size();
720 instanceInfo.ppEnabledLayerNames = enabledInstanceLayerNames.data();
Jamie Madill327ba852016-11-30 12:38:28 -0500721
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400722 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500723
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500724 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500725 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500726 // Try to use the newer EXT_debug_utils if it exists.
727 InitDebugUtilsEXTFunctions(mInstance);
728
729 // Create the messenger callback.
730 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
731
Shahbaz Youssefi983e4462019-01-18 16:04:50 -0500732 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
733 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
734 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
735
736 constexpr VkDebugUtilsMessageTypeFlagsEXT kMessagesToLog =
737 VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
738 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
739 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
740
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500741 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
Shahbaz Youssefi983e4462019-01-18 16:04:50 -0500742 messengerInfo.messageSeverity = kSeveritiesToLog;
743 messengerInfo.messageType = kMessagesToLog;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500744 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
745 messengerInfo.pUserData = this;
746
747 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
748 &mDebugUtilsMessenger));
749 }
750 else if (enableDebugReport)
751 {
752 // Fallback to EXT_debug_report.
753 InitDebugReportEXTFunctions(mInstance);
754
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400755 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500756
757 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500758 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500759 debugReportInfo.pfnCallback = &DebugReportCallback;
760 debugReportInfo.pUserData = this;
761
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500762 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
763 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500764 }
765
Jamie Madill4d0bf552016-12-28 15:45:24 -0500766 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400767 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
768 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500769
770 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700771 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400772 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
773 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400774 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700775 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500776
Jamie Madill30b5d842018-08-31 17:19:12 -0400777 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
778
Jamie Madill4d0bf552016-12-28 15:45:24 -0500779 // Ensure we can find a graphics queue family.
780 uint32_t queueCount = 0;
781 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
782
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400783 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500784
785 mQueueFamilyProperties.resize(queueCount);
786 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
787 mQueueFamilyProperties.data());
788
Jamie Madillb980c562018-11-27 11:34:27 -0500789 size_t graphicsQueueFamilyCount = false;
790 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500791 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500792 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
793 {
794 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500795 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500796 {
797 ASSERT(queueInfo.queueCount > 0);
798 graphicsQueueFamilyCount++;
799 if (firstGraphicsQueueFamily == 0)
800 {
801 firstGraphicsQueueFamily = familyIndex;
802 }
803 break;
804 }
805 }
806
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400807 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500808
809 // If only one queue family, go ahead and initialize the device. If there is more than one
810 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
811 if (graphicsQueueFamilyCount == 1)
812 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400813 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500814 }
815
Jamie Madill035fd6b2017-10-03 15:43:22 -0400816 // Store the physical device memory properties so we can find the right memory pools.
817 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500818
Jamie Madill06ca6342018-07-12 15:56:53 -0400819 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500820
Jamie Madill6a89d222017-11-02 11:59:51 -0400821 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500822 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400823
Jamie Madill7c985f52018-11-29 18:16:17 -0500824 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400825}
826
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400827angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500828{
829 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400830 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400831 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500832
833 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
834 if (deviceLayerCount > 0)
835 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400836 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
837 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500838 }
839
Michael Spang6c13c702019-02-06 15:59:44 -0500840 VulkanLayerVector enabledDeviceLayerNames;
841 if (mEnableValidationLayers)
842 {
843 mEnableValidationLayers =
844 GetAvailableValidationLayers(deviceLayerProps, false, &enabledDeviceLayerNames);
845 }
846
847 const char *wsiLayer = displayVk->getWSILayer();
848 if (wsiLayer)
849 {
850 enabledDeviceLayerNames.push_back(wsiLayer);
851 }
852
853 // Enumerate device extensions that are provided by the vulkan
854 // implementation and implicit layers.
Jamie Madill4d0bf552016-12-28 15:45:24 -0500855 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400856 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
857 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500858
859 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
860 if (deviceExtensionCount > 0)
861 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400862 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
863 &deviceExtensionCount,
864 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500865 }
866
Michael Spang6c13c702019-02-06 15:59:44 -0500867 // Enumerate device extensions that are provided by explicit layers.
868 for (const char *layerName : enabledDeviceLayerNames)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500869 {
Michael Spang6c13c702019-02-06 15:59:44 -0500870 uint32_t previousExtensionCount = deviceExtensionProps.size();
871 uint32_t deviceLayerExtensionCount = 0;
872 ANGLE_VK_TRY(displayVk,
873 vkEnumerateDeviceExtensionProperties(mPhysicalDevice, layerName,
874 &deviceLayerExtensionCount, nullptr));
875 deviceExtensionProps.resize(previousExtensionCount + deviceLayerExtensionCount);
876 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(
877 mPhysicalDevice, layerName, &deviceLayerExtensionCount,
878 deviceExtensionProps.data() + previousExtensionCount));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500879 }
880
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000881 std::vector<const char *> enabledDeviceExtensions;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500882 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
883
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000884 initFeatures(deviceExtensionProps);
Ian Elliottbcb78902018-12-19 11:46:29 -0700885 mFeaturesInitialized = true;
886
Luc Ferronbf6dc372018-06-28 15:24:19 -0400887 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700888 if ((getFeatures().flipViewportY) &&
889 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400890 {
891 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
892 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700893 if (getFeatures().supportsIncrementalPresent)
894 {
895 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
896 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400897
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000898 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500899
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400900 // Select additional features to be enabled
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000901 VkPhysicalDeviceFeatures enabledFeatures = {};
902 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
903 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400904
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400905 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500906
907 float zeroPriority = 0.0f;
908
909 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500910 queueCreateInfo.flags = 0;
911 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
912 queueCreateInfo.queueCount = 1;
913 queueCreateInfo.pQueuePriorities = &zeroPriority;
914
915 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400916 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500917
Jamie Madill50cf2be2018-06-15 09:46:57 -0400918 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400919 createInfo.flags = 0;
920 createInfo.queueCreateInfoCount = 1;
921 createInfo.pQueueCreateInfos = &queueCreateInfo;
Michael Spang6c13c702019-02-06 15:59:44 -0500922 createInfo.enabledLayerCount = enabledDeviceLayerNames.size();
923 createInfo.ppEnabledLayerNames = enabledDeviceLayerNames.data();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500924 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
925 createInfo.ppEnabledExtensionNames =
926 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi341304d2019-02-12 20:58:54 +0000927 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500928
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400929 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500930
931 mCurrentQueueFamilyIndex = queueFamilyIndex;
932
933 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
934
935 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400936 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500937 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
938 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
939 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500940
Tobin Ehlis47ca1b22019-01-23 16:11:41 +0000941 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400942
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400943 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500944 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500945
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400946 // Initialize the submission semaphore pool.
947 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
948
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400949#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
950 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
951 ASSERT(platform);
952
953 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
954 // platform discovery.
955 const unsigned char *gpuEventsEnabled =
956 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
957 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
958#endif
959
960 if (mGpuEventsEnabled)
961 {
962 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
963 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
964 vk::kDefaultTimestampQueryPoolSize));
965 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
966 }
967
Jamie Madill7c985f52018-11-29 18:16:17 -0500968 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500969}
970
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400971angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400972 VkSurfaceKHR surface,
973 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500974{
975 // We've already initialized a device, and can't re-create it unless it's never been used.
976 // TODO(jmadill): Handle the re-creation case if necessary.
977 if (mDevice != VK_NULL_HANDLE)
978 {
979 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
980
981 // Check if the current device supports present on this surface.
982 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400983 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400984 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500985 surface, &supportsPresent));
986
Jamie Madill6cad7732018-07-11 09:01:17 -0400987 if (supportsPresent == VK_TRUE)
988 {
989 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500990 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400991 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500992 }
993
994 // Find a graphics and present queue.
995 Optional<uint32_t> newPresentQueue;
996 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500997 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500998 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
999 {
1000 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001001 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001002 {
1003 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001004 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
1005 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001006
1007 if (supportsPresent == VK_TRUE)
1008 {
1009 newPresentQueue = queueIndex;
1010 break;
1011 }
1012 }
1013 }
1014
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001015 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1016 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001017
Jamie Madill6cad7732018-07-11 09:01:17 -04001018 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001019 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001020}
1021
1022std::string RendererVk::getVendorString() const
1023{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001024 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001025}
1026
Jamie Madille09bd5d2016-11-29 16:20:35 -05001027std::string RendererVk::getRendererDescription() const
1028{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001029 std::stringstream strstr;
1030
1031 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1032
1033 strstr << "Vulkan ";
1034 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1035 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1036 strstr << VK_VERSION_PATCH(apiVersion);
1037
Olli Etuahoc6a06182018-04-13 14:11:46 +03001038 strstr << "(";
1039
1040 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1041 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1042 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1043 // driver detection.
1044 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1045 {
1046 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1047 }
1048
Geoff Langa7af56b2018-12-14 14:20:28 -05001049 strstr << mPhysicalDeviceProperties.deviceName;
1050 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1051
1052 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001053
1054 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001055}
1056
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001057gl::Version RendererVk::getMaxSupportedESVersion() const
1058{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001059 // Current highest supported version
1060 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1061 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001062
Geoff Lang0c2c9232019-01-14 16:01:38 -05001063 // Vulkan inherited queries are required to support any GL query type
1064 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001065 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001066 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001067 }
1068
Geoff Lang0c2c9232019-01-14 16:01:38 -05001069 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001070}
1071
Shahbaz Youssefi341304d2019-02-12 20:58:54 +00001072void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001073{
Jamie Madillb36a4812018-09-25 10:15:11 -04001074// Use OpenGL line rasterization rules by default.
1075// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1076#if defined(ANGLE_PLATFORM_ANDROID)
1077 mFeatures.basicGLLineRasterization = false;
1078#else
Jamie Madill12222072018-07-11 14:59:48 -04001079 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001080#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001081
Ian Elliott52f5da42018-12-21 09:02:09 -07001082 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
Shahbaz Youssefi341304d2019-02-12 20:58:54 +00001083 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001084 {
1085 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1086 // investigation. http://anglebug.com/2728
1087 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1088 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001089
1090#ifdef ANGLE_PLATFORM_WINDOWS
1091 // http://anglebug.com/2838
1092 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001093
1094 // http://anglebug.com/3055
1095 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001096#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001097
1098 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1099 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001100
1101 // Work around incorrect NVIDIA point size range clamping.
1102 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1103 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1104 {
1105 mFeatures.clampPointSize = true;
1106 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001107
Jamie Madillfa7ca182019-01-15 11:20:58 -05001108 // We also need to clamp point size on several Android drivers.
1109 // TODO(jmadill): Remove suppression once fixed. http://anglebug.com/2599
1110 if (IsAndroid())
1111 {
1112 mFeatures.clampPointSize = true;
1113 }
1114
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001115#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001116 // Work around ineffective compute-graphics barriers on Nexus 5X.
1117 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1118 // http://anglebug.com/3019
1119 mFeatures.flushAfterVertexConversion =
1120 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001121#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001122
Shahbaz Youssefi341304d2019-02-12 20:58:54 +00001123 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottbcb78902018-12-19 11:46:29 -07001124 {
1125 mFeatures.supportsIncrementalPresent = true;
1126 }
Jamie Madill12222072018-07-11 14:59:48 -04001127}
1128
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001129void RendererVk::initPipelineCacheVkKey()
1130{
1131 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1132 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1133 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1134 // there is no '\0' in the result.
1135 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1136 {
1137 hashStream << std::hex << c;
1138 }
1139 // Add the vendor and device id too for good measure.
1140 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1141 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1142
1143 const std::string &hashString = hashStream.str();
1144 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1145 hashString.length(), mPipelineCacheVkBlobKey.data());
1146}
1147
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001148angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001149{
1150 initPipelineCacheVkKey();
1151
1152 egl::BlobCache::Value initialData;
1153 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1154 mPipelineCacheVkBlobKey, &initialData);
1155
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001156 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001157
1158 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001159 pipelineCacheCreateInfo.flags = 0;
1160 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1161 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1162
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001163 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001164 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001165}
1166
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001167void RendererVk::getSubmitWaitSemaphores(
1168 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001169 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1170 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001171{
1172 if (mSubmitLastSignaledSemaphore.getSemaphore())
1173 {
1174 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001175 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001176
1177 // Return the semaphore to the pool (which will remain valid and unused until the
1178 // queue it's about to be waited on has finished execution).
1179 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1180 }
1181
1182 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1183 {
1184 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001185 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1186
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001187 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1188 }
1189 mSubmitWaitSemaphores.clear();
1190}
1191
Jamie Madillacccc6c2016-05-03 17:22:10 -04001192const gl::Caps &RendererVk::getNativeCaps() const
1193{
1194 ensureCapsInitialized();
1195 return mNativeCaps;
1196}
1197
1198const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1199{
1200 ensureCapsInitialized();
1201 return mNativeTextureCaps;
1202}
1203
1204const gl::Extensions &RendererVk::getNativeExtensions() const
1205{
1206 ensureCapsInitialized();
1207 return mNativeExtensions;
1208}
1209
1210const gl::Limitations &RendererVk::getNativeLimitations() const
1211{
1212 ensureCapsInitialized();
1213 return mNativeLimitations;
1214}
1215
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001216uint32_t RendererVk::getMaxActiveTextures()
1217{
1218 // TODO(lucferron): expose this limitation to GL in Context Caps
1219 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1220 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1221}
1222
Jamie Madill49ac74b2017-12-21 14:42:33 -05001223const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001224{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001225 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001226}
1227
Jamie Madill21061022018-07-12 23:56:30 -04001228angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001229{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001230 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001231 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001232 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1233
Luc Ferron1617e692018-07-11 11:08:19 -04001234 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1235 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001236
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001237 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001238 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1239 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001240
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001241 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001242 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001243 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1244 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001245 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001246 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001247 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001248 submitInfo.signalSemaphoreCount = 0;
1249 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001250
Jamie Madill21061022018-07-12 23:56:30 -04001251 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001252 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001253
Jamie Madill4c26fc22017-02-24 11:04:10 -05001254 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001255 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001256 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001257
1258 if (mGpuEventsEnabled)
1259 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001260 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001261 while (mInFlightGpuEventQueries.size() > 0)
1262 {
1263 ANGLE_TRY(checkCompletedGpuEvents(context));
1264 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001265 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1266 // synchronization if there is no event to be adjusted (happens when finish() gets called
1267 // multiple times towards the end of the application).
1268 if (mGpuEvents.size() > 0)
1269 {
1270 ANGLE_TRY(synchronizeCpuGpuTime(context));
1271 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001272 }
1273
Jamie Madill7c985f52018-11-29 18:16:17 -05001274 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001275}
1276
Jamie Madill0c0dc342017-03-24 14:18:51 -04001277void RendererVk::freeAllInFlightResources()
1278{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001279 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001280 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001281 // On device loss we need to wait for fence to be signaled before destroying it
1282 if (mDeviceLost)
1283 {
1284 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1285 // If wait times out, it is probably not possible to recover from lost device
1286 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1287 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001288 batch.fence.destroy(mDevice);
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001289 batch.commandPool.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001290 }
1291 mInFlightCommands.clear();
1292
1293 for (auto &garbage : mGarbage)
1294 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001295 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001296 }
1297 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001298
1299 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001300}
1301
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001302angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001303{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001304 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001305
Jamie Madill49ac74b2017-12-21 14:42:33 -05001306 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001307 {
Yuly Novikov27780292018-11-09 11:19:49 -05001308 VkResult result = batch.fence.getStatus(mDevice);
1309 if (result == VK_NOT_READY)
1310 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001311 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001312 }
1313 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001314
Jamie Madill49ac74b2017-12-21 14:42:33 -05001315 ASSERT(batch.serial > mLastCompletedQueueSerial);
1316 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001317
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318 batch.fence.destroy(mDevice);
Tobin Ehlis4a419142019-02-05 08:50:30 -07001319 TRACE_EVENT0("gpu.angle", "commandPool.destroy");
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001320 batch.commandPool.destroy(mDevice);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001321 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001322 }
1323
Jamie Madill49ac74b2017-12-21 14:42:33 -05001324 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001325
1326 size_t freeIndex = 0;
1327 for (; freeIndex < mGarbage.size(); ++freeIndex)
1328 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001329 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001330 break;
1331 }
1332
1333 // Remove the entries from the garbage list - they should be ready to go.
1334 if (freeIndex > 0)
1335 {
1336 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001337 }
1338
Jamie Madill7c985f52018-11-29 18:16:17 -05001339 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001340}
1341
Jamie Madill21061022018-07-12 23:56:30 -04001342angle::Result RendererVk::submitFrame(vk::Context *context,
1343 const VkSubmitInfo &submitInfo,
1344 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001345{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001346 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001347 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001348 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1349 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001350
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001351 vk::Scoped<CommandBatch> scopedBatch(mDevice);
Jamie Madillbea35a62018-07-05 11:54:10 -04001352 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001353 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001354
Jamie Madill21061022018-07-12 23:56:30 -04001355 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001356
1357 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001358 batch.commandPool = std::move(mCommandPool);
1359 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001360
Jamie Madillbea35a62018-07-05 11:54:10 -04001361 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001362
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001363 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1364 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001365 // so the limit is larger than the expected number of images. The
1366 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001367 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001368
Jamie Madill85ca1892019-01-16 13:27:15 -05001369 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001370
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001371 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001372
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001373 if (mGpuEventsEnabled)
1374 {
1375 ANGLE_TRY(checkCompletedGpuEvents(context));
1376 }
1377
Jamie Madill49ac74b2017-12-21 14:42:33 -05001378 // Simply null out the command buffer here - it was allocated using the command pool.
1379 commandBuffer.releaseHandle();
1380
1381 // Reallocate the command pool for next frame.
1382 // TODO(jmadill): Consider reusing command pools.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001383 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001384 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001385 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001386 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001387
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001388 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001389 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001390}
1391
Jamie Madill85ca1892019-01-16 13:27:15 -05001392void RendererVk::nextSerial()
1393{
1394 // Increment the queue serial. If this fails, we should restart ANGLE.
1395 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1396 mCurrentQueueSerial = mQueueSerialFactory.generate();
1397
1398 // Notify the Contexts that they should be starting new command buffers.
1399 // We use one command pool per serial/submit associated with this VkQueue. We can also
1400 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1401 // check for a new serial when starting a new command buffer. We just check that the current
1402 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1403 // using this VkQueue that they their current command buffer is no longer valid.
1404 for (gl::Context *context : mDisplay->getContextSet())
1405 {
1406 ContextVk *contextVk = vk::GetImpl(context);
1407 contextVk->onCommandBufferFinished();
1408 }
1409}
1410
Jamie Madillaaca96e2018-06-12 10:19:48 -04001411bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001412{
1413 return serial > mLastCompletedQueueSerial;
1414}
1415
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001416angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1417{
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001418 bool timedOut = false;
1419 angle::Result result = finishToSerialOrTimeout(context, serial, kMaxFenceWaitTimeNs, &timedOut);
1420
1421 // Don't tolerate timeout. If such a large wait time results in timeout, something's wrong.
1422 if (timedOut)
1423 {
1424 result = angle::Result::Stop;
1425 }
1426 return result;
1427}
1428
1429angle::Result RendererVk::finishToSerialOrTimeout(vk::Context *context,
1430 Serial serial,
1431 uint64_t timeout,
1432 bool *outTimedOut)
1433{
1434 *outTimedOut = false;
1435
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001436 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1437 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001438 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001439 }
1440
1441 // Find the first batch with serial equal to or bigger than given serial (note that
1442 // the batch serials are unique, otherwise upper-bound would have been necessary).
1443 size_t batchIndex = mInFlightCommands.size() - 1;
1444 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1445 {
1446 if (mInFlightCommands[i].serial >= serial)
1447 {
1448 batchIndex = i;
1449 break;
1450 }
1451 }
1452 const CommandBatch &batch = mInFlightCommands[batchIndex];
1453
1454 // Wait for it finish
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001455 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1456
1457 // If timed out, report it as such.
1458 if (status == VK_TIMEOUT)
1459 {
1460 *outTimedOut = true;
1461 return angle::Result::Continue;
1462 }
1463
1464 ANGLE_VK_TRY(context, status);
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001465
1466 // Clean up finished batches.
1467 return checkCompletedCommands(context);
1468}
1469
Jamie Madill21061022018-07-12 23:56:30 -04001470angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1471 const vk::RenderPassDesc &desc,
1472 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001473{
Jamie Madill21061022018-07-12 23:56:30 -04001474 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001475 renderPassOut);
1476}
1477
Jamie Madill21061022018-07-12 23:56:30 -04001478angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1479 const vk::RenderPassDesc &desc,
1480 const vk::AttachmentOpsArray &ops,
1481 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001482{
Jamie Madill21061022018-07-12 23:56:30 -04001483 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001484 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001485}
1486
Jamie Madilla5e06072018-05-18 14:36:05 -04001487vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001488{
Jamie Madilla5e06072018-05-18 14:36:05 -04001489 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001490}
1491
Jamie Madill21061022018-07-12 23:56:30 -04001492angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001493{
Jamie Madill21061022018-07-12 23:56:30 -04001494 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001495 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001496}
1497
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001498angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001499{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001500 if (mCommandGraph.empty())
1501 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001502 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001503 }
1504
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001505 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1506
Jamie Madillbea35a62018-07-05 11:54:10 -04001507 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1508 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001509
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001510 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001511 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1512 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001513
1514 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1515 // will be waited on.
1516 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001517
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001518 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001519 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001520 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1521 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001522 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001523 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001524 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001525 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001526 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001527
Jamie Madill21061022018-07-12 23:56:30 -04001528 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001529
Jamie Madill7c985f52018-11-29 18:16:17 -05001530 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001531}
1532
Jamie Madill78feddc2018-04-27 11:45:05 -04001533Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001534{
Jamie Madill78feddc2018-04-27 11:45:05 -04001535 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001536}
1537
Jamie Madill21061022018-07-12 23:56:30 -04001538angle::Result RendererVk::getDescriptorSetLayout(
1539 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001540 const vk::DescriptorSetLayoutDesc &desc,
1541 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1542{
Jamie Madill21061022018-07-12 23:56:30 -04001543 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001544}
1545
Jamie Madill21061022018-07-12 23:56:30 -04001546angle::Result RendererVk::getPipelineLayout(
1547 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001548 const vk::PipelineLayoutDesc &desc,
1549 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1550 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1551{
Jamie Madill21061022018-07-12 23:56:30 -04001552 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001553 pipelineLayoutOut);
1554}
1555
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001556angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1557{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001558 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001559
1560 if (--mPipelineCacheVkUpdateTimeout > 0)
1561 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001562 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001563 }
1564
1565 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1566
1567 // Get the size of the cache.
1568 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001569 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001570 if (result != VK_INCOMPLETE)
1571 {
1572 ANGLE_VK_TRY(displayVk, result);
1573 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001574
1575 angle::MemoryBuffer *pipelineCacheData = nullptr;
1576 ANGLE_VK_CHECK_ALLOC(displayVk,
1577 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1578
1579 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001580 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001581 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1582 // was determined just above), so receiving it hints at an implementation bug we would want
1583 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001584 ASSERT(result != VK_INCOMPLETE);
1585 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001586
1587 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1588 // the buffer to avoid leaking garbage memory.
1589 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1590 if (pipelineCacheSize < originalPipelineCacheSize)
1591 {
1592 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1593 originalPipelineCacheSize - pipelineCacheSize);
1594 }
1595
1596 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1597
Jamie Madill7c985f52018-11-29 18:16:17 -05001598 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001599}
1600
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001601angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1602 const vk::Semaphore **outSemaphore)
1603{
1604 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1605
1606 vk::SemaphoreHelper semaphore;
1607 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1608
1609 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1610 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1611
Jamie Madill7c985f52018-11-29 18:16:17 -05001612 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001613}
1614
1615const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1616{
1617 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1618
1619 // Return the semaphore to the pool (which will remain valid and unused until the
1620 // queue it's about to be waited on has finished execution). The caller is about
1621 // to wait on it.
1622 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1623
1624 return semaphore;
1625}
1626
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001627angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1628{
1629 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1630 // that seems impossible, so instead, we are going to make a small submission with just a
1631 // timestamp query. First, the disjoint timer query extension says:
1632 //
1633 // > This will return the GL time after all previous commands have reached the GL server but
1634 // have not yet necessarily executed.
1635 //
1636 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1637 // The wording allows us to make a submission to get the timestamp without performing a flush.
1638 //
1639 // Second:
1640 //
1641 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1642 // object target, applications can measure the latency between when commands reach the GL server
1643 // and when they are realized in the framebuffer.
1644 //
1645 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1646 // GPU bubble. This function directly generates a command buffer and submits it instead of
1647 // using the other member functions. This is to avoid changing any state, such as the queue
1648 // serial.
1649
1650 // Create a query used to receive the GPU timestamp
1651 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1652 vk::QueryHelper timestampQuery;
1653 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1654 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1655
1656 // Record the command buffer
1657 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1658 vk::CommandBuffer &commandBuffer = commandBatch.get();
1659
1660 VkCommandBufferAllocateInfo commandBufferInfo = {};
1661 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1662 commandBufferInfo.commandPool = mCommandPool.getHandle();
1663 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1664 commandBufferInfo.commandBufferCount = 1;
1665
Yuly Novikov27780292018-11-09 11:19:49 -05001666 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001667
1668 VkCommandBufferBeginInfo beginInfo = {};
1669 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1670 beginInfo.flags = 0;
1671 beginInfo.pInheritanceInfo = nullptr;
1672
Yuly Novikov27780292018-11-09 11:19:49 -05001673 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001674
1675 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1676 timestampQuery.getQuery(), 1);
1677 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1678 timestampQuery.getQueryPool()->getHandle(),
1679 timestampQuery.getQuery());
1680
Yuly Novikov27780292018-11-09 11:19:49 -05001681 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001682
1683 // Create fence for the submission
1684 VkFenceCreateInfo fenceInfo = {};
1685 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1686 fenceInfo.flags = 0;
1687
1688 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001689 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001690
1691 // Submit the command buffer
1692 VkSubmitInfo submitInfo = {};
1693 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1694 submitInfo.waitSemaphoreCount = 0;
1695 submitInfo.pWaitSemaphores = nullptr;
1696 submitInfo.pWaitDstStageMask = nullptr;
1697 submitInfo.commandBufferCount = 1;
1698 submitInfo.pCommandBuffers = commandBuffer.ptr();
1699 submitInfo.signalSemaphoreCount = 0;
1700 submitInfo.pSignalSemaphores = nullptr;
1701
1702 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1703
1704 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1705 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001706 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001707
1708 // Get the query results
1709 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1710
Yuly Novikov27780292018-11-09 11:19:49 -05001711 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1712 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1713 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001714
1715 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1716
Shahbaz Youssefi5904ee32019-01-25 11:15:16 -05001717 // Convert results to nanoseconds.
1718 *timestampOut = static_cast<uint64_t>(
1719 *timestampOut * static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod));
1720
Jamie Madill7c985f52018-11-29 18:16:17 -05001721 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001722}
1723
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001724// These functions look at the mandatory format for support, and fallback to querying the device (if
1725// necessary) to test the availability of the bits.
1726bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1727 const VkFormatFeatureFlags featureBits)
1728{
1729 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1730}
1731
1732bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1733 const VkFormatFeatureFlags featureBits)
1734{
1735 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1736}
1737
1738bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1739{
1740 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1741}
1742
Shahbaz Youssefi983e4462019-01-18 16:04:50 -05001743void RendererVk::insertDebugMarker(GLenum source, GLuint id, std::string &&marker)
1744{
1745 mCommandGraph.insertDebugMarker(source, std::move(marker));
1746}
1747
1748void RendererVk::pushDebugMarker(GLenum source, GLuint id, std::string &&marker)
1749{
1750 mCommandGraph.pushDebugMarker(source, std::move(marker));
1751}
1752
1753void RendererVk::popDebugMarker()
1754{
1755 mCommandGraph.popDebugMarker();
1756}
1757
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001758angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1759{
1760 ASSERT(mGpuEventsEnabled);
1761
1762 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1763 ASSERT(platform);
1764
1765 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1766 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1767 //
1768 // CPU GPU
1769 //
1770 // Record command buffer
1771 // with timestamp query
1772 //
1773 // Submit command buffer
1774 //
1775 // Post-submission work Begin execution
1776 //
Tobin Ehlis47ca1b22019-01-23 16:11:41 +00001777 // ???? Write timstamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001778 //
1779 // ???? End execution
1780 //
1781 // ???? Return query results
1782 //
1783 // ????
1784 //
1785 // Get query results
1786 //
1787 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1788 // finished post-submission work while the GPU is executing in parallel. With no further work,
1789 // querying CPU timestamps before submission and after getting query results give the bounds to
1790 // Tgpu, which could be quite large.
1791 //
1792 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1793 // reduce this range. This function implements the following procedure:
1794 //
1795 // CPU GPU
1796 //
1797 // Record command buffer
1798 // with timestamp query
1799 //
1800 // Submit command buffer
1801 //
1802 // Post-submission work Begin execution
1803 //
1804 // ???? Set Event GPUReady
1805 //
1806 // Wait on Event GPUReady Wait on Event CPUReady
1807 //
1808 // Get CPU Time Ts Wait on Event CPUReady
1809 //
1810 // Set Event CPUReady Wait on Event CPUReady
1811 //
1812 // Get CPU Time Tcpu Get GPU Time Tgpu
1813 //
1814 // Wait on Event GPUDone Set Event GPUDone
1815 //
1816 // Get CPU Time Te End Execution
1817 //
1818 // Idle Return query results
1819 //
1820 // Get query results
1821 //
1822 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1823 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1824 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1825 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1826 // calibration.
1827 //
1828 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1829
1830 // Make sure nothing is running
1831 ASSERT(mCommandGraph.empty());
1832
1833 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1834
1835 // Create a query used to receive the GPU timestamp
1836 vk::QueryHelper timestampQuery;
1837 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1838
1839 // Create the three events
1840 VkEventCreateInfo eventCreateInfo = {};
1841 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1842 eventCreateInfo.flags = 0;
1843
1844 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001845 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1846 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1847 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001848
1849 constexpr uint32_t kRetries = 10;
1850
1851 // Time suffixes used are S for seconds and Cycles for cycles
1852 double tightestRangeS = 1e6f;
1853 double TcpuS = 0;
1854 uint64_t TgpuCycles = 0;
1855 for (uint32_t i = 0; i < kRetries; ++i)
1856 {
1857 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001858 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1859 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1860 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001861
1862 // Record the command buffer
1863 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1864 vk::CommandBuffer &commandBuffer = commandBatch.get();
1865
1866 VkCommandBufferAllocateInfo commandBufferInfo = {};
1867 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1868 commandBufferInfo.commandPool = mCommandPool.getHandle();
1869 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1870 commandBufferInfo.commandBufferCount = 1;
1871
Yuly Novikov27780292018-11-09 11:19:49 -05001872 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001873
1874 VkCommandBufferBeginInfo beginInfo = {};
1875 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1876 beginInfo.flags = 0;
1877 beginInfo.pInheritanceInfo = nullptr;
1878
Yuly Novikov27780292018-11-09 11:19:49 -05001879 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001880
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001881 commandBuffer.setEvent(gpuReady.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001882 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1883 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1884 nullptr);
1885
1886 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1887 timestampQuery.getQuery(), 1);
1888 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1889 timestampQuery.getQueryPool()->getHandle(),
1890 timestampQuery.getQuery());
1891
Shahbaz Youssefi82fddcb2019-01-18 14:27:43 -05001892 commandBuffer.setEvent(gpuDone.get().getHandle(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001893
Yuly Novikov27780292018-11-09 11:19:49 -05001894 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001895
1896 // Submit the command buffer
1897 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1898 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1899 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1900
1901 VkSubmitInfo submitInfo = {};
1902 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1903 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1904 submitInfo.pWaitSemaphores = waitSemaphores.data();
1905 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1906 submitInfo.commandBufferCount = 1;
1907 submitInfo.pCommandBuffers = commandBuffer.ptr();
1908 submitInfo.signalSemaphoreCount = 0;
1909 submitInfo.pSignalSemaphores = nullptr;
1910
1911 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1912
1913 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001914 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001915 do
1916 {
Yuly Novikov27780292018-11-09 11:19:49 -05001917 result = gpuReady.get().getStatus(mDevice);
1918 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1919 {
1920 ANGLE_VK_TRY(context, result);
1921 }
1922 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001923
1924 double TsS = platform->monotonicallyIncreasingTime(platform);
1925
1926 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001927 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001928 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1929
1930 // Wait for GPU to be done. Another short busy wait.
1931 do
1932 {
Yuly Novikov27780292018-11-09 11:19:49 -05001933 result = gpuDone.get().getStatus(mDevice);
1934 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1935 {
1936 ANGLE_VK_TRY(context, result);
1937 }
1938 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001939
1940 double TeS = platform->monotonicallyIncreasingTime(platform);
1941
1942 // Get the query results
1943 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1944
1945 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1946
1947 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001948 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1949 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1950 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001951
1952 // Use the first timestamp queried as origin.
1953 if (mGpuEventTimestampOrigin == 0)
1954 {
1955 mGpuEventTimestampOrigin = gpuTimestampCycles;
1956 }
1957
1958 // Take these CPU and GPU timestamps if there is better confidence.
1959 double confidenceRangeS = TeS - TsS;
1960 if (confidenceRangeS < tightestRangeS)
1961 {
1962 tightestRangeS = confidenceRangeS;
1963 TcpuS = cpuTimestampS;
1964 TgpuCycles = gpuTimestampCycles;
1965 }
1966 }
1967
1968 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1969
1970 // timestampPeriod gives nanoseconds/cycle.
1971 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1972 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1973 1'000'000'000.0;
1974
1975 flushGpuEvents(TgpuS, TcpuS);
1976
1977 mGpuClockSync.gpuTimestampS = TgpuS;
1978 mGpuClockSync.cpuTimestampS = TcpuS;
1979
Jamie Madill7c985f52018-11-29 18:16:17 -05001980 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001981}
1982
1983angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1984 vk::CommandBuffer *commandBuffer,
1985 char phase,
1986 const char *name)
1987{
1988 ASSERT(mGpuEventsEnabled);
1989
1990 GpuEventQuery event;
1991
1992 event.name = name;
1993 event.phase = phase;
1994 event.serial = mCurrentQueueSerial;
1995
1996 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1997
1998 commandBuffer->resetQueryPool(
1999 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
2000 commandBuffer->writeTimestamp(
2001 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2002 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
2003
2004 mInFlightGpuEventQueries.push_back(std::move(event));
2005
Jamie Madill7c985f52018-11-29 18:16:17 -05002006 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002007}
2008
2009angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
2010{
2011 ASSERT(mGpuEventsEnabled);
2012
2013 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2014 ASSERT(platform);
2015
2016 int finishedCount = 0;
2017
2018 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
2019 {
2020 // Only check the timestamp query if the submission has finished.
2021 if (eventQuery.serial > mLastCompletedQueueSerial)
2022 {
2023 break;
2024 }
2025
2026 // See if the results are available.
2027 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05002028 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
2029 ->getResults(mDevice, eventQuery.queryIndex, 1,
2030 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
2031 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
2032 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002033 {
2034 break;
2035 }
Yuly Novikov27780292018-11-09 11:19:49 -05002036 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002037
2038 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
2039
2040 GpuEvent event;
2041 event.gpuTimestampCycles = gpuTimestampCycles;
2042 event.name = eventQuery.name;
2043 event.phase = eventQuery.phase;
2044
2045 mGpuEvents.emplace_back(event);
2046
2047 ++finishedCount;
2048 }
2049
2050 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2051 mInFlightGpuEventQueries.begin() + finishedCount);
2052
Jamie Madill7c985f52018-11-29 18:16:17 -05002053 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002054}
2055
2056void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2057{
2058 if (mGpuEvents.size() == 0)
2059 {
2060 return;
2061 }
2062
2063 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2064 ASSERT(platform);
2065
2066 // Find the slope of the clock drift for adjustment
2067 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2068 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2069 double gpuSyncDriftSlope = 0;
2070
2071 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2072 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2073
2074 // No gpu trace events should have been generated before the clock sync, so if there is no
2075 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2076 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2077 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2078
2079 gpuSyncDriftSlope =
2080 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2081
2082 for (const GpuEvent &event : mGpuEvents)
2083 {
2084 double gpuTimestampS =
2085 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2086 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2087
2088 // Account for clock drift.
2089 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2090
2091 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2092 // for.
2093 static long long eventId = 1;
2094 static const unsigned char *categoryEnabled =
2095 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2096 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2097 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2098 }
2099
2100 mGpuEvents.clear();
2101}
2102
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002103template <VkFormatFeatureFlags VkFormatProperties::*features>
2104bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2105{
2106 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2107 VkFormatProperties &deviceProperties = mFormatProperties[format];
2108
2109 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2110 {
2111 // If we don't have the actual device features, see if the requested features are mandatory.
2112 // If so, there's no need to query the device.
2113 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2114 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2115 {
2116 return true;
2117 }
2118
2119 // Otherwise query the format features and cache it.
2120 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2121 }
2122
2123 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2124}
2125
Jamie Madillaaca96e2018-06-12 10:19:48 -04002126uint32_t GetUniformBufferDescriptorCount()
2127{
2128 return kUniformBufferDescriptorsPerDescriptorSet;
2129}
2130
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002131} // namespace rx