blob: 8916ad132e6932ed08660d8f250b40ab8e527543 [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"
Jamie Madill9e54b5a2016-05-25 12:57:39 -040034
Shahbaz Youssefi61656022018-10-24 15:00:50 -040035#include "third_party/trace_event/trace_event.h"
36
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070037// Consts
38namespace
39{
Jamie Madill7c985f52018-11-29 18:16:17 -050040const uint32_t kMockVendorID = 0xba5eba11;
41const uint32_t kMockDeviceID = 0xf005ba11;
42constexpr char kMockDeviceName[] = "Vulkan Mock Device";
43constexpr size_t kInFlightCommandsLimit = 100u;
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -050044constexpr VkFormatFeatureFlags kInvalidFormatFeatureFlags = static_cast<VkFormatFeatureFlags>(-1);
Tobin Ehlisa3b220f2018-03-06 16:22:13 -070045} // anonymous namespace
46
Jamie Madill9e54b5a2016-05-25 12:57:39 -040047namespace rx
48{
49
Jamie Madille09bd5d2016-11-29 16:20:35 -050050namespace
51{
Luc Ferrondaedf4d2018-03-16 09:28:53 -040052// We currently only allocate 2 uniform buffer per descriptor set, one for the fragment shader and
53// one for the vertex shader.
54constexpr size_t kUniformBufferDescriptorsPerDescriptorSet = 2;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -040055// Update the pipeline cache every this many swaps (if 60fps, this means every 10 minutes)
56static constexpr uint32_t kPipelineCacheVkUpdatePeriod = 10 * 60 * 60;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -040057// Wait a maximum of 10s. If that times out, we declare it a failure.
58static constexpr uint64_t kMaxFenceWaitTimeNs = 10'000'000'000llu;
Jamie Madille09bd5d2016-11-29 16:20:35 -050059
Omar El Sheikh26c61b22018-06-29 12:50:59 -060060bool ShouldEnableMockICD(const egl::AttributeMap &attribs)
61{
62#if !defined(ANGLE_PLATFORM_ANDROID)
63 // Mock ICD does not currently run on Android
64 return (attribs.get(EGL_PLATFORM_ANGLE_DEVICE_TYPE_ANGLE,
65 EGL_PLATFORM_ANGLE_DEVICE_TYPE_HARDWARE_ANGLE) ==
66 EGL_PLATFORM_ANGLE_DEVICE_TYPE_NULL_ANGLE);
67#else
68 return false;
69#endif // !defined(ANGLE_PLATFORM_ANDROID)
70}
71
Jamie Madille09bd5d2016-11-29 16:20:35 -050072VkResult VerifyExtensionsPresent(const std::vector<VkExtensionProperties> &extensionProps,
73 const std::vector<const char *> &enabledExtensionNames)
74{
75 // Compile the extensions names into a set.
76 std::set<std::string> extensionNames;
77 for (const auto &extensionProp : extensionProps)
78 {
79 extensionNames.insert(extensionProp.extensionName);
80 }
81
Jamie Madillacf2f3a2017-11-21 19:22:44 -050082 for (const char *extensionName : enabledExtensionNames)
Jamie Madille09bd5d2016-11-29 16:20:35 -050083 {
84 if (extensionNames.count(extensionName) == 0)
85 {
86 return VK_ERROR_EXTENSION_NOT_PRESENT;
87 }
88 }
89
90 return VK_SUCCESS;
91}
92
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050093bool ExtensionFound(const char *extensionName,
94 const std::vector<VkExtensionProperties> &extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060095{
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050096 for (const auto &extensionProp : extensionProps)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060097 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -050098 if (strcmp(extensionProp.extensionName, extensionName) == 0)
Tobin Ehlis3a181e32018-08-29 15:17:05 -060099 {
100 return true;
101 }
102 }
103 return false;
104}
105
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500106// Array of Validation error/warning messages that will be ignored, should include bugID
107constexpr std::array<const char *, 1> kSkippedMessages = {
108 // http://anglebug.com/2796
109 "UNASSIGNED-CoreValidation-Shader-PointSizeMissing"};
110
111// Suppress validation errors that are known
112// return "true" if given code/prefix/message is known, else return "false"
113bool IsIgnoredDebugMessage(const char *message)
114{
115 for (const char *msg : kSkippedMessages)
116 {
117 if (strstr(message, msg) != nullptr)
118 {
119 return true;
120 }
121 }
122 return false;
123}
124
125const char *GetVkObjectTypeName(VkObjectType type)
126{
127 switch (type)
128 {
129 case VK_OBJECT_TYPE_UNKNOWN:
130 return "Unknown";
131 case VK_OBJECT_TYPE_INSTANCE:
132 return "Instance";
133 case VK_OBJECT_TYPE_PHYSICAL_DEVICE:
134 return "Physical Device";
135 case VK_OBJECT_TYPE_DEVICE:
136 return "Device";
137 case VK_OBJECT_TYPE_QUEUE:
138 return "Queue";
139 case VK_OBJECT_TYPE_SEMAPHORE:
140 return "Semaphore";
141 case VK_OBJECT_TYPE_COMMAND_BUFFER:
142 return "Command Buffer";
143 case VK_OBJECT_TYPE_FENCE:
144 return "Fence";
145 case VK_OBJECT_TYPE_DEVICE_MEMORY:
146 return "Device Memory";
147 case VK_OBJECT_TYPE_BUFFER:
148 return "Buffer";
149 case VK_OBJECT_TYPE_IMAGE:
150 return "Image";
151 case VK_OBJECT_TYPE_EVENT:
152 return "Event";
153 case VK_OBJECT_TYPE_QUERY_POOL:
154 return "Query Pool";
155 case VK_OBJECT_TYPE_BUFFER_VIEW:
156 return "Buffer View";
157 case VK_OBJECT_TYPE_IMAGE_VIEW:
158 return "Image View";
159 case VK_OBJECT_TYPE_SHADER_MODULE:
160 return "Shader Module";
161 case VK_OBJECT_TYPE_PIPELINE_CACHE:
162 return "Pipeline Cache";
163 case VK_OBJECT_TYPE_PIPELINE_LAYOUT:
164 return "Pipeline Layout";
165 case VK_OBJECT_TYPE_RENDER_PASS:
166 return "Render Pass";
167 case VK_OBJECT_TYPE_PIPELINE:
168 return "Pipeline";
169 case VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT:
170 return "Descriptor Set Layout";
171 case VK_OBJECT_TYPE_SAMPLER:
172 return "Sampler";
173 case VK_OBJECT_TYPE_DESCRIPTOR_POOL:
174 return "Descriptor Pool";
175 case VK_OBJECT_TYPE_DESCRIPTOR_SET:
176 return "Descriptor Set";
177 case VK_OBJECT_TYPE_FRAMEBUFFER:
178 return "Framebuffer";
179 case VK_OBJECT_TYPE_COMMAND_POOL:
180 return "Command Pool";
181 case VK_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION:
182 return "Sampler YCbCr Conversion";
183 case VK_OBJECT_TYPE_DESCRIPTOR_UPDATE_TEMPLATE:
184 return "Descriptor Update Template";
185 case VK_OBJECT_TYPE_SURFACE_KHR:
186 return "Surface";
187 case VK_OBJECT_TYPE_SWAPCHAIN_KHR:
188 return "Swapchain";
189 case VK_OBJECT_TYPE_DISPLAY_KHR:
190 return "Display";
191 case VK_OBJECT_TYPE_DISPLAY_MODE_KHR:
192 return "Display Mode";
193 case VK_OBJECT_TYPE_DEBUG_REPORT_CALLBACK_EXT:
194 return "Debug Report Callback";
195 case VK_OBJECT_TYPE_OBJECT_TABLE_NVX:
196 return "Object Table";
197 case VK_OBJECT_TYPE_INDIRECT_COMMANDS_LAYOUT_NVX:
198 return "Indirect Commands Layout";
199 case VK_OBJECT_TYPE_DEBUG_UTILS_MESSENGER_EXT:
200 return "Debug Utils Messenger";
201 case VK_OBJECT_TYPE_VALIDATION_CACHE_EXT:
202 return "Validation Cache";
203 case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NVX:
204 return "Acceleration Structure";
205 default:
206 return "<Unrecognized>";
207 }
208}
209
210VKAPI_ATTR VkBool32 VKAPI_CALL
211DebugUtilsMessenger(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
212 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
213 const VkDebugUtilsMessengerCallbackDataEXT *callbackData,
214 void *userData)
215{
216 constexpr VkDebugUtilsMessageSeverityFlagsEXT kSeveritiesToLog =
217 VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
218 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
219
220 // Check if we even care about this message.
221 if ((messageSeverity & kSeveritiesToLog) == 0)
222 {
223 return VK_FALSE;
224 }
225
226 // See if it's an issue we are aware of and don't want to be spammed about.
227 if (IsIgnoredDebugMessage(callbackData->pMessageIdName))
228 {
229 return VK_FALSE;
230 }
231
232 std::ostringstream log;
233 log << "[ " << callbackData->pMessageIdName << " ] " << callbackData->pMessage << std::endl;
234
235 // Aesthetic value based on length of the function name, line number, etc.
236 constexpr size_t kStartIndent = 28;
237
238 // Output the debug marker hierarchy under which this error has occured.
239 size_t indent = kStartIndent;
240 if (callbackData->queueLabelCount > 0)
241 {
242 log << std::string(indent++, ' ') << "<Queue Label Hierarchy:>" << std::endl;
243 for (uint32_t i = 0; i < callbackData->queueLabelCount; ++i)
244 {
245 log << std::string(indent++, ' ') << callbackData->pQueueLabels[i].pLabelName
246 << std::endl;
247 }
248 }
249 if (callbackData->cmdBufLabelCount > 0)
250 {
251 log << std::string(indent++, ' ') << "<Command Buffer Label Hierarchy:>" << std::endl;
252 for (uint32_t i = 0; i < callbackData->cmdBufLabelCount; ++i)
253 {
254 log << std::string(indent++, ' ') << callbackData->pCmdBufLabels[i].pLabelName
255 << std::endl;
256 }
257 }
258 // Output the objects involved in this error message.
259 if (callbackData->objectCount > 0)
260 {
261 for (uint32_t i = 0; i < callbackData->objectCount; ++i)
262 {
263 const char *objectName = callbackData->pObjects[i].pObjectName;
264 const char *objectType = GetVkObjectTypeName(callbackData->pObjects[i].objectType);
265 uint64_t objectHandle = callbackData->pObjects[i].objectHandle;
266 log << std::string(indent, ' ') << "Object: ";
267 if (objectHandle == 0)
268 {
269 log << "VK_NULL_HANDLE";
270 }
271 else
272 {
273 log << "0x" << std::hex << objectHandle << std::dec;
274 }
275 log << " (type = " << objectType << "(" << callbackData->pObjects[i].objectType << "))";
276 if (objectName)
277 {
278 log << " [" << objectName << "]";
279 }
280 log << std::endl;
281 }
282 }
283
284 bool isError = (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0;
285
286 if (isError)
287 {
288 ERR() << log.str();
289 }
290 else
291 {
292 WARN() << log.str();
293 }
294
295 return VK_FALSE;
296}
297
Yuly Novikov199f4292018-01-19 19:04:05 -0500298VKAPI_ATTR VkBool32 VKAPI_CALL DebugReportCallback(VkDebugReportFlagsEXT flags,
299 VkDebugReportObjectTypeEXT objectType,
300 uint64_t object,
301 size_t location,
302 int32_t messageCode,
303 const char *layerPrefix,
304 const char *message,
305 void *userData)
Jamie Madill0448ec82016-12-23 13:41:47 -0500306{
Tobin Ehlis3a181e32018-08-29 15:17:05 -0600307 if (IsIgnoredDebugMessage(message))
308 {
309 return VK_FALSE;
310 }
Jamie Madill0448ec82016-12-23 13:41:47 -0500311 if ((flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) != 0)
312 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500313 ERR() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500314#if !defined(NDEBUG)
315 // Abort the call in Debug builds.
316 return VK_TRUE;
317#endif
318 }
319 else if ((flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) != 0)
320 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500321 WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500322 }
323 else
324 {
Yuly Novikovbcb3f9b2017-01-27 22:45:18 -0500325 // Uncomment this if you want Vulkan spam.
326 // WARN() << message;
Jamie Madill0448ec82016-12-23 13:41:47 -0500327 }
328
329 return VK_FALSE;
330}
331
Yuly Novikov199f4292018-01-19 19:04:05 -0500332// If we're loading the validation layers, we could be running from any random directory.
333// Change to the executable directory so we can find the layers, then change back to the
334// previous directory to be safe we don't disrupt the application.
335class ScopedVkLoaderEnvironment : angle::NonCopyable
336{
337 public:
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600338 ScopedVkLoaderEnvironment(bool enableValidationLayers, bool enableMockICD)
339 : mEnableValidationLayers(enableValidationLayers),
340 mEnableMockICD(enableMockICD),
341 mChangedCWD(false),
342 mChangedICDPath(false)
Yuly Novikov199f4292018-01-19 19:04:05 -0500343 {
344// Changing CWD and setting environment variables makes no sense on Android,
345// since this code is a part of Java application there.
346// Android Vulkan loader doesn't need this either.
347#if !defined(ANGLE_PLATFORM_ANDROID)
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600348 if (enableMockICD)
349 {
350 // Override environment variable to use built Mock ICD
351 // ANGLE_VK_ICD_JSON gets set to the built mock ICD in BUILD.gn
352 mPreviousICDPath = angle::GetEnvironmentVar(g_VkICDPathEnv);
353 mChangedICDPath = angle::SetEnvironmentVar(g_VkICDPathEnv, ANGLE_VK_ICD_JSON);
354 if (!mChangedICDPath)
355 {
356 ERR() << "Error setting Path for Mock/Null Driver.";
357 mEnableMockICD = false;
358 }
359 }
Jamie Madill46848422018-08-09 10:46:06 -0400360 if (mEnableValidationLayers || mEnableMockICD)
Yuly Novikov199f4292018-01-19 19:04:05 -0500361 {
362 const auto &cwd = angle::GetCWD();
363 if (!cwd.valid())
364 {
365 ERR() << "Error getting CWD for Vulkan layers init.";
366 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400367 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500368 }
369 else
370 {
371 mPreviousCWD = cwd.value();
Jamie Madillbab03022019-01-16 14:12:28 -0500372 std::string exeDir = angle::GetExecutableDirectory();
373 mChangedCWD = angle::SetCWD(exeDir.c_str());
Yuly Novikov199f4292018-01-19 19:04:05 -0500374 if (!mChangedCWD)
375 {
376 ERR() << "Error setting CWD for Vulkan layers init.";
377 mEnableValidationLayers = false;
Jamie Madill46848422018-08-09 10:46:06 -0400378 mEnableMockICD = false;
Yuly Novikov199f4292018-01-19 19:04:05 -0500379 }
380 }
381 }
382
383 // Override environment variable to use the ANGLE layers.
384 if (mEnableValidationLayers)
385 {
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700386 if (!angle::PrependPathToEnvironmentVar(g_VkLoaderLayersPathEnv, ANGLE_VK_DATA_DIR))
Yuly Novikov199f4292018-01-19 19:04:05 -0500387 {
388 ERR() << "Error setting environment for Vulkan layers init.";
389 mEnableValidationLayers = false;
390 }
391 }
392#endif // !defined(ANGLE_PLATFORM_ANDROID)
393 }
394
395 ~ScopedVkLoaderEnvironment()
396 {
397 if (mChangedCWD)
398 {
399#if !defined(ANGLE_PLATFORM_ANDROID)
400 ASSERT(mPreviousCWD.valid());
401 angle::SetCWD(mPreviousCWD.value().c_str());
402#endif // !defined(ANGLE_PLATFORM_ANDROID)
403 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600404 if (mChangedICDPath)
405 {
Omar El Sheikh80d4ef12018-07-13 17:08:19 -0600406 if (mPreviousICDPath.value().empty())
407 {
408 angle::UnsetEnvironmentVar(g_VkICDPathEnv);
409 }
410 else
411 {
412 angle::SetEnvironmentVar(g_VkICDPathEnv, mPreviousICDPath.value().c_str());
413 }
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600414 }
Yuly Novikov199f4292018-01-19 19:04:05 -0500415 }
416
Jamie Madillaaca96e2018-06-12 10:19:48 -0400417 bool canEnableValidationLayers() const { return mEnableValidationLayers; }
Yuly Novikov199f4292018-01-19 19:04:05 -0500418
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600419 bool canEnableMockICD() const { return mEnableMockICD; }
420
Yuly Novikov199f4292018-01-19 19:04:05 -0500421 private:
422 bool mEnableValidationLayers;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600423 bool mEnableMockICD;
Yuly Novikov199f4292018-01-19 19:04:05 -0500424 bool mChangedCWD;
425 Optional<std::string> mPreviousCWD;
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600426 bool mChangedICDPath;
427 Optional<std::string> mPreviousICDPath;
Yuly Novikov199f4292018-01-19 19:04:05 -0500428};
429
Jamie Madill21061022018-07-12 23:56:30 -0400430void ChoosePhysicalDevice(const std::vector<VkPhysicalDevice> &physicalDevices,
431 bool preferMockICD,
432 VkPhysicalDevice *physicalDeviceOut,
433 VkPhysicalDeviceProperties *physicalDevicePropertiesOut)
434{
435 ASSERT(!physicalDevices.empty());
436 if (preferMockICD)
437 {
438 for (const VkPhysicalDevice &physicalDevice : physicalDevices)
439 {
440 vkGetPhysicalDeviceProperties(physicalDevice, physicalDevicePropertiesOut);
441 if ((kMockVendorID == physicalDevicePropertiesOut->vendorID) &&
442 (kMockDeviceID == physicalDevicePropertiesOut->deviceID) &&
443 (strcmp(kMockDeviceName, physicalDevicePropertiesOut->deviceName) == 0))
444 {
445 *physicalDeviceOut = physicalDevice;
446 return;
447 }
448 }
449 WARN() << "Vulkan Mock Driver was requested but Mock Device was not found. Using default "
450 "physicalDevice instead.";
451 }
452
453 // Fall back to first device.
454 *physicalDeviceOut = physicalDevices[0];
455 vkGetPhysicalDeviceProperties(*physicalDeviceOut, physicalDevicePropertiesOut);
456}
Jamie Madill0da73fe2018-10-02 09:31:39 -0400457
458// Initially dumping the command graphs is disabled.
459constexpr bool kEnableCommandGraphDiagnostics = false;
Ian Elliottbcb78902018-12-19 11:46:29 -0700460
Tobin Ehlis05459e02019-01-17 12:25:54 -0500461// Custom allocation functions
462VKAPI_ATTR void *VKAPI_CALL PoolAllocationFunction(void *pUserData,
463 size_t size,
464 size_t alignment,
465 VkSystemAllocationScope allocationScope)
466{
467 angle::PoolAllocator *poolAllocator = static_cast<angle::PoolAllocator *>(pUserData);
468
469 ASSERT((angle::PoolAllocator::kDefaultAlignment % alignment) == 0);
470 return poolAllocator->allocate(size);
471}
472
473VKAPI_ATTR void *VKAPI_CALL PoolReallocationFunction(void *pUserData,
474 void *pOriginal,
475 size_t size,
476 size_t alignment,
477 VkSystemAllocationScope allocationScope)
478{
479 angle::PoolAllocator *poolAllocator = static_cast<angle::PoolAllocator *>(pUserData);
480 return poolAllocator->reallocate(pOriginal, size);
481}
482
483VKAPI_ATTR void VKAPI_CALL PoolFreeFunction(void *pUserData, void *pMemory) {}
484
485VKAPI_ATTR void VKAPI_CALL
486PoolInternalAllocationNotification(void *pUserData,
487 size_t size,
488 VkInternalAllocationType allocationType,
489 VkSystemAllocationScope allocationScope)
490{}
491
492VKAPI_ATTR void VKAPI_CALL PoolInternalFreeNotification(void *pUserData,
493 size_t size,
494 VkInternalAllocationType allocationType,
495 VkSystemAllocationScope allocationScope)
496{}
497
498void InitPoolAllocationCallbacks(angle::PoolAllocator *poolAllocator,
499 VkAllocationCallbacks *allocationCallbacks)
500{
501 allocationCallbacks->pUserData = static_cast<void *>(poolAllocator);
502 allocationCallbacks->pfnAllocation = &PoolAllocationFunction;
503 allocationCallbacks->pfnReallocation = &PoolReallocationFunction;
504 allocationCallbacks->pfnFree = &PoolFreeFunction;
505 allocationCallbacks->pfnInternalAllocation = &PoolInternalAllocationNotification;
506 allocationCallbacks->pfnInternalFree = &PoolInternalFreeNotification;
507}
508
Jamie Madille09bd5d2016-11-29 16:20:35 -0500509} // anonymous namespace
510
Jamie Madill49ac74b2017-12-21 14:42:33 -0500511// CommandBatch implementation.
Jamie Madillaaca96e2018-06-12 10:19:48 -0400512RendererVk::CommandBatch::CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500513
Jamie Madillaaca96e2018-06-12 10:19:48 -0400514RendererVk::CommandBatch::~CommandBatch() = default;
Jamie Madill49ac74b2017-12-21 14:42:33 -0500515
516RendererVk::CommandBatch::CommandBatch(CommandBatch &&other)
Tobin Ehlis05459e02019-01-17 12:25:54 -0500517 : commandPool(std::move(other.commandPool)),
518 poolAllocator(std::move(other.poolAllocator)),
519 fence(std::move(other.fence)),
520 serial(other.serial)
Jamie Madillb980c562018-11-27 11:34:27 -0500521{}
Jamie Madill49ac74b2017-12-21 14:42:33 -0500522
523RendererVk::CommandBatch &RendererVk::CommandBatch::operator=(CommandBatch &&other)
524{
525 std::swap(commandPool, other.commandPool);
Tobin Ehlis05459e02019-01-17 12:25:54 -0500526 std::swap(poolAllocator, other.poolAllocator);
Jamie Madill49ac74b2017-12-21 14:42:33 -0500527 std::swap(fence, other.fence);
528 std::swap(serial, other.serial);
529 return *this;
530}
531
Tobin Ehlis05459e02019-01-17 12:25:54 -0500532void RendererVk::CommandBatch::destroy(VkDevice device,
533 const VkAllocationCallbacks *allocationCallbacks)
Jamie Madillbea35a62018-07-05 11:54:10 -0400534{
Tobin Ehlis05459e02019-01-17 12:25:54 -0500535 commandPool.destroy(device, allocationCallbacks);
Jamie Madillbea35a62018-07-05 11:54:10 -0400536 fence.destroy(device);
537}
538
Jamie Madill9f2a8612017-11-30 12:43:09 -0500539// RendererVk implementation.
Jamie Madill0448ec82016-12-23 13:41:47 -0500540RendererVk::RendererVk()
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400541 : mDisplay(nullptr),
542 mCapsInitialized(false),
Ian Elliottbcb78902018-12-19 11:46:29 -0700543 mFeaturesInitialized(false),
Jamie Madill0448ec82016-12-23 13:41:47 -0500544 mInstance(VK_NULL_HANDLE),
545 mEnableValidationLayers(false),
Jamie Madill0ea96212018-10-30 15:14:51 -0400546 mEnableMockICD(false),
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500547 mDebugUtilsMessenger(VK_NULL_HANDLE),
Jamie Madill4d0bf552016-12-28 15:45:24 -0500548 mDebugReportCallback(VK_NULL_HANDLE),
549 mPhysicalDevice(VK_NULL_HANDLE),
550 mQueue(VK_NULL_HANDLE),
551 mCurrentQueueFamilyIndex(std::numeric_limits<uint32_t>::max()),
552 mDevice(VK_NULL_HANDLE),
Jamie Madillfb05bcb2017-06-07 15:43:18 -0400553 mLastCompletedQueueSerial(mQueueSerialFactory.generate()),
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400554 mCurrentQueueSerial(mQueueSerialFactory.generate()),
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400555 mDeviceLost(false),
Jamie Madill0da73fe2018-10-02 09:31:39 -0400556 mPipelineCacheVkUpdateTimeout(kPipelineCacheVkUpdatePeriod),
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400557 mCommandGraph(kEnableCommandGraphDiagnostics),
558 mGpuEventsEnabled(false),
559 mGpuClockSync{std::numeric_limits<double>::max(), std::numeric_limits<double>::max()},
560 mGpuEventTimestampOrigin(0)
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500561{
562 VkFormatProperties invalid = {0, 0, kInvalidFormatFeatureFlags};
563 mFormatProperties.fill(invalid);
564}
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400565
Jamie Madillb980c562018-11-27 11:34:27 -0500566RendererVk::~RendererVk() {}
Jamie Madill21061022018-07-12 23:56:30 -0400567
568void RendererVk::onDestroy(vk::Context *context)
569{
Jamie Madill49ac74b2017-12-21 14:42:33 -0500570 if (!mInFlightCommands.empty() || !mGarbage.empty())
Jamie Madill4c26fc22017-02-24 11:04:10 -0500571 {
Jamie Madill49ac74b2017-12-21 14:42:33 -0500572 // TODO(jmadill): Not nice to pass nullptr here, but shouldn't be a problem.
Jamie Madill21061022018-07-12 23:56:30 -0400573 (void)finish(context);
Jamie Madill4c26fc22017-02-24 11:04:10 -0500574 }
575
Shahbaz Youssefie3219402018-12-08 16:54:14 +0100576 mUtils.destroy(mDevice);
Shahbaz Youssefi8f1b7a62018-11-14 16:02:54 -0500577
Jamie Madillc7918ce2018-06-13 13:25:31 -0400578 mPipelineLayoutCache.destroy(mDevice);
579 mDescriptorSetLayoutCache.destroy(mDevice);
580
Jamie Madill9f2a8612017-11-30 12:43:09 -0500581 mRenderPassCache.destroy(mDevice);
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500582 mPipelineCache.destroy(mDevice);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400583 mSubmitSemaphorePool.destroy(mDevice);
Jamie Madilld47044a2018-04-27 11:45:03 -0400584 mShaderLibrary.destroy(mDevice);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400585 mGpuEventQueryPool.destroy(mDevice);
Jamie Madill9f2a8612017-11-30 12:43:09 -0500586
Jamie Madill06ca6342018-07-12 15:56:53 -0400587 GlslangWrapper::Release();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500588
Jamie Madill5deea722017-02-16 10:44:46 -0500589 if (mCommandPool.valid())
590 {
Tobin Ehlis05459e02019-01-17 12:25:54 -0500591 mCommandPool.destroy(mDevice, &mAllocationCallbacks);
Jamie Madill5deea722017-02-16 10:44:46 -0500592 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500593
594 if (mDevice)
595 {
596 vkDestroyDevice(mDevice, nullptr);
597 mDevice = VK_NULL_HANDLE;
598 }
599
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500600 if (mDebugUtilsMessenger)
Jamie Madill0448ec82016-12-23 13:41:47 -0500601 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500602 ASSERT(mInstance && vkDestroyDebugUtilsMessengerEXT);
603 vkDestroyDebugUtilsMessengerEXT(mInstance, mDebugUtilsMessenger, nullptr);
604
605 ASSERT(mDebugReportCallback == VK_NULL_HANDLE);
606 }
607 else if (mDebugReportCallback)
608 {
609 ASSERT(mInstance && vkDestroyDebugReportCallbackEXT);
610 vkDestroyDebugReportCallbackEXT(mInstance, mDebugReportCallback, nullptr);
Jamie Madill0448ec82016-12-23 13:41:47 -0500611 }
612
Jamie Madill4d0bf552016-12-28 15:45:24 -0500613 if (mInstance)
614 {
615 vkDestroyInstance(mInstance, nullptr);
616 mInstance = VK_NULL_HANDLE;
617 }
618
Omar El Sheikheb4b8692018-07-17 10:55:40 -0600619 mMemoryProperties.destroy();
Jamie Madill4d0bf552016-12-28 15:45:24 -0500620 mPhysicalDevice = VK_NULL_HANDLE;
Jamie Madill327ba852016-11-30 12:38:28 -0500621}
622
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400623void RendererVk::notifyDeviceLost()
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400624{
625 mDeviceLost = true;
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400626
627 mCommandGraph.clear();
Jamie Madill85ca1892019-01-16 13:27:15 -0500628 nextSerial();
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400629 freeAllInFlightResources();
630
631 mDisplay->notifyDeviceLost();
Geoff Lang2fe5e1d2018-08-28 14:00:24 -0400632}
633
634bool RendererVk::isDeviceLost() const
635{
636 return mDeviceLost;
637}
638
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400639angle::Result RendererVk::initialize(DisplayVk *displayVk,
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400640 egl::Display *display,
Jamie Madill21061022018-07-12 23:56:30 -0400641 const char *wsiName)
Jamie Madill327ba852016-11-30 12:38:28 -0500642{
Yuly Novikovb56ddbb2018-11-02 16:53:18 -0400643 mDisplay = display;
644 const egl::AttributeMap &attribs = mDisplay->getAttributeMap();
Omar El Sheikh26c61b22018-06-29 12:50:59 -0600645 ScopedVkLoaderEnvironment scopedEnvironment(ShouldUseDebugLayers(attribs),
646 ShouldEnableMockICD(attribs));
Yuly Novikov199f4292018-01-19 19:04:05 -0500647 mEnableValidationLayers = scopedEnvironment.canEnableValidationLayers();
Jamie Madill0ea96212018-10-30 15:14:51 -0400648 mEnableMockICD = scopedEnvironment.canEnableMockICD();
Jamie Madilla66779f2017-01-06 10:43:44 -0500649
Jamie Madill0448ec82016-12-23 13:41:47 -0500650 // Gather global layer properties.
651 uint32_t instanceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400652 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount, nullptr));
Jamie Madill0448ec82016-12-23 13:41:47 -0500653
654 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerCount);
655 if (instanceLayerCount > 0)
656 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400657 ANGLE_VK_TRY(displayVk, vkEnumerateInstanceLayerProperties(&instanceLayerCount,
658 instanceLayerProps.data()));
Jamie Madill0448ec82016-12-23 13:41:47 -0500659 }
660
Jamie Madille09bd5d2016-11-29 16:20:35 -0500661 uint32_t instanceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400662 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400663 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount, nullptr));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500664
665 std::vector<VkExtensionProperties> instanceExtensionProps(instanceExtensionCount);
666 if (instanceExtensionCount > 0)
667 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400668 ANGLE_VK_TRY(displayVk,
669 vkEnumerateInstanceExtensionProperties(nullptr, &instanceExtensionCount,
670 instanceExtensionProps.data()));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500671 }
672
Yuly Novikov199f4292018-01-19 19:04:05 -0500673 const char *const *enabledLayerNames = nullptr;
674 uint32_t enabledLayerCount = 0;
Jamie Madill0448ec82016-12-23 13:41:47 -0500675 if (mEnableValidationLayers)
676 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500677 bool layersRequested =
678 (attribs.get(EGL_PLATFORM_ANGLE_DEBUG_LAYERS_ENABLED_ANGLE, EGL_DONT_CARE) == EGL_TRUE);
679 mEnableValidationLayers = GetAvailableValidationLayers(
680 instanceLayerProps, layersRequested, &enabledLayerNames, &enabledLayerCount);
Jamie Madill0448ec82016-12-23 13:41:47 -0500681 }
682
Jamie Madille09bd5d2016-11-29 16:20:35 -0500683 std::vector<const char *> enabledInstanceExtensions;
684 enabledInstanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
Frank Henigman29f148b2016-11-23 21:05:36 -0500685 enabledInstanceExtensions.push_back(wsiName);
Jamie Madille09bd5d2016-11-29 16:20:35 -0500686
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500687 bool enableDebugUtils =
688 mEnableValidationLayers &&
689 ExtensionFound(VK_EXT_DEBUG_UTILS_EXTENSION_NAME, instanceExtensionProps);
690 bool enableDebugReport =
691 mEnableValidationLayers && !enableDebugUtils &&
692 ExtensionFound(VK_EXT_DEBUG_REPORT_EXTENSION_NAME, instanceExtensionProps);
693
694 if (enableDebugUtils)
695 {
696 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
697 }
698 else if (enableDebugReport)
Jamie Madill0448ec82016-12-23 13:41:47 -0500699 {
700 enabledInstanceExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
701 }
702
Jamie Madille09bd5d2016-11-29 16:20:35 -0500703 // Verify the required extensions are in the extension names set. Fail if not.
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400704 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400705 VerifyExtensionsPresent(instanceExtensionProps, enabledInstanceExtensions));
Jamie Madille09bd5d2016-11-29 16:20:35 -0500706
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400707 VkApplicationInfo applicationInfo = {};
Jamie Madill327ba852016-11-30 12:38:28 -0500708 applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
Jamie Madill327ba852016-11-30 12:38:28 -0500709 applicationInfo.pApplicationName = "ANGLE";
710 applicationInfo.applicationVersion = 1;
711 applicationInfo.pEngineName = "ANGLE";
712 applicationInfo.engineVersion = 1;
Ian Elliott899c5d22018-12-21 13:12:50 -0700713
714 auto enumerateInstanceVersion = reinterpret_cast<PFN_vkEnumerateInstanceVersion>(
715 vkGetInstanceProcAddr(mInstance, "vkEnumerateInstanceVersion"));
716 if (!enumerateInstanceVersion)
717 {
718 applicationInfo.apiVersion = VK_API_VERSION_1_0;
719 }
720 else
721 {
722 uint32_t apiVersion = VK_API_VERSION_1_0;
723 ANGLE_VK_TRY(displayVk, enumerateInstanceVersion(&apiVersion));
724 if ((VK_VERSION_MAJOR(apiVersion) > 1) || (VK_VERSION_MINOR(apiVersion) >= 1))
725 {
726 // Note: will need to revisit this with Vulkan 1.2+.
727 applicationInfo.apiVersion = VK_API_VERSION_1_1;
728 }
729 else
730 {
731 applicationInfo.apiVersion = VK_API_VERSION_1_0;
732 }
733 }
Jamie Madill327ba852016-11-30 12:38:28 -0500734
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400735 VkInstanceCreateInfo instanceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500736 instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
737 instanceInfo.flags = 0;
738 instanceInfo.pApplicationInfo = &applicationInfo;
Jamie Madill327ba852016-11-30 12:38:28 -0500739
Jamie Madille09bd5d2016-11-29 16:20:35 -0500740 // Enable requested layers and extensions.
741 instanceInfo.enabledExtensionCount = static_cast<uint32_t>(enabledInstanceExtensions.size());
742 instanceInfo.ppEnabledExtensionNames =
743 enabledInstanceExtensions.empty() ? nullptr : enabledInstanceExtensions.data();
Yuly Novikov199f4292018-01-19 19:04:05 -0500744 instanceInfo.enabledLayerCount = enabledLayerCount;
745 instanceInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill327ba852016-11-30 12:38:28 -0500746
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400747 ANGLE_VK_TRY(displayVk, vkCreateInstance(&instanceInfo, nullptr, &mInstance));
Jamie Madill327ba852016-11-30 12:38:28 -0500748
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500749 if (enableDebugUtils)
Jamie Madill0448ec82016-12-23 13:41:47 -0500750 {
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500751 // Try to use the newer EXT_debug_utils if it exists.
752 InitDebugUtilsEXTFunctions(mInstance);
753
754 // Create the messenger callback.
755 VkDebugUtilsMessengerCreateInfoEXT messengerInfo = {};
756
757 messengerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
758 messengerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT |
759 VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT;
760 messengerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT |
761 VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT |
762 VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
763 messengerInfo.pfnUserCallback = &DebugUtilsMessenger;
764 messengerInfo.pUserData = this;
765
766 ANGLE_VK_TRY(displayVk, vkCreateDebugUtilsMessengerEXT(mInstance, &messengerInfo, nullptr,
767 &mDebugUtilsMessenger));
768 }
769 else if (enableDebugReport)
770 {
771 // Fallback to EXT_debug_report.
772 InitDebugReportEXTFunctions(mInstance);
773
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400774 VkDebugReportCallbackCreateInfoEXT debugReportInfo = {};
Jamie Madill0448ec82016-12-23 13:41:47 -0500775
776 debugReportInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500777 debugReportInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT;
Jamie Madill0448ec82016-12-23 13:41:47 -0500778 debugReportInfo.pfnCallback = &DebugReportCallback;
779 debugReportInfo.pUserData = this;
780
Shahbaz Youssefi5bca4fe2019-01-09 17:07:06 -0500781 ANGLE_VK_TRY(displayVk, vkCreateDebugReportCallbackEXT(mInstance, &debugReportInfo, nullptr,
782 &mDebugReportCallback));
Jamie Madill0448ec82016-12-23 13:41:47 -0500783 }
784
Jamie Madill4d0bf552016-12-28 15:45:24 -0500785 uint32_t physicalDeviceCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400786 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount, nullptr));
787 ANGLE_VK_CHECK(displayVk, physicalDeviceCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500788
789 // TODO(jmadill): Handle multiple physical devices. For now, use the first device.
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700790 std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400791 ANGLE_VK_TRY(displayVk, vkEnumeratePhysicalDevices(mInstance, &physicalDeviceCount,
792 physicalDevices.data()));
Jamie Madill0ea96212018-10-30 15:14:51 -0400793 ChoosePhysicalDevice(physicalDevices, mEnableMockICD, &mPhysicalDevice,
Tobin Ehlisa3b220f2018-03-06 16:22:13 -0700794 &mPhysicalDeviceProperties);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500795
Jamie Madill30b5d842018-08-31 17:19:12 -0400796 vkGetPhysicalDeviceFeatures(mPhysicalDevice, &mPhysicalDeviceFeatures);
797
Jamie Madill4d0bf552016-12-28 15:45:24 -0500798 // Ensure we can find a graphics queue family.
799 uint32_t queueCount = 0;
800 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount, nullptr);
801
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400802 ANGLE_VK_CHECK(displayVk, queueCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500803
804 mQueueFamilyProperties.resize(queueCount);
805 vkGetPhysicalDeviceQueueFamilyProperties(mPhysicalDevice, &queueCount,
806 mQueueFamilyProperties.data());
807
Jamie Madillb980c562018-11-27 11:34:27 -0500808 size_t graphicsQueueFamilyCount = false;
809 uint32_t firstGraphicsQueueFamily = 0;
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500810 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500811 for (uint32_t familyIndex = 0; familyIndex < queueCount; ++familyIndex)
812 {
813 const auto &queueInfo = mQueueFamilyProperties[familyIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500814 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500815 {
816 ASSERT(queueInfo.queueCount > 0);
817 graphicsQueueFamilyCount++;
818 if (firstGraphicsQueueFamily == 0)
819 {
820 firstGraphicsQueueFamily = familyIndex;
821 }
822 break;
823 }
824 }
825
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400826 ANGLE_VK_CHECK(displayVk, graphicsQueueFamilyCount > 0, VK_ERROR_INITIALIZATION_FAILED);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500827
828 // If only one queue family, go ahead and initialize the device. If there is more than one
829 // queue, we'll have to wait until we see a WindowSurface to know which supports present.
830 if (graphicsQueueFamilyCount == 1)
831 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400832 ANGLE_TRY(initializeDevice(displayVk, firstGraphicsQueueFamily));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500833 }
834
Jamie Madill035fd6b2017-10-03 15:43:22 -0400835 // Store the physical device memory properties so we can find the right memory pools.
836 mMemoryProperties.init(mPhysicalDevice);
Jamie Madill7b57b9d2017-01-13 09:33:38 -0500837
Jamie Madill06ca6342018-07-12 15:56:53 -0400838 GlslangWrapper::Initialize();
Jamie Madill8ecf7f92017-01-13 17:29:52 -0500839
Jamie Madill6a89d222017-11-02 11:59:51 -0400840 // Initialize the format table.
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -0500841 mFormatTable.initialize(this, &mNativeTextureCaps, &mNativeCaps.compressedTextureFormats);
Jamie Madill6a89d222017-11-02 11:59:51 -0400842
Jamie Madill7c985f52018-11-29 18:16:17 -0500843 return angle::Result::Continue;
Jamie Madill9e54b5a2016-05-25 12:57:39 -0400844}
845
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400846angle::Result RendererVk::initializeDevice(DisplayVk *displayVk, uint32_t queueFamilyIndex)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500847{
848 uint32_t deviceLayerCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400849 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400850 vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500851
852 std::vector<VkLayerProperties> deviceLayerProps(deviceLayerCount);
853 if (deviceLayerCount > 0)
854 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400855 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceLayerProperties(mPhysicalDevice, &deviceLayerCount,
856 deviceLayerProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500857 }
858
859 uint32_t deviceExtensionCount = 0;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400860 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
861 &deviceExtensionCount, nullptr));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500862
863 std::vector<VkExtensionProperties> deviceExtensionProps(deviceExtensionCount);
864 if (deviceExtensionCount > 0)
865 {
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400866 ANGLE_VK_TRY(displayVk, vkEnumerateDeviceExtensionProperties(mPhysicalDevice, nullptr,
867 &deviceExtensionCount,
868 deviceExtensionProps.data()));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500869 }
870
Yuly Novikov199f4292018-01-19 19:04:05 -0500871 const char *const *enabledLayerNames = nullptr;
872 uint32_t enabledLayerCount = 0;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500873 if (mEnableValidationLayers)
874 {
Yuly Novikov199f4292018-01-19 19:04:05 -0500875 mEnableValidationLayers = GetAvailableValidationLayers(
876 deviceLayerProps, false, &enabledLayerNames, &enabledLayerCount);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500877 }
878
879 std::vector<const char *> enabledDeviceExtensions;
880 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
881
Ian Elliottbcb78902018-12-19 11:46:29 -0700882 initFeatures(deviceExtensionProps);
883 mFeaturesInitialized = true;
884
Luc Ferronbf6dc372018-06-28 15:24:19 -0400885 // Selectively enable KHR_MAINTENANCE1 to support viewport flipping.
Ian Elliott52f5da42018-12-21 09:02:09 -0700886 if ((getFeatures().flipViewportY) &&
887 (mPhysicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 1, 0)))
Luc Ferronbf6dc372018-06-28 15:24:19 -0400888 {
889 enabledDeviceExtensions.push_back(VK_KHR_MAINTENANCE1_EXTENSION_NAME);
890 }
Ian Elliottbcb78902018-12-19 11:46:29 -0700891 if (getFeatures().supportsIncrementalPresent)
892 {
893 enabledDeviceExtensions.push_back(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME);
894 }
Luc Ferronbf6dc372018-06-28 15:24:19 -0400895
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400896 ANGLE_VK_TRY(displayVk, VerifyExtensionsPresent(deviceExtensionProps, enabledDeviceExtensions));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500897
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400898 // Select additional features to be enabled
899 VkPhysicalDeviceFeatures enabledFeatures = {};
900 enabledFeatures.inheritedQueries = mPhysicalDeviceFeatures.inheritedQueries;
Jamie Madill17a50e12019-01-10 22:05:43 -0500901 enabledFeatures.robustBufferAccess = mPhysicalDeviceFeatures.robustBufferAccess;
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400902
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400903 VkDeviceQueueCreateInfo queueCreateInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500904
905 float zeroPriority = 0.0f;
906
907 queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500908 queueCreateInfo.flags = 0;
909 queueCreateInfo.queueFamilyIndex = queueFamilyIndex;
910 queueCreateInfo.queueCount = 1;
911 queueCreateInfo.pQueuePriorities = &zeroPriority;
912
913 // Initialize the device
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400914 VkDeviceCreateInfo createInfo = {};
Jamie Madill4d0bf552016-12-28 15:45:24 -0500915
Jamie Madill50cf2be2018-06-15 09:46:57 -0400916 createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
Jamie Madill50cf2be2018-06-15 09:46:57 -0400917 createInfo.flags = 0;
918 createInfo.queueCreateInfoCount = 1;
919 createInfo.pQueueCreateInfos = &queueCreateInfo;
Yuly Novikov199f4292018-01-19 19:04:05 -0500920 createInfo.enabledLayerCount = enabledLayerCount;
921 createInfo.ppEnabledLayerNames = enabledLayerNames;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500922 createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledDeviceExtensions.size());
923 createInfo.ppEnabledExtensionNames =
924 enabledDeviceExtensions.empty() ? nullptr : enabledDeviceExtensions.data();
Shahbaz Youssefi563fbaa2018-10-02 11:22:01 -0400925 createInfo.pEnabledFeatures = &enabledFeatures;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500926
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400927 ANGLE_VK_TRY(displayVk, vkCreateDevice(mPhysicalDevice, &createInfo, nullptr, &mDevice));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500928
929 mCurrentQueueFamilyIndex = queueFamilyIndex;
930
931 vkGetDeviceQueue(mDevice, mCurrentQueueFamilyIndex, 0, &mQueue);
932
Tobin Ehlis05459e02019-01-17 12:25:54 -0500933 InitPoolAllocationCallbacks(&mPoolAllocator, &mAllocationCallbacks);
Jamie Madill4d0bf552016-12-28 15:45:24 -0500934 // Initialize the command pool now that we know the queue family index.
Shahbaz Youssefi06270c92018-10-03 17:00:25 -0400935 VkCommandPoolCreateInfo commandPoolInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -0500936 commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
937 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
938 commandPoolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500939
Tobin Ehlis05459e02019-01-17 12:25:54 -0500940 ANGLE_VK_TRY(displayVk, mCommandPool.init(mDevice, commandPoolInfo, &mAllocationCallbacks));
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400941
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400942 // Initialize the vulkan pipeline cache.
Jamie Madilldc65c5b2018-11-21 11:07:26 -0500943 ANGLE_TRY(initPipelineCache(displayVk));
Jamie Madill4d0bf552016-12-28 15:45:24 -0500944
Shahbaz Youssefi3a482172018-10-11 10:34:44 -0400945 // Initialize the submission semaphore pool.
946 ANGLE_TRY(mSubmitSemaphorePool.init(displayVk, vk::kDefaultSemaphorePoolSize));
947
Shahbaz Youssefi25224e72018-10-22 11:56:02 -0400948#if ANGLE_ENABLE_VULKAN_GPU_TRACE_EVENTS
949 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
950 ASSERT(platform);
951
952 // GPU tracing workaround for anglebug.com/2927. The renderer should not emit gpu events during
953 // platform discovery.
954 const unsigned char *gpuEventsEnabled =
955 platform->getTraceCategoryEnabledFlag(platform, "gpu.angle.gpu");
956 mGpuEventsEnabled = gpuEventsEnabled && *gpuEventsEnabled;
957#endif
958
959 if (mGpuEventsEnabled)
960 {
961 // Calculate the difference between CPU and GPU clocks for GPU event reporting.
962 ANGLE_TRY(mGpuEventQueryPool.init(displayVk, VK_QUERY_TYPE_TIMESTAMP,
963 vk::kDefaultTimestampQueryPoolSize));
964 ANGLE_TRY(synchronizeCpuGpuTime(displayVk));
965 }
966
Jamie Madill7c985f52018-11-29 18:16:17 -0500967 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500968}
969
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400970angle::Result RendererVk::selectPresentQueueForSurface(DisplayVk *displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400971 VkSurfaceKHR surface,
972 uint32_t *presentQueueOut)
Jamie Madill4d0bf552016-12-28 15:45:24 -0500973{
974 // We've already initialized a device, and can't re-create it unless it's never been used.
975 // TODO(jmadill): Handle the re-creation case if necessary.
976 if (mDevice != VK_NULL_HANDLE)
977 {
978 ASSERT(mCurrentQueueFamilyIndex != std::numeric_limits<uint32_t>::max());
979
980 // Check if the current device supports present on this surface.
981 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -0400982 ANGLE_VK_TRY(displayVk,
Jamie Madill21061022018-07-12 23:56:30 -0400983 vkGetPhysicalDeviceSurfaceSupportKHR(mPhysicalDevice, mCurrentQueueFamilyIndex,
Jamie Madill4d0bf552016-12-28 15:45:24 -0500984 surface, &supportsPresent));
985
Jamie Madill6cad7732018-07-11 09:01:17 -0400986 if (supportsPresent == VK_TRUE)
987 {
988 *presentQueueOut = mCurrentQueueFamilyIndex;
Jamie Madill7c985f52018-11-29 18:16:17 -0500989 return angle::Result::Continue;
Jamie Madill6cad7732018-07-11 09:01:17 -0400990 }
Jamie Madill4d0bf552016-12-28 15:45:24 -0500991 }
992
993 // Find a graphics and present queue.
994 Optional<uint32_t> newPresentQueue;
995 uint32_t queueCount = static_cast<uint32_t>(mQueueFamilyProperties.size());
Shahbaz Youssefi823d8972018-11-13 10:52:40 -0500996 constexpr VkQueueFlags kGraphicsAndCompute = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT;
Jamie Madill4d0bf552016-12-28 15:45:24 -0500997 for (uint32_t queueIndex = 0; queueIndex < queueCount; ++queueIndex)
998 {
999 const auto &queueInfo = mQueueFamilyProperties[queueIndex];
Shahbaz Youssefi823d8972018-11-13 10:52:40 -05001000 if ((queueInfo.queueFlags & kGraphicsAndCompute) == kGraphicsAndCompute)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001001 {
1002 VkBool32 supportsPresent = VK_FALSE;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001003 ANGLE_VK_TRY(displayVk, vkGetPhysicalDeviceSurfaceSupportKHR(
1004 mPhysicalDevice, queueIndex, surface, &supportsPresent));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001005
1006 if (supportsPresent == VK_TRUE)
1007 {
1008 newPresentQueue = queueIndex;
1009 break;
1010 }
1011 }
1012 }
1013
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001014 ANGLE_VK_CHECK(displayVk, newPresentQueue.valid(), VK_ERROR_INITIALIZATION_FAILED);
1015 ANGLE_TRY(initializeDevice(displayVk, newPresentQueue.value()));
Jamie Madill4d0bf552016-12-28 15:45:24 -05001016
Jamie Madill6cad7732018-07-11 09:01:17 -04001017 *presentQueueOut = newPresentQueue.value();
Jamie Madill7c985f52018-11-29 18:16:17 -05001018 return angle::Result::Continue;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001019}
1020
1021std::string RendererVk::getVendorString() const
1022{
Olli Etuahoc6a06182018-04-13 14:11:46 +03001023 return GetVendorString(mPhysicalDeviceProperties.vendorID);
Jamie Madill4d0bf552016-12-28 15:45:24 -05001024}
1025
Jamie Madille09bd5d2016-11-29 16:20:35 -05001026std::string RendererVk::getRendererDescription() const
1027{
Jamie Madill4d0bf552016-12-28 15:45:24 -05001028 std::stringstream strstr;
1029
1030 uint32_t apiVersion = mPhysicalDeviceProperties.apiVersion;
1031
1032 strstr << "Vulkan ";
1033 strstr << VK_VERSION_MAJOR(apiVersion) << ".";
1034 strstr << VK_VERSION_MINOR(apiVersion) << ".";
1035 strstr << VK_VERSION_PATCH(apiVersion);
1036
Olli Etuahoc6a06182018-04-13 14:11:46 +03001037 strstr << "(";
1038
1039 // In the case of NVIDIA, deviceName does not necessarily contain "NVIDIA". Add "NVIDIA" so that
1040 // Vulkan end2end tests can be selectively disabled on NVIDIA. TODO(jmadill): should not be
1041 // needed after http://anglebug.com/1874 is fixed and end2end_tests use more sophisticated
1042 // driver detection.
1043 if (mPhysicalDeviceProperties.vendorID == VENDOR_ID_NVIDIA)
1044 {
1045 strstr << GetVendorString(mPhysicalDeviceProperties.vendorID) << " ";
1046 }
1047
Geoff Langa7af56b2018-12-14 14:20:28 -05001048 strstr << mPhysicalDeviceProperties.deviceName;
1049 strstr << " (" << gl::FmtHex(mPhysicalDeviceProperties.deviceID) << ")";
1050
1051 strstr << ")";
Jamie Madill4d0bf552016-12-28 15:45:24 -05001052
1053 return strstr.str();
Jamie Madille09bd5d2016-11-29 16:20:35 -05001054}
1055
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001056gl::Version RendererVk::getMaxSupportedESVersion() const
1057{
Geoff Lang0c2c9232019-01-14 16:01:38 -05001058 // Current highest supported version
1059 // TODO: Update this to support ES 3.0. http://crbug.com/angleproject/2950
1060 gl::Version maxVersion = gl::Version(2, 0);
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001061
Geoff Lang0c2c9232019-01-14 16:01:38 -05001062 // Vulkan inherited queries are required to support any GL query type
1063 if (!mPhysicalDeviceFeatures.inheritedQueries)
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001064 {
Geoff Lang0c2c9232019-01-14 16:01:38 -05001065 maxVersion = std::max(maxVersion, gl::Version(2, 0));
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001066 }
1067
Geoff Lang0c2c9232019-01-14 16:01:38 -05001068 return maxVersion;
Shahbaz Youssefi092481a2018-11-08 00:25:50 -05001069}
1070
Ian Elliottbcb78902018-12-19 11:46:29 -07001071void RendererVk::initFeatures(const std::vector<VkExtensionProperties> &deviceExtensionProps)
Jamie Madill12222072018-07-11 14:59:48 -04001072{
Jamie Madillb36a4812018-09-25 10:15:11 -04001073// Use OpenGL line rasterization rules by default.
1074// TODO(jmadill): Fix Android support. http://anglebug.com/2830
1075#if defined(ANGLE_PLATFORM_ANDROID)
1076 mFeatures.basicGLLineRasterization = false;
1077#else
Jamie Madill12222072018-07-11 14:59:48 -04001078 mFeatures.basicGLLineRasterization = true;
Jamie Madillb36a4812018-09-25 10:15:11 -04001079#endif // defined(ANGLE_PLATFORM_ANDROID)
Jamie Madill12222072018-07-11 14:59:48 -04001080
Ian Elliott52f5da42018-12-21 09:02:09 -07001081 if ((mPhysicalDeviceProperties.apiVersion >= VK_MAKE_VERSION(1, 1, 0)) ||
1082 ExtensionFound(VK_KHR_MAINTENANCE1_EXTENSION_NAME, deviceExtensionProps))
Ian Elliottd50521f2018-12-20 12:05:14 -07001083 {
1084 // TODO(lucferron): Currently disabled on Intel only since many tests are failing and need
1085 // investigation. http://anglebug.com/2728
1086 mFeatures.flipViewportY = !IsIntel(mPhysicalDeviceProperties.vendorID);
1087 }
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001088
1089#ifdef ANGLE_PLATFORM_WINDOWS
1090 // http://anglebug.com/2838
1091 mFeatures.extraCopyBufferRegion = IsIntel(mPhysicalDeviceProperties.vendorID);
Shahbaz Youssefi4f3b2072019-01-01 14:48:25 -05001092
1093 // http://anglebug.com/3055
1094 mFeatures.forceCpuPathForCubeMapCopy = IsIntel(mPhysicalDeviceProperties.vendorID);
Frank Henigmanbeb669d2018-09-21 16:25:52 -04001095#endif
Shahbaz Youssefid856ca42018-10-31 16:55:12 -04001096
1097 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1098 platform->overrideFeaturesVk(platform, &mFeatures);
Jamie Madillfde74c02018-11-18 16:12:02 -05001099
1100 // Work around incorrect NVIDIA point size range clamping.
1101 // TODO(jmadill): Narrow driver range once fixed. http://anglebug.com/2970
1102 if (IsNvidia(mPhysicalDeviceProperties.vendorID))
1103 {
1104 mFeatures.clampPointSize = true;
1105 }
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001106
1107#if defined(ANGLE_PLATFORM_ANDROID)
Shahbaz Youssefib08457d2018-12-11 15:13:54 -05001108 // Work around ineffective compute-graphics barriers on Nexus 5X.
1109 // TODO(syoussefi): Figure out which other vendors and driver versions are affected.
1110 // http://anglebug.com/3019
1111 mFeatures.flushAfterVertexConversion =
1112 IsNexus5X(mPhysicalDeviceProperties.vendorID, mPhysicalDeviceProperties.deviceID);
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001113#endif
Ian Elliottbcb78902018-12-19 11:46:29 -07001114
1115 if (ExtensionFound(VK_KHR_INCREMENTAL_PRESENT_EXTENSION_NAME, deviceExtensionProps))
1116 {
1117 mFeatures.supportsIncrementalPresent = true;
1118 }
Jamie Madill12222072018-07-11 14:59:48 -04001119}
1120
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001121void RendererVk::initPipelineCacheVkKey()
1122{
1123 std::ostringstream hashStream("ANGLE Pipeline Cache: ", std::ios_base::ate);
1124 // Add the pipeline cache UUID to make sure the blob cache always gives a compatible pipeline
1125 // cache. It's not particularly necessary to write it as a hex number as done here, so long as
1126 // there is no '\0' in the result.
1127 for (const uint32_t c : mPhysicalDeviceProperties.pipelineCacheUUID)
1128 {
1129 hashStream << std::hex << c;
1130 }
1131 // Add the vendor and device id too for good measure.
1132 hashStream << std::hex << mPhysicalDeviceProperties.vendorID;
1133 hashStream << std::hex << mPhysicalDeviceProperties.deviceID;
1134
1135 const std::string &hashString = hashStream.str();
1136 angle::base::SHA1HashBytes(reinterpret_cast<const unsigned char *>(hashString.c_str()),
1137 hashString.length(), mPipelineCacheVkBlobKey.data());
1138}
1139
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001140angle::Result RendererVk::initPipelineCache(DisplayVk *display)
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001141{
1142 initPipelineCacheVkKey();
1143
1144 egl::BlobCache::Value initialData;
1145 bool success = display->getBlobCache()->get(display->getScratchBuffer(),
1146 mPipelineCacheVkBlobKey, &initialData);
1147
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001148 VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {};
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001149
1150 pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001151 pipelineCacheCreateInfo.flags = 0;
1152 pipelineCacheCreateInfo.initialDataSize = success ? initialData.size() : 0;
1153 pipelineCacheCreateInfo.pInitialData = success ? initialData.data() : nullptr;
1154
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001155 ANGLE_VK_TRY(display, mPipelineCache.init(mDevice, pipelineCacheCreateInfo));
Jamie Madill7c985f52018-11-29 18:16:17 -05001156 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001157}
1158
Jamie Madillacccc6c2016-05-03 17:22:10 -04001159void RendererVk::ensureCapsInitialized() const
1160{
1161 if (!mCapsInitialized)
1162 {
Shahbaz Youssefic2b576d2018-10-12 14:45:34 -04001163 ASSERT(mCurrentQueueFamilyIndex < mQueueFamilyProperties.size());
1164 vk::GenerateCaps(mPhysicalDeviceProperties, mPhysicalDeviceFeatures,
1165 mQueueFamilyProperties[mCurrentQueueFamilyIndex], mNativeTextureCaps,
Jamie Madill30b5d842018-08-31 17:19:12 -04001166 &mNativeCaps, &mNativeExtensions, &mNativeLimitations);
Jamie Madillacccc6c2016-05-03 17:22:10 -04001167 mCapsInitialized = true;
1168 }
1169}
1170
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001171void RendererVk::getSubmitWaitSemaphores(
1172 vk::Context *context,
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001173 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> *waitSemaphores,
1174 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> *waitStageMasks)
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001175{
1176 if (mSubmitLastSignaledSemaphore.getSemaphore())
1177 {
1178 waitSemaphores->push_back(mSubmitLastSignaledSemaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001179 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001180
1181 // Return the semaphore to the pool (which will remain valid and unused until the
1182 // queue it's about to be waited on has finished execution).
1183 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1184 }
1185
1186 for (vk::SemaphoreHelper &semaphore : mSubmitWaitSemaphores)
1187 {
1188 waitSemaphores->push_back(semaphore.getSemaphore()->getHandle());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001189 waitStageMasks->push_back(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
1190
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001191 mSubmitSemaphorePool.freeSemaphore(context, &semaphore);
1192 }
1193 mSubmitWaitSemaphores.clear();
1194}
1195
Jamie Madillacccc6c2016-05-03 17:22:10 -04001196const gl::Caps &RendererVk::getNativeCaps() const
1197{
1198 ensureCapsInitialized();
1199 return mNativeCaps;
1200}
1201
1202const gl::TextureCapsMap &RendererVk::getNativeTextureCaps() const
1203{
1204 ensureCapsInitialized();
1205 return mNativeTextureCaps;
1206}
1207
1208const gl::Extensions &RendererVk::getNativeExtensions() const
1209{
1210 ensureCapsInitialized();
1211 return mNativeExtensions;
1212}
1213
1214const gl::Limitations &RendererVk::getNativeLimitations() const
1215{
1216 ensureCapsInitialized();
1217 return mNativeLimitations;
1218}
1219
Luc Ferrondaedf4d2018-03-16 09:28:53 -04001220uint32_t RendererVk::getMaxActiveTextures()
1221{
1222 // TODO(lucferron): expose this limitation to GL in Context Caps
1223 return std::min<uint32_t>(mPhysicalDeviceProperties.limits.maxPerStageDescriptorSamplers,
1224 gl::IMPLEMENTATION_MAX_ACTIVE_TEXTURES);
1225}
1226
Jamie Madill49ac74b2017-12-21 14:42:33 -05001227const vk::CommandPool &RendererVk::getCommandPool() const
Jamie Madill4d0bf552016-12-28 15:45:24 -05001228{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001229 return mCommandPool;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001230}
1231
Jamie Madill21061022018-07-12 23:56:30 -04001232angle::Result RendererVk::finish(vk::Context *context)
Jamie Madill4d0bf552016-12-28 15:45:24 -05001233{
Jamie Madill1f46bc12018-02-20 16:09:43 -05001234 if (!mCommandGraph.empty())
Jamie Madill49ac74b2017-12-21 14:42:33 -05001235 {
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001236 TRACE_EVENT0("gpu.angle", "RendererVk::finish");
1237
Luc Ferron1617e692018-07-11 11:08:19 -04001238 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1239 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001240
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001241 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001242 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1243 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001244
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001245 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001246 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001247 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1248 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001249 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001250 submitInfo.commandBufferCount = 1;
Luc Ferron1617e692018-07-11 11:08:19 -04001251 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001252 submitInfo.signalSemaphoreCount = 0;
1253 submitInfo.pSignalSemaphores = nullptr;
Jamie Madill4d0bf552016-12-28 15:45:24 -05001254
Jamie Madill21061022018-07-12 23:56:30 -04001255 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBatch.get())));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001256 }
Jamie Madill4d0bf552016-12-28 15:45:24 -05001257
Jamie Madill4c26fc22017-02-24 11:04:10 -05001258 ASSERT(mQueue != VK_NULL_HANDLE);
Jamie Madill21061022018-07-12 23:56:30 -04001259 ANGLE_VK_TRY(context, vkQueueWaitIdle(mQueue));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001260 freeAllInFlightResources();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001261
1262 if (mGpuEventsEnabled)
1263 {
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001264 // This loop should in practice execute once since the queue is already idle.
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001265 while (mInFlightGpuEventQueries.size() > 0)
1266 {
1267 ANGLE_TRY(checkCompletedGpuEvents(context));
1268 }
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001269 // Recalculate the CPU/GPU time difference to account for clock drifting. Avoid unnecessary
1270 // synchronization if there is no event to be adjusted (happens when finish() gets called
1271 // multiple times towards the end of the application).
1272 if (mGpuEvents.size() > 0)
1273 {
1274 ANGLE_TRY(synchronizeCpuGpuTime(context));
1275 }
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001276 }
1277
Jamie Madill7c985f52018-11-29 18:16:17 -05001278 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001279}
1280
Jamie Madill0c0dc342017-03-24 14:18:51 -04001281void RendererVk::freeAllInFlightResources()
1282{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001283 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill0c0dc342017-03-24 14:18:51 -04001284 {
Yuly Novikovb56ddbb2018-11-02 16:53:18 -04001285 // On device loss we need to wait for fence to be signaled before destroying it
1286 if (mDeviceLost)
1287 {
1288 VkResult status = batch.fence.wait(mDevice, kMaxFenceWaitTimeNs);
1289 // If wait times out, it is probably not possible to recover from lost device
1290 ASSERT(status == VK_SUCCESS || status == VK_ERROR_DEVICE_LOST);
1291 }
Jamie Madill49ac74b2017-12-21 14:42:33 -05001292 batch.fence.destroy(mDevice);
Tobin Ehlis05459e02019-01-17 12:25:54 -05001293 batch.commandPool.destroy(mDevice, &mAllocationCallbacks);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001294 }
1295 mInFlightCommands.clear();
1296
1297 for (auto &garbage : mGarbage)
1298 {
Jamie Madille88ec8e2017-10-31 17:18:14 -04001299 garbage.destroy(mDevice);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001300 }
1301 mGarbage.clear();
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001302
1303 mLastCompletedQueueSerial = mLastSubmittedQueueSerial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001304}
1305
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001306angle::Result RendererVk::checkCompletedCommands(vk::Context *context)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001307{
Jamie Madill49ac74b2017-12-21 14:42:33 -05001308 int finishedCount = 0;
Jamie Madillf651c772017-02-21 15:03:51 -05001309
Jamie Madill49ac74b2017-12-21 14:42:33 -05001310 for (CommandBatch &batch : mInFlightCommands)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001311 {
Yuly Novikov27780292018-11-09 11:19:49 -05001312 VkResult result = batch.fence.getStatus(mDevice);
1313 if (result == VK_NOT_READY)
1314 {
Jamie Madill0c0dc342017-03-24 14:18:51 -04001315 break;
Yuly Novikov27780292018-11-09 11:19:49 -05001316 }
1317 ANGLE_VK_TRY(context, result);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001318
Jamie Madill49ac74b2017-12-21 14:42:33 -05001319 ASSERT(batch.serial > mLastCompletedQueueSerial);
1320 mLastCompletedQueueSerial = batch.serial;
Jamie Madill0c0dc342017-03-24 14:18:51 -04001321
Jamie Madill49ac74b2017-12-21 14:42:33 -05001322 batch.fence.destroy(mDevice);
Tobin Ehlis05459e02019-01-17 12:25:54 -05001323 batch.commandPool.destroy(mDevice, &mAllocationCallbacks);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001324 ++finishedCount;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001325 }
1326
Jamie Madill49ac74b2017-12-21 14:42:33 -05001327 mInFlightCommands.erase(mInFlightCommands.begin(), mInFlightCommands.begin() + finishedCount);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001328
1329 size_t freeIndex = 0;
1330 for (; freeIndex < mGarbage.size(); ++freeIndex)
1331 {
Jamie Madill49ac74b2017-12-21 14:42:33 -05001332 if (!mGarbage[freeIndex].destroyIfComplete(mDevice, mLastCompletedQueueSerial))
Jamie Madill0c0dc342017-03-24 14:18:51 -04001333 break;
1334 }
1335
1336 // Remove the entries from the garbage list - they should be ready to go.
1337 if (freeIndex > 0)
1338 {
1339 mGarbage.erase(mGarbage.begin(), mGarbage.begin() + freeIndex);
Jamie Madillf651c772017-02-21 15:03:51 -05001340 }
1341
Jamie Madill7c985f52018-11-29 18:16:17 -05001342 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001343}
1344
Jamie Madill21061022018-07-12 23:56:30 -04001345angle::Result RendererVk::submitFrame(vk::Context *context,
1346 const VkSubmitInfo &submitInfo,
1347 vk::CommandBuffer &&commandBuffer)
Jamie Madill4c26fc22017-02-24 11:04:10 -05001348{
Tobin Ehlis573f76b2018-05-03 11:10:44 -06001349 TRACE_EVENT0("gpu.angle", "RendererVk::submitFrame");
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001350 VkFenceCreateInfo fenceInfo = {};
Jamie Madillb980c562018-11-27 11:34:27 -05001351 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1352 fenceInfo.flags = 0;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001353
Tobin Ehlis05459e02019-01-17 12:25:54 -05001354 vk::ScopedCustomAllocation<CommandBatch> scopedBatch(mDevice, &mAllocationCallbacks);
Jamie Madillbea35a62018-07-05 11:54:10 -04001355 CommandBatch &batch = scopedBatch.get();
Yuly Novikov27780292018-11-09 11:19:49 -05001356 ANGLE_VK_TRY(context, batch.fence.init(mDevice, fenceInfo));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001357
Jamie Madill21061022018-07-12 23:56:30 -04001358 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, batch.fence.getHandle()));
Jamie Madill4c26fc22017-02-24 11:04:10 -05001359
1360 // Store this command buffer in the in-flight list.
Jamie Madill49ac74b2017-12-21 14:42:33 -05001361 batch.commandPool = std::move(mCommandPool);
Tobin Ehlis05459e02019-01-17 12:25:54 -05001362 batch.poolAllocator = std::move(mPoolAllocator);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001363 batch.serial = mCurrentQueueSerial;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001364
Jamie Madillbea35a62018-07-05 11:54:10 -04001365 mInFlightCommands.emplace_back(scopedBatch.release());
Jamie Madill0c0dc342017-03-24 14:18:51 -04001366
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001367 // CPU should be throttled to avoid mInFlightCommands from growing too fast. That is done on
1368 // swap() though, and there could be multiple submissions in between (through glFlush() calls),
Shahbaz Youssefi611bbaa2018-12-06 01:59:53 +01001369 // so the limit is larger than the expected number of images. The
1370 // InterleavedAttributeDataBenchmark perf test for example issues a large number of flushes.
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001371 ASSERT(mInFlightCommands.size() <= kInFlightCommandsLimit);
Jamie Madill0c0dc342017-03-24 14:18:51 -04001372
Jamie Madill85ca1892019-01-16 13:27:15 -05001373 nextSerial();
Jamie Madill0c0dc342017-03-24 14:18:51 -04001374
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001375 ANGLE_TRY(checkCompletedCommands(context));
Jamie Madill0c0dc342017-03-24 14:18:51 -04001376
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001377 if (mGpuEventsEnabled)
1378 {
1379 ANGLE_TRY(checkCompletedGpuEvents(context));
1380 }
1381
Jamie Madill49ac74b2017-12-21 14:42:33 -05001382 // Simply null out the command buffer here - it was allocated using the command pool.
1383 commandBuffer.releaseHandle();
1384
1385 // Reallocate the command pool for next frame.
1386 // TODO(jmadill): Consider reusing command pools.
Tobin Ehlis05459e02019-01-17 12:25:54 -05001387 InitPoolAllocationCallbacks(&mPoolAllocator, &mAllocationCallbacks);
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001388 VkCommandPoolCreateInfo poolInfo = {};
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001389 poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001390 poolInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001391 poolInfo.queueFamilyIndex = mCurrentQueueFamilyIndex;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001392
Tobin Ehlis05459e02019-01-17 12:25:54 -05001393 ANGLE_VK_TRY(context, mCommandPool.init(mDevice, poolInfo, &mAllocationCallbacks));
Jamie Madill7c985f52018-11-29 18:16:17 -05001394 return angle::Result::Continue;
Jamie Madill4c26fc22017-02-24 11:04:10 -05001395}
1396
Jamie Madill85ca1892019-01-16 13:27:15 -05001397void RendererVk::nextSerial()
1398{
1399 // Increment the queue serial. If this fails, we should restart ANGLE.
1400 mLastSubmittedQueueSerial = mCurrentQueueSerial;
1401 mCurrentQueueSerial = mQueueSerialFactory.generate();
1402
1403 // Notify the Contexts that they should be starting new command buffers.
1404 // We use one command pool per serial/submit associated with this VkQueue. We can also
1405 // have multiple Contexts sharing one VkQueue. In ContextVk::setupDraw we don't explicitly
1406 // check for a new serial when starting a new command buffer. We just check that the current
1407 // recording command buffer is valid. Thus we need to explicitly notify every other Context
1408 // using this VkQueue that they their current command buffer is no longer valid.
1409 for (gl::Context *context : mDisplay->getContextSet())
1410 {
1411 ContextVk *contextVk = vk::GetImpl(context);
1412 contextVk->onCommandBufferFinished();
1413 }
1414}
1415
Jamie Madillaaca96e2018-06-12 10:19:48 -04001416bool RendererVk::isSerialInUse(Serial serial) const
Jamie Madill97760352017-11-09 13:08:29 -05001417{
1418 return serial > mLastCompletedQueueSerial;
1419}
1420
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001421angle::Result RendererVk::finishToSerial(vk::Context *context, Serial serial)
1422{
1423 if (!isSerialInUse(serial) || mInFlightCommands.empty())
1424 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001425 return angle::Result::Continue;
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001426 }
1427
1428 // Find the first batch with serial equal to or bigger than given serial (note that
1429 // the batch serials are unique, otherwise upper-bound would have been necessary).
1430 size_t batchIndex = mInFlightCommands.size() - 1;
1431 for (size_t i = 0; i < mInFlightCommands.size(); ++i)
1432 {
1433 if (mInFlightCommands[i].serial >= serial)
1434 {
1435 batchIndex = i;
1436 break;
1437 }
1438 }
1439 const CommandBatch &batch = mInFlightCommands[batchIndex];
1440
1441 // Wait for it finish
Yuly Novikov27780292018-11-09 11:19:49 -05001442 ANGLE_VK_TRY(context, batch.fence.wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefic4765aa2018-10-12 14:40:29 -04001443
1444 // Clean up finished batches.
1445 return checkCompletedCommands(context);
1446}
1447
Jamie Madill21061022018-07-12 23:56:30 -04001448angle::Result RendererVk::getCompatibleRenderPass(vk::Context *context,
1449 const vk::RenderPassDesc &desc,
1450 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001451{
Jamie Madill21061022018-07-12 23:56:30 -04001452 return mRenderPassCache.getCompatibleRenderPass(context, mCurrentQueueSerial, desc,
Jamie Madill9f2a8612017-11-30 12:43:09 -05001453 renderPassOut);
1454}
1455
Jamie Madill21061022018-07-12 23:56:30 -04001456angle::Result RendererVk::getRenderPassWithOps(vk::Context *context,
1457 const vk::RenderPassDesc &desc,
1458 const vk::AttachmentOpsArray &ops,
1459 vk::RenderPass **renderPassOut)
Jamie Madill9f2a8612017-11-30 12:43:09 -05001460{
Jamie Madill21061022018-07-12 23:56:30 -04001461 return mRenderPassCache.getRenderPassWithOps(context, mCurrentQueueSerial, desc, ops,
Jamie Madillbef918c2017-12-13 13:11:30 -05001462 renderPassOut);
Jamie Madill9f2a8612017-11-30 12:43:09 -05001463}
1464
Jamie Madilla5e06072018-05-18 14:36:05 -04001465vk::CommandGraph *RendererVk::getCommandGraph()
Jamie Madill49ac74b2017-12-21 14:42:33 -05001466{
Jamie Madilla5e06072018-05-18 14:36:05 -04001467 return &mCommandGraph;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001468}
1469
Jamie Madill21061022018-07-12 23:56:30 -04001470angle::Result RendererVk::flushCommandGraph(vk::Context *context, vk::CommandBuffer *commandBatch)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001471{
Jamie Madill21061022018-07-12 23:56:30 -04001472 return mCommandGraph.submitCommands(context, mCurrentQueueSerial, &mRenderPassCache,
Jamie Madill1f46bc12018-02-20 16:09:43 -05001473 &mCommandPool, commandBatch);
Jamie Madill49ac74b2017-12-21 14:42:33 -05001474}
1475
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001476angle::Result RendererVk::flush(vk::Context *context)
Jamie Madill49ac74b2017-12-21 14:42:33 -05001477{
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001478 if (mCommandGraph.empty())
1479 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001480 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001481 }
1482
Shahbaz Youssefi61656022018-10-24 15:00:50 -04001483 TRACE_EVENT0("gpu.angle", "RendererVk::flush");
1484
Jamie Madillbea35a62018-07-05 11:54:10 -04001485 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1486 ANGLE_TRY(flushCommandGraph(context, &commandBatch.get()));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001487
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001488 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001489 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1490 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001491
1492 // On every flush, create a semaphore to be signaled. On the next submission, this semaphore
1493 // will be waited on.
1494 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &mSubmitLastSignaledSemaphore));
Jamie Madill49ac74b2017-12-21 14:42:33 -05001495
Shahbaz Youssefi06270c92018-10-03 17:00:25 -04001496 VkSubmitInfo submitInfo = {};
Jamie Madill49ac74b2017-12-21 14:42:33 -05001497 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001498 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1499 submitInfo.pWaitSemaphores = waitSemaphores.data();
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001500 submitInfo.pWaitDstStageMask = waitStageMasks.data();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001501 submitInfo.commandBufferCount = 1;
Jamie Madillbea35a62018-07-05 11:54:10 -04001502 submitInfo.pCommandBuffers = commandBatch.get().ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001503 submitInfo.signalSemaphoreCount = 1;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001504 submitInfo.pSignalSemaphores = mSubmitLastSignaledSemaphore.getSemaphore()->ptr();
Jamie Madill49ac74b2017-12-21 14:42:33 -05001505
Jamie Madill21061022018-07-12 23:56:30 -04001506 ANGLE_TRY(submitFrame(context, submitInfo, commandBatch.release()));
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001507
Jamie Madill7c985f52018-11-29 18:16:17 -05001508 return angle::Result::Continue;
Jamie Madill49ac74b2017-12-21 14:42:33 -05001509}
1510
Jamie Madill78feddc2018-04-27 11:45:05 -04001511Serial RendererVk::issueShaderSerial()
Jamie Madillf2f6d372018-01-10 21:37:23 -05001512{
Jamie Madill78feddc2018-04-27 11:45:05 -04001513 return mShaderSerialFactory.generate();
Jamie Madillf2f6d372018-01-10 21:37:23 -05001514}
1515
Jamie Madill21061022018-07-12 23:56:30 -04001516angle::Result RendererVk::getDescriptorSetLayout(
1517 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001518 const vk::DescriptorSetLayoutDesc &desc,
1519 vk::BindingPointer<vk::DescriptorSetLayout> *descriptorSetLayoutOut)
1520{
Jamie Madill21061022018-07-12 23:56:30 -04001521 return mDescriptorSetLayoutCache.getDescriptorSetLayout(context, desc, descriptorSetLayoutOut);
Jamie Madill9b168d02018-06-13 13:25:32 -04001522}
1523
Jamie Madill21061022018-07-12 23:56:30 -04001524angle::Result RendererVk::getPipelineLayout(
1525 vk::Context *context,
Jamie Madill9b168d02018-06-13 13:25:32 -04001526 const vk::PipelineLayoutDesc &desc,
1527 const vk::DescriptorSetLayoutPointerArray &descriptorSetLayouts,
1528 vk::BindingPointer<vk::PipelineLayout> *pipelineLayoutOut)
1529{
Jamie Madill21061022018-07-12 23:56:30 -04001530 return mPipelineLayoutCache.getPipelineLayout(context, desc, descriptorSetLayouts,
Jamie Madill9b168d02018-06-13 13:25:32 -04001531 pipelineLayoutOut);
1532}
1533
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001534angle::Result RendererVk::syncPipelineCacheVk(DisplayVk *displayVk)
1535{
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001536 ASSERT(mPipelineCache.valid());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001537
1538 if (--mPipelineCacheVkUpdateTimeout > 0)
1539 {
Jamie Madill7c985f52018-11-29 18:16:17 -05001540 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001541 }
1542
1543 mPipelineCacheVkUpdateTimeout = kPipelineCacheVkUpdatePeriod;
1544
1545 // Get the size of the cache.
1546 size_t pipelineCacheSize = 0;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001547 VkResult result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, nullptr);
Yuly Novikov27780292018-11-09 11:19:49 -05001548 if (result != VK_INCOMPLETE)
1549 {
1550 ANGLE_VK_TRY(displayVk, result);
1551 }
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001552
1553 angle::MemoryBuffer *pipelineCacheData = nullptr;
1554 ANGLE_VK_CHECK_ALLOC(displayVk,
1555 displayVk->getScratchBuffer(pipelineCacheSize, &pipelineCacheData));
1556
1557 size_t originalPipelineCacheSize = pipelineCacheSize;
Jamie Madilldc65c5b2018-11-21 11:07:26 -05001558 result = mPipelineCache.getCacheData(mDevice, &pipelineCacheSize, pipelineCacheData->data());
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001559 // Note: currently we don't accept incomplete as we don't expect it (the full size of cache
1560 // was determined just above), so receiving it hints at an implementation bug we would want
1561 // to know about early.
Yuly Novikov27780292018-11-09 11:19:49 -05001562 ASSERT(result != VK_INCOMPLETE);
1563 ANGLE_VK_TRY(displayVk, result);
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001564
1565 // If vkGetPipelineCacheData ends up writing fewer bytes than requested, zero out the rest of
1566 // the buffer to avoid leaking garbage memory.
1567 ASSERT(pipelineCacheSize <= originalPipelineCacheSize);
1568 if (pipelineCacheSize < originalPipelineCacheSize)
1569 {
1570 memset(pipelineCacheData->data() + pipelineCacheSize, 0,
1571 originalPipelineCacheSize - pipelineCacheSize);
1572 }
1573
1574 displayVk->getBlobCache()->putApplication(mPipelineCacheVkBlobKey, *pipelineCacheData);
1575
Jamie Madill7c985f52018-11-29 18:16:17 -05001576 return angle::Result::Continue;
Shahbaz Youssefi996628a2018-09-24 16:39:26 -04001577}
1578
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001579angle::Result RendererVk::allocateSubmitWaitSemaphore(vk::Context *context,
1580 const vk::Semaphore **outSemaphore)
1581{
1582 ASSERT(mSubmitWaitSemaphores.size() < mSubmitWaitSemaphores.max_size());
1583
1584 vk::SemaphoreHelper semaphore;
1585 ANGLE_TRY(mSubmitSemaphorePool.allocateSemaphore(context, &semaphore));
1586
1587 mSubmitWaitSemaphores.push_back(std::move(semaphore));
1588 *outSemaphore = mSubmitWaitSemaphores.back().getSemaphore();
1589
Jamie Madill7c985f52018-11-29 18:16:17 -05001590 return angle::Result::Continue;
Shahbaz Youssefi3a482172018-10-11 10:34:44 -04001591}
1592
1593const vk::Semaphore *RendererVk::getSubmitLastSignaledSemaphore(vk::Context *context)
1594{
1595 const vk::Semaphore *semaphore = mSubmitLastSignaledSemaphore.getSemaphore();
1596
1597 // Return the semaphore to the pool (which will remain valid and unused until the
1598 // queue it's about to be waited on has finished execution). The caller is about
1599 // to wait on it.
1600 mSubmitSemaphorePool.freeSemaphore(context, &mSubmitLastSignaledSemaphore);
1601
1602 return semaphore;
1603}
1604
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001605angle::Result RendererVk::getTimestamp(vk::Context *context, uint64_t *timestampOut)
1606{
1607 // The intent of this function is to query the timestamp without stalling the GPU. Currently,
1608 // that seems impossible, so instead, we are going to make a small submission with just a
1609 // timestamp query. First, the disjoint timer query extension says:
1610 //
1611 // > This will return the GL time after all previous commands have reached the GL server but
1612 // have not yet necessarily executed.
1613 //
1614 // The previous commands are stored in the command graph at the moment and are not yet flushed.
1615 // The wording allows us to make a submission to get the timestamp without performing a flush.
1616 //
1617 // Second:
1618 //
1619 // > By using a combination of this synchronous get command and the asynchronous timestamp query
1620 // object target, applications can measure the latency between when commands reach the GL server
1621 // and when they are realized in the framebuffer.
1622 //
1623 // This fits with the above strategy as well, although inevitably we are possibly introducing a
1624 // GPU bubble. This function directly generates a command buffer and submits it instead of
1625 // using the other member functions. This is to avoid changing any state, such as the queue
1626 // serial.
1627
1628 // Create a query used to receive the GPU timestamp
1629 vk::Scoped<vk::DynamicQueryPool> timestampQueryPool(mDevice);
1630 vk::QueryHelper timestampQuery;
1631 ANGLE_TRY(timestampQueryPool.get().init(context, VK_QUERY_TYPE_TIMESTAMP, 1));
1632 ANGLE_TRY(timestampQueryPool.get().allocateQuery(context, &timestampQuery));
1633
1634 // Record the command buffer
1635 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1636 vk::CommandBuffer &commandBuffer = commandBatch.get();
1637
1638 VkCommandBufferAllocateInfo commandBufferInfo = {};
1639 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1640 commandBufferInfo.commandPool = mCommandPool.getHandle();
1641 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1642 commandBufferInfo.commandBufferCount = 1;
1643
Yuly Novikov27780292018-11-09 11:19:49 -05001644 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001645
1646 VkCommandBufferBeginInfo beginInfo = {};
1647 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1648 beginInfo.flags = 0;
1649 beginInfo.pInheritanceInfo = nullptr;
1650
Yuly Novikov27780292018-11-09 11:19:49 -05001651 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001652
1653 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1654 timestampQuery.getQuery(), 1);
1655 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1656 timestampQuery.getQueryPool()->getHandle(),
1657 timestampQuery.getQuery());
1658
Yuly Novikov27780292018-11-09 11:19:49 -05001659 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001660
1661 // Create fence for the submission
1662 VkFenceCreateInfo fenceInfo = {};
1663 fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1664 fenceInfo.flags = 0;
1665
1666 vk::Scoped<vk::Fence> fence(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001667 ANGLE_VK_TRY(context, fence.get().init(mDevice, fenceInfo));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001668
1669 // Submit the command buffer
1670 VkSubmitInfo submitInfo = {};
1671 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1672 submitInfo.waitSemaphoreCount = 0;
1673 submitInfo.pWaitSemaphores = nullptr;
1674 submitInfo.pWaitDstStageMask = nullptr;
1675 submitInfo.commandBufferCount = 1;
1676 submitInfo.pCommandBuffers = commandBuffer.ptr();
1677 submitInfo.signalSemaphoreCount = 0;
1678 submitInfo.pSignalSemaphores = nullptr;
1679
1680 ANGLE_VK_TRY(context, vkQueueSubmit(mQueue, 1, &submitInfo, fence.get().getHandle()));
1681
1682 // Wait for the submission to finish. Given no semaphores, there is hope that it would execute
1683 // in parallel with what's already running on the GPU.
Yuly Novikov27780292018-11-09 11:19:49 -05001684 ANGLE_VK_TRY(context, fence.get().wait(mDevice, kMaxFenceWaitTimeNs));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001685
1686 // Get the query results
1687 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1688
Yuly Novikov27780292018-11-09 11:19:49 -05001689 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1690 mDevice, timestampQuery.getQuery(), 1, sizeof(*timestampOut),
1691 timestampOut, sizeof(*timestampOut), queryFlags));
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001692
1693 timestampQueryPool.get().freeQuery(context, &timestampQuery);
1694
Jamie Madill7c985f52018-11-29 18:16:17 -05001695 return angle::Result::Continue;
Shahbaz Youssefi749589f2018-10-25 12:48:49 -04001696}
1697
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05001698// These functions look at the mandatory format for support, and fallback to querying the device (if
1699// necessary) to test the availability of the bits.
1700bool RendererVk::hasLinearTextureFormatFeatureBits(VkFormat format,
1701 const VkFormatFeatureFlags featureBits)
1702{
1703 return hasFormatFeatureBits<&VkFormatProperties::linearTilingFeatures>(format, featureBits);
1704}
1705
1706bool RendererVk::hasTextureFormatFeatureBits(VkFormat format,
1707 const VkFormatFeatureFlags featureBits)
1708{
1709 return hasFormatFeatureBits<&VkFormatProperties::optimalTilingFeatures>(format, featureBits);
1710}
1711
1712bool RendererVk::hasBufferFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
1713{
1714 return hasFormatFeatureBits<&VkFormatProperties::bufferFeatures>(format, featureBits);
1715}
1716
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001717angle::Result RendererVk::synchronizeCpuGpuTime(vk::Context *context)
1718{
1719 ASSERT(mGpuEventsEnabled);
1720
1721 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1722 ASSERT(platform);
1723
1724 // To synchronize CPU and GPU times, we need to get the CPU timestamp as close as possible to
1725 // the GPU timestamp. The process of getting the GPU timestamp is as follows:
1726 //
1727 // CPU GPU
1728 //
1729 // Record command buffer
1730 // with timestamp query
1731 //
1732 // Submit command buffer
1733 //
1734 // Post-submission work Begin execution
1735 //
Tobin Ehlis05459e02019-01-17 12:25:54 -05001736 // ???? Write timestamp Tgpu
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001737 //
1738 // ???? End execution
1739 //
1740 // ???? Return query results
1741 //
1742 // ????
1743 //
1744 // Get query results
1745 //
1746 // The areas of unknown work (????) on the CPU indicate that the CPU may or may not have
1747 // finished post-submission work while the GPU is executing in parallel. With no further work,
1748 // querying CPU timestamps before submission and after getting query results give the bounds to
1749 // Tgpu, which could be quite large.
1750 //
1751 // Using VkEvents, the GPU can be made to wait for the CPU and vice versa, in an effort to
1752 // reduce this range. This function implements the following procedure:
1753 //
1754 // CPU GPU
1755 //
1756 // Record command buffer
1757 // with timestamp query
1758 //
1759 // Submit command buffer
1760 //
1761 // Post-submission work Begin execution
1762 //
1763 // ???? Set Event GPUReady
1764 //
1765 // Wait on Event GPUReady Wait on Event CPUReady
1766 //
1767 // Get CPU Time Ts Wait on Event CPUReady
1768 //
1769 // Set Event CPUReady Wait on Event CPUReady
1770 //
1771 // Get CPU Time Tcpu Get GPU Time Tgpu
1772 //
1773 // Wait on Event GPUDone Set Event GPUDone
1774 //
1775 // Get CPU Time Te End Execution
1776 //
1777 // Idle Return query results
1778 //
1779 // Get query results
1780 //
1781 // If Te-Ts > epsilon, a GPU or CPU interruption can be assumed and the operation can be
1782 // retried. Once Te-Ts < epsilon, Tcpu can be taken to presumably match Tgpu. Finding an
1783 // epsilon that's valid for all devices may be difficult, so the loop can be performed only a
1784 // limited number of times and the Tcpu,Tgpu pair corresponding to smallest Te-Ts used for
1785 // calibration.
1786 //
1787 // Note: Once VK_EXT_calibrated_timestamps is ubiquitous, this should be redone.
1788
1789 // Make sure nothing is running
1790 ASSERT(mCommandGraph.empty());
1791
1792 TRACE_EVENT0("gpu.angle", "RendererVk::synchronizeCpuGpuTime");
1793
1794 // Create a query used to receive the GPU timestamp
1795 vk::QueryHelper timestampQuery;
1796 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &timestampQuery));
1797
1798 // Create the three events
1799 VkEventCreateInfo eventCreateInfo = {};
1800 eventCreateInfo.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO;
1801 eventCreateInfo.flags = 0;
1802
1803 vk::Scoped<vk::Event> cpuReady(mDevice), gpuReady(mDevice), gpuDone(mDevice);
Yuly Novikov27780292018-11-09 11:19:49 -05001804 ANGLE_VK_TRY(context, cpuReady.get().init(mDevice, eventCreateInfo));
1805 ANGLE_VK_TRY(context, gpuReady.get().init(mDevice, eventCreateInfo));
1806 ANGLE_VK_TRY(context, gpuDone.get().init(mDevice, eventCreateInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001807
1808 constexpr uint32_t kRetries = 10;
1809
1810 // Time suffixes used are S for seconds and Cycles for cycles
1811 double tightestRangeS = 1e6f;
1812 double TcpuS = 0;
1813 uint64_t TgpuCycles = 0;
1814 for (uint32_t i = 0; i < kRetries; ++i)
1815 {
1816 // Reset the events
Yuly Novikov27780292018-11-09 11:19:49 -05001817 ANGLE_VK_TRY(context, cpuReady.get().reset(mDevice));
1818 ANGLE_VK_TRY(context, gpuReady.get().reset(mDevice));
1819 ANGLE_VK_TRY(context, gpuDone.get().reset(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001820
1821 // Record the command buffer
1822 vk::Scoped<vk::CommandBuffer> commandBatch(mDevice);
1823 vk::CommandBuffer &commandBuffer = commandBatch.get();
1824
1825 VkCommandBufferAllocateInfo commandBufferInfo = {};
1826 commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1827 commandBufferInfo.commandPool = mCommandPool.getHandle();
1828 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1829 commandBufferInfo.commandBufferCount = 1;
1830
Yuly Novikov27780292018-11-09 11:19:49 -05001831 ANGLE_VK_TRY(context, commandBuffer.init(mDevice, commandBufferInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001832
1833 VkCommandBufferBeginInfo beginInfo = {};
1834 beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1835 beginInfo.flags = 0;
1836 beginInfo.pInheritanceInfo = nullptr;
1837
Yuly Novikov27780292018-11-09 11:19:49 -05001838 ANGLE_VK_TRY(context, commandBuffer.begin(beginInfo));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001839
1840 commandBuffer.setEvent(gpuReady.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1841 commandBuffer.waitEvents(1, cpuReady.get().ptr(), VK_PIPELINE_STAGE_HOST_BIT,
1842 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, nullptr, 0, nullptr, 0,
1843 nullptr);
1844
1845 commandBuffer.resetQueryPool(timestampQuery.getQueryPool()->getHandle(),
1846 timestampQuery.getQuery(), 1);
1847 commandBuffer.writeTimestamp(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1848 timestampQuery.getQueryPool()->getHandle(),
1849 timestampQuery.getQuery());
1850
1851 commandBuffer.setEvent(gpuDone.get(), VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT);
1852
Yuly Novikov27780292018-11-09 11:19:49 -05001853 ANGLE_VK_TRY(context, commandBuffer.end());
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001854
1855 // Submit the command buffer
1856 angle::FixedVector<VkSemaphore, kMaxWaitSemaphores> waitSemaphores;
1857 angle::FixedVector<VkPipelineStageFlags, kMaxWaitSemaphores> waitStageMasks;
1858 getSubmitWaitSemaphores(context, &waitSemaphores, &waitStageMasks);
1859
1860 VkSubmitInfo submitInfo = {};
1861 submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1862 submitInfo.waitSemaphoreCount = static_cast<uint32_t>(waitSemaphores.size());
1863 submitInfo.pWaitSemaphores = waitSemaphores.data();
1864 submitInfo.pWaitDstStageMask = waitStageMasks.data();
1865 submitInfo.commandBufferCount = 1;
1866 submitInfo.pCommandBuffers = commandBuffer.ptr();
1867 submitInfo.signalSemaphoreCount = 0;
1868 submitInfo.pSignalSemaphores = nullptr;
1869
1870 ANGLE_TRY(submitFrame(context, submitInfo, std::move(commandBuffer)));
1871
1872 // Wait for GPU to be ready. This is a short busy wait.
Yuly Novikov27780292018-11-09 11:19:49 -05001873 VkResult result = VK_EVENT_RESET;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001874 do
1875 {
Yuly Novikov27780292018-11-09 11:19:49 -05001876 result = gpuReady.get().getStatus(mDevice);
1877 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1878 {
1879 ANGLE_VK_TRY(context, result);
1880 }
1881 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001882
1883 double TsS = platform->monotonicallyIncreasingTime(platform);
1884
1885 // Tell the GPU to go ahead with the timestamp query.
Yuly Novikov27780292018-11-09 11:19:49 -05001886 ANGLE_VK_TRY(context, cpuReady.get().set(mDevice));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001887 double cpuTimestampS = platform->monotonicallyIncreasingTime(platform);
1888
1889 // Wait for GPU to be done. Another short busy wait.
1890 do
1891 {
Yuly Novikov27780292018-11-09 11:19:49 -05001892 result = gpuDone.get().getStatus(mDevice);
1893 if (result != VK_EVENT_SET && result != VK_EVENT_RESET)
1894 {
1895 ANGLE_VK_TRY(context, result);
1896 }
1897 } while (result == VK_EVENT_RESET);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001898
1899 double TeS = platform->monotonicallyIncreasingTime(platform);
1900
1901 // Get the query results
1902 ANGLE_TRY(finishToSerial(context, getLastSubmittedQueueSerial()));
1903
1904 constexpr VkQueryResultFlags queryFlags = VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT;
1905
1906 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001907 ANGLE_VK_TRY(context, timestampQuery.getQueryPool()->getResults(
1908 mDevice, timestampQuery.getQuery(), 1, sizeof(gpuTimestampCycles),
1909 &gpuTimestampCycles, sizeof(gpuTimestampCycles), queryFlags));
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001910
1911 // Use the first timestamp queried as origin.
1912 if (mGpuEventTimestampOrigin == 0)
1913 {
1914 mGpuEventTimestampOrigin = gpuTimestampCycles;
1915 }
1916
1917 // Take these CPU and GPU timestamps if there is better confidence.
1918 double confidenceRangeS = TeS - TsS;
1919 if (confidenceRangeS < tightestRangeS)
1920 {
1921 tightestRangeS = confidenceRangeS;
1922 TcpuS = cpuTimestampS;
1923 TgpuCycles = gpuTimestampCycles;
1924 }
1925 }
1926
1927 mGpuEventQueryPool.freeQuery(context, &timestampQuery);
1928
1929 // timestampPeriod gives nanoseconds/cycle.
1930 double TgpuS = (TgpuCycles - mGpuEventTimestampOrigin) *
1931 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) /
1932 1'000'000'000.0;
1933
1934 flushGpuEvents(TgpuS, TcpuS);
1935
1936 mGpuClockSync.gpuTimestampS = TgpuS;
1937 mGpuClockSync.cpuTimestampS = TcpuS;
1938
Jamie Madill7c985f52018-11-29 18:16:17 -05001939 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001940}
1941
1942angle::Result RendererVk::traceGpuEventImpl(vk::Context *context,
1943 vk::CommandBuffer *commandBuffer,
1944 char phase,
1945 const char *name)
1946{
1947 ASSERT(mGpuEventsEnabled);
1948
1949 GpuEventQuery event;
1950
1951 event.name = name;
1952 event.phase = phase;
1953 event.serial = mCurrentQueueSerial;
1954
1955 ANGLE_TRY(mGpuEventQueryPool.allocateQuery(context, &event.queryPoolIndex, &event.queryIndex));
1956
1957 commandBuffer->resetQueryPool(
1958 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex, 1);
1959 commandBuffer->writeTimestamp(
1960 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
1961 mGpuEventQueryPool.getQueryPool(event.queryPoolIndex)->getHandle(), event.queryIndex);
1962
1963 mInFlightGpuEventQueries.push_back(std::move(event));
1964
Jamie Madill7c985f52018-11-29 18:16:17 -05001965 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001966}
1967
1968angle::Result RendererVk::checkCompletedGpuEvents(vk::Context *context)
1969{
1970 ASSERT(mGpuEventsEnabled);
1971
1972 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
1973 ASSERT(platform);
1974
1975 int finishedCount = 0;
1976
1977 for (GpuEventQuery &eventQuery : mInFlightGpuEventQueries)
1978 {
1979 // Only check the timestamp query if the submission has finished.
1980 if (eventQuery.serial > mLastCompletedQueueSerial)
1981 {
1982 break;
1983 }
1984
1985 // See if the results are available.
1986 uint64_t gpuTimestampCycles = 0;
Yuly Novikov27780292018-11-09 11:19:49 -05001987 VkResult result = mGpuEventQueryPool.getQueryPool(eventQuery.queryPoolIndex)
1988 ->getResults(mDevice, eventQuery.queryIndex, 1,
1989 sizeof(gpuTimestampCycles), &gpuTimestampCycles,
1990 sizeof(gpuTimestampCycles), VK_QUERY_RESULT_64_BIT);
1991 if (result == VK_NOT_READY)
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001992 {
1993 break;
1994 }
Yuly Novikov27780292018-11-09 11:19:49 -05001995 ANGLE_VK_TRY(context, result);
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04001996
1997 mGpuEventQueryPool.freeQuery(context, eventQuery.queryPoolIndex, eventQuery.queryIndex);
1998
1999 GpuEvent event;
2000 event.gpuTimestampCycles = gpuTimestampCycles;
2001 event.name = eventQuery.name;
2002 event.phase = eventQuery.phase;
2003
2004 mGpuEvents.emplace_back(event);
2005
2006 ++finishedCount;
2007 }
2008
2009 mInFlightGpuEventQueries.erase(mInFlightGpuEventQueries.begin(),
2010 mInFlightGpuEventQueries.begin() + finishedCount);
2011
Jamie Madill7c985f52018-11-29 18:16:17 -05002012 return angle::Result::Continue;
Shahbaz Youssefi25224e72018-10-22 11:56:02 -04002013}
2014
2015void RendererVk::flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS)
2016{
2017 if (mGpuEvents.size() == 0)
2018 {
2019 return;
2020 }
2021
2022 angle::PlatformMethods *platform = ANGLEPlatformCurrent();
2023 ASSERT(platform);
2024
2025 // Find the slope of the clock drift for adjustment
2026 double lastGpuSyncTimeS = mGpuClockSync.gpuTimestampS;
2027 double lastGpuSyncDiffS = mGpuClockSync.cpuTimestampS - mGpuClockSync.gpuTimestampS;
2028 double gpuSyncDriftSlope = 0;
2029
2030 double nextGpuSyncTimeS = nextSyncGpuTimestampS;
2031 double nextGpuSyncDiffS = nextSyncCpuTimestampS - nextSyncGpuTimestampS;
2032
2033 // No gpu trace events should have been generated before the clock sync, so if there is no
2034 // "previous" clock sync, there should be no gpu events (i.e. the function early-outs above).
2035 ASSERT(mGpuClockSync.gpuTimestampS != std::numeric_limits<double>::max() &&
2036 mGpuClockSync.cpuTimestampS != std::numeric_limits<double>::max());
2037
2038 gpuSyncDriftSlope =
2039 (nextGpuSyncDiffS - lastGpuSyncDiffS) / (nextGpuSyncTimeS - lastGpuSyncTimeS);
2040
2041 for (const GpuEvent &event : mGpuEvents)
2042 {
2043 double gpuTimestampS =
2044 (event.gpuTimestampCycles - mGpuEventTimestampOrigin) *
2045 static_cast<double>(mPhysicalDeviceProperties.limits.timestampPeriod) * 1e-9;
2046
2047 // Account for clock drift.
2048 gpuTimestampS += lastGpuSyncDiffS + gpuSyncDriftSlope * (gpuTimestampS - lastGpuSyncTimeS);
2049
2050 // Generate the trace now that the GPU timestamp is available and clock drifts are accounted
2051 // for.
2052 static long long eventId = 1;
2053 static const unsigned char *categoryEnabled =
2054 TRACE_EVENT_API_GET_CATEGORY_ENABLED("gpu.angle.gpu");
2055 platform->addTraceEvent(platform, event.phase, categoryEnabled, event.name, eventId++,
2056 gpuTimestampS, 0, nullptr, nullptr, nullptr, TRACE_EVENT_FLAG_NONE);
2057 }
2058
2059 mGpuEvents.clear();
2060}
2061
Shahbaz Youssefi96bd8fd2018-11-30 14:30:18 -05002062template <VkFormatFeatureFlags VkFormatProperties::*features>
2063bool RendererVk::hasFormatFeatureBits(VkFormat format, const VkFormatFeatureFlags featureBits)
2064{
2065 ASSERT(static_cast<uint32_t>(format) < vk::kNumVkFormats);
2066 VkFormatProperties &deviceProperties = mFormatProperties[format];
2067
2068 if (deviceProperties.bufferFeatures == kInvalidFormatFeatureFlags)
2069 {
2070 // If we don't have the actual device features, see if the requested features are mandatory.
2071 // If so, there's no need to query the device.
2072 const VkFormatProperties &mandatoryProperties = vk::GetMandatoryFormatSupport(format);
2073 if (IsMaskFlagSet(mandatoryProperties.*features, featureBits))
2074 {
2075 return true;
2076 }
2077
2078 // Otherwise query the format features and cache it.
2079 vkGetPhysicalDeviceFormatProperties(mPhysicalDevice, format, &deviceProperties);
2080 }
2081
2082 return IsMaskFlagSet(deviceProperties.*features, featureBits);
2083}
2084
Jamie Madillaaca96e2018-06-12 10:19:48 -04002085uint32_t GetUniformBufferDescriptorCount()
2086{
2087 return kUniformBufferDescriptorsPerDescriptorSet;
2088}
2089
Jamie Madill9e54b5a2016-05-25 12:57:39 -04002090} // namespace rx