Skip to content

Commit af028a8

Browse files
authored
Avoid most vulkan initialization for known bad vulkan drivers (flutter#193875)
Adds a short-circuit in vulkan initialization for known bad devices (e.g., IsKnownBadDriver()==True). Adds a callback `should_reject_device` to the Vulkan context initialization to allow callers to specify a fast fail during context creation before the bulk of the Vulkan context creation operations are kicked off. This is only used on Android at the moment. Fixes flutter#193502 ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant in-code documentation (doc comments with `///`). - [x] If this PR introduces a new feature or capability, I created and linked a website documentation issue or PR in [flutter/website] (or verified none is needed). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing.
1 parent a8cb261 commit af028a8

6 files changed

Lines changed: 182 additions & 36 deletions

File tree

‎engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.cc‎

Lines changed: 51 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -102,15 +102,26 @@ static std::optional<QueueIndexVK> PickQueue(const vk::PhysicalDevice& device,
102102
return std::nullopt;
103103
}
104104

105-
std::shared_ptr<ContextVK> ContextVK::Create(Settings settings) {
105+
std::shared_ptr<ContextVK> ContextVK::DeviceSelection::CreateContext() {
106+
if (!device_holder) {
107+
return nullptr;
108+
}
106109
auto context = std::shared_ptr<ContextVK>(new ContextVK(settings.flags));
107-
context->Setup(std::move(settings));
110+
context->Setup(std::move(*this));
108111
if (!context->IsValid()) {
109112
return nullptr;
110113
}
111114
return context;
112115
}
113116

117+
std::shared_ptr<ContextVK> ContextVK::Create(Settings settings) {
118+
auto selection = SelectDevice(std::move(settings));
119+
if (!selection.ok()) {
120+
return nullptr;
121+
}
122+
return selection->CreateContext();
123+
}
124+
114125
// static
115126
size_t ContextVK::ChooseThreadCountForWorkers(size_t hardware_concurrency) {
116127
// Never create more than 4 worker threads. Attempt to use up to
@@ -144,18 +155,17 @@ Context::BackendType ContextVK::GetBackendType() const {
144155
/* version 2.0.0 */
145156
static constexpr uint32_t kImpellerEngineVersion =
146157
VK_MAKE_API_VERSION(0, 2, 0, 0);
158+
static constexpr uint32_t kImpellerVulkanApiVersion = VK_API_VERSION_1_1;
147159

148-
void ContextVK::Setup(Settings settings) {
149-
TRACE_EVENT0("impeller", "ContextVK::Setup");
160+
absl::StatusOr<ContextVK::DeviceSelection> ContextVK::SelectDevice(
161+
Settings settings) {
162+
TRACE_EVENT0("impeller", "ContextVK::SelectDevice");
150163

151164
if (!settings.proc_address_callback) {
152165
VALIDATION_LOG << "Missing proc address callback.";
153-
return;
166+
return absl::InvalidArgumentError("Missing proc address callback.");
154167
}
155168

156-
raster_message_loop_ = fml::ConcurrentMessageLoop::Create(
157-
ChooseThreadCountForWorkers(std::thread::hardware_concurrency()));
158-
159169
auto& dispatcher = VULKAN_HPP_DEFAULT_DISPATCHER;
160170
dispatcher.init(settings.proc_address_callback);
161171

@@ -175,7 +185,7 @@ void ContextVK::Setup(Settings settings) {
175185

176186
if (!caps->IsValid()) {
177187
VALIDATION_LOG << "Could not determine device capabilities.";
178-
return;
188+
return absl::InternalError("Could not determine device capabilities.");
179189
}
180190

181191
gHasValidationLayers = caps->AreValidationsEnabled();
@@ -185,7 +195,7 @@ void ContextVK::Setup(Settings settings) {
185195

186196
if (!enabled_layers.has_value() || !enabled_extensions.has_value()) {
187197
VALIDATION_LOG << "Device has insufficient capabilities.";
188-
return;
198+
return absl::InternalError("Device has insufficient capabilities.");
189199
}
190200

191201
vk::InstanceCreateFlags instance_flags = {};
@@ -220,7 +230,7 @@ void ContextVK::Setup(Settings settings) {
220230
//
221231
// variant, major, minor, patch
222232
application_info.setApplicationVersion(VK_API_VERSION_1_0);
223-
application_info.setApiVersion(VK_API_VERSION_1_1);
233+
application_info.setApiVersion(kImpellerVulkanApiVersion);
224234
application_info.setEngineVersion(kImpellerEngineVersion);
225235
application_info.setPEngineName("Impeller");
226236
application_info.setPApplicationName("Impeller");
@@ -251,7 +261,7 @@ void ContextVK::Setup(Settings settings) {
251261
if (instance.result != vk::Result::eSuccess) {
252262
VALIDATION_LOG << "Could not create Vulkan instance: "
253263
<< vk::to_string(instance.result);
254-
return;
264+
return absl::InternalError("Could not create Vulkan instance.");
255265
}
256266
device_holder->instance = std::move(instance.value);
257267
} else {
@@ -271,7 +281,7 @@ void ContextVK::Setup(Settings settings) {
271281

272282
if (!debug_report->IsValid()) {
273283
VALIDATION_LOG << "Could not set up debug report.";
274-
return;
284+
return absl::InternalError("Could not set up debug report.");
275285
}
276286

277287
//----------------------------------------------------------------------------
@@ -282,13 +292,34 @@ void ContextVK::Setup(Settings settings) {
282292
PickPhysicalDevice(*caps, device_holder->instance.get());
283293
if (!physical_device.has_value()) {
284294
VALIDATION_LOG << "No valid Vulkan device found.";
285-
return;
295+
return absl::NotFoundError("No valid Vulkan device found.");
286296
}
287297
device_holder->physical_device = physical_device.value();
288298
} else {
289299
device_holder->physical_device = settings.embedder_data->physical_device;
290300
}
291301

302+
auto driver_info =
303+
std::make_unique<DriverInfoVK>(device_holder->physical_device);
304+
305+
return DeviceSelection{
306+
.settings = std::move(settings),
307+
.caps = std::move(caps),
308+
.device_holder = std::move(device_holder),
309+
.debug_report = std::move(debug_report),
310+
.driver_info = std::move(driver_info),
311+
};
312+
}
313+
314+
void ContextVK::Setup(DeviceSelection selection) {
315+
TRACE_EVENT0("impeller", "ContextVK::Setup");
316+
317+
Settings settings = std::move(selection.settings);
318+
auto caps = std::move(selection.caps);
319+
auto device_holder = std::move(selection.device_holder);
320+
auto debug_report = std::move(selection.debug_report);
321+
auto driver_info = std::move(selection.driver_info);
322+
292323
//----------------------------------------------------------------------------
293324
/// Pick device queues.
294325
///
@@ -368,7 +399,7 @@ void ContextVK::Setup(Settings settings) {
368399
///
369400
auto allocator = std::shared_ptr<AllocatorVK>(new AllocatorVK(
370401
weak_from_this(), //
371-
application_info.apiVersion, //
402+
kImpellerVulkanApiVersion, //
372403
device_holder->physical_device, //
373404
device_holder, //
374405
device_holder->instance.get(), //
@@ -381,8 +412,11 @@ void ContextVK::Setup(Settings settings) {
381412
}
382413

383414
//----------------------------------------------------------------------------
384-
/// Setup the pipeline library.
415+
/// Setup the worker threads and the pipeline library.
385416
///
417+
raster_message_loop_ = fml::ConcurrentMessageLoop::Create(
418+
ChooseThreadCountForWorkers(std::thread::hardware_concurrency()));
419+
386420
auto pipeline_library = std::shared_ptr<PipelineLibraryVK>(
387421
new PipelineLibraryVK(device_holder, //
388422
caps, //
@@ -457,20 +491,15 @@ void ContextVK::Setup(Settings settings) {
457491
return;
458492
}
459493

460-
VkPhysicalDeviceProperties physical_device_properties;
461-
dispatcher.vkGetPhysicalDeviceProperties(device_holder->physical_device,
462-
&physical_device_properties);
463-
464494
//----------------------------------------------------------------------------
465495
/// All done!
466496
///
467497

468498
// Apply workarounds for broken drivers.
469-
auto driver_info =
470-
std::make_unique<DriverInfoVK>(device_holder->physical_device);
471499
workarounds_ = GetWorkaroundsFromDriverInfo(*driver_info);
472500
caps->ApplyWorkarounds(workarounds_);
473501

502+
device_name_ = driver_info->GetDriverName();
474503
device_holder_ = std::move(device_holder);
475504
idle_waiter_vk_ = std::make_shared<IdleWaiterVK>(device_holder_);
476505
driver_info_ = std::move(driver_info);
@@ -487,7 +516,6 @@ void ContextVK::Setup(Settings settings) {
487516
resource_manager_ = std::move(resource_manager);
488517
command_pool_recycler_ = std::move(command_pool_recycler);
489518
descriptor_pool_recycler_ = std::move(descriptor_pool_recycler);
490-
device_name_ = std::string(physical_device_properties.deviceName);
491519
command_queue_vk_ = std::make_shared<CommandQueueVK>(weak_from_this());
492520
should_enable_surface_control_ = settings.enable_surface_control;
493521
should_batch_cmd_buffers_ = !workarounds_.batch_submit_command_buffer_timeout;

‎engine/src/flutter/impeller/renderer/backend/vulkan/context_vk.h‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@
77

88
#include <format>
99
#include <memory>
10+
#include <optional>
1011

1112
#include "flutter/fml/concurrent_message_loop.h"
1213
#include "flutter/fml/mapping.h"
1314
#include "flutter/fml/unique_fd.h"
1415
#include "impeller/base/backend_cast.h"
1516
#include "impeller/core/formats.h"
1617
#include "impeller/core/runtime_types.h"
18+
#include "impeller/renderer/backend/vulkan/capabilities_vk.h"
1719
#include "impeller/renderer/backend/vulkan/command_pool_vk.h"
20+
#include "impeller/renderer/backend/vulkan/debug_report_vk.h"
1821
#include "impeller/renderer/backend/vulkan/device_holder_vk.h"
1922
#include "impeller/renderer/backend/vulkan/driver_info_vk.h"
2023
#include "impeller/renderer/backend/vulkan/pipeline_library_vk.h"
@@ -26,6 +29,7 @@
2629
#include "impeller/renderer/command_buffer.h"
2730
#include "impeller/renderer/command_queue.h"
2831
#include "impeller/renderer/context.h"
32+
#include "third_party/abseil-cpp/absl/status/statusor.h"
2933

3034
namespace impeller {
3135

@@ -34,7 +38,6 @@ bool HasValidationLayers();
3438
class CommandEncoderFactoryVK;
3539
class CommandEncoderVK;
3640
class CommandPoolRecyclerVK;
37-
class DebugReportVK;
3841
class FenceWaiterVK;
3942
class ResourceManagerVK;
4043
class SurfaceContextVK;
@@ -64,6 +67,8 @@ class IdleWaiterVK : public IdleWaiter {
6467
class ContextVK final : public Context,
6568
public BackendCast<ContextVK, Context>,
6669
public std::enable_shared_from_this<ContextVK> {
70+
struct DeviceHolderImpl;
71+
6772
public:
6873
// Mutable tracker for command buffer submission bookkeeping.
6974
const std::shared_ptr<GpuSubmissionTracker>& GetMutableSubmissionTracker()
@@ -96,13 +101,34 @@ class ContextVK final : public Context,
96101
Settings() = default;
97102

98103
Settings(Settings&&) = default;
104+
Settings& operator=(Settings&&) = default;
105+
};
106+
107+
/// Holds the Vulkan instance, selected physical device, and its
108+
/// `DriverInfoVK` produced by `SelectDevice`, before the logical device,
109+
/// allocator, pipeline cache, shader modules, or worker threads are created.
110+
struct DeviceSelection {
111+
Settings settings;
112+
std::shared_ptr<CapabilitiesVK> caps;
113+
std::shared_ptr<DeviceHolderImpl> device_holder;
114+
std::unique_ptr<DebugReportVK> debug_report;
115+
std::unique_ptr<DriverInfoVK> driver_info;
116+
117+
/// Finish initializing the `ContextVK` for the selected physical device.
118+
/// Consumes this `DeviceSelection`.
119+
std::shared_ptr<ContextVK> CreateContext();
99120
};
100121

101122
/// Choose the number of worker threads the context_vk will create.
102123
///
103124
/// Visible for testing.
104125
static size_t ChooseThreadCountForWorkers(size_t hardware_concurrency);
105126

127+
/// Initialize the Vulkan instance and select a physical device, returning its
128+
/// `DriverInfoVK` so the caller can inspect or reject the device before the
129+
/// remainder of context setup runs.
130+
static absl::StatusOr<DeviceSelection> SelectDevice(Settings settings);
131+
106132
static std::shared_ptr<ContextVK> Create(Settings settings);
107133

108134
uint64_t GetHash() const { return hash_; }
@@ -316,7 +342,7 @@ class ContextVK final : public Context,
316342

317343
explicit ContextVK(const Flags& flags);
318344

319-
void Setup(Settings settings);
345+
void Setup(DeviceSelection selection);
320346

321347
ContextVK(const ContextVK&) = delete;
322348

‎engine/src/flutter/impeller/renderer/backend/vulkan/context_vk_unittests.cc‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22
// Use of this source code is governed by a BSD-style license that can be
33
// found in the LICENSE file.
44

5+
#include <optional>
6+
#include <string_view>
7+
58
#include "flutter/fml/synchronization/waitable_event.h"
69
#include "flutter/testing/testing.h" // IWYU pragma: keep
710
#include "impeller/base/validation.h"
@@ -426,5 +429,68 @@ TEST(ContextVKTest, HashIsUniqueAcrossThreads) {
426429
EXPECT_NE(hash1, hash2);
427430
}
428431

432+
namespace {
433+
434+
constexpr std::string_view kAdreno630Name = "Adreno (TM) 630";
435+
constexpr uint32_t kQualcommVendorID = 0x5143;
436+
437+
void SetAdreno630Properties(VkPhysicalDevice device,
438+
VkPhysicalDeviceProperties* prop) {
439+
prop->vendorID = kQualcommVendorID;
440+
kAdreno630Name.copy(prop->deviceName, kAdreno630Name.size());
441+
prop->deviceName[kAdreno630Name.size()] = '\0';
442+
prop->deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU;
443+
}
444+
445+
} // namespace
446+
447+
TEST(ContextVKTest, SelectDeviceExposesDriverInfoBeforeContextCreation) {
448+
absl::StatusOr<ContextVK::DeviceSelection> selection =
449+
MockVulkanContextBuilder()
450+
.SetPhysicalPropertiesCallback(SetAdreno630Properties)
451+
.SelectDevice();
452+
453+
ASSERT_TRUE(selection.ok());
454+
EXPECT_EQ(selection->driver_info->GetVendor(), VendorVK::kQualcomm);
455+
EXPECT_EQ(selection->driver_info->GetAdrenoGPUInfo(), AdrenoGPU::kAdreno630);
456+
EXPECT_TRUE(selection->driver_info->IsKnownBadDriver());
457+
// Dropping `selection` without calling CreateContext() tears down the Vulkan
458+
// instance cleanly (verified by MockVulkanStatePtr's thread-exit leak check).
459+
}
460+
461+
TEST(ContextVKTest, SelectDeviceCanFinishCreatingContext) {
462+
absl::StatusOr<ContextVK::DeviceSelection> selection =
463+
MockVulkanContextBuilder()
464+
.SetPhysicalPropertiesCallback(SetAdreno630Properties)
465+
.SelectDevice();
466+
467+
ASSERT_TRUE(selection.ok());
468+
std::shared_ptr<ContextVK> context = selection->CreateContext();
469+
470+
ASSERT_NE(context, nullptr);
471+
EXPECT_TRUE(context->IsValid());
472+
// The same DriverInfoVK inspected on the selection is retained by the
473+
// context.
474+
EXPECT_EQ(context->GetDriverInfo()->GetAdrenoGPUInfo(),
475+
AdrenoGPU::kAdreno630);
476+
EXPECT_EQ(context->DescribeGpuModel(), std::string(kAdreno630Name));
477+
478+
// CreateContext() consumes the selection; calling it again returns nullptr.
479+
EXPECT_EQ(selection->CreateContext(), nullptr);
480+
}
481+
482+
TEST(ContextVKTest, CreateAcceptsKnownBadDriversByDefault) {
483+
// ContextVK::Create does not reject known-bad drivers on its own; callers
484+
// without a fallback rely on this.
485+
std::shared_ptr<ContextVK> context =
486+
MockVulkanContextBuilder()
487+
.SetPhysicalPropertiesCallback(SetAdreno630Properties)
488+
.Build();
489+
490+
ASSERT_NE(context, nullptr);
491+
EXPECT_TRUE(context->IsValid());
492+
EXPECT_TRUE(context->GetDriverInfo()->IsKnownBadDriver());
493+
}
494+
429495
} // namespace testing
430496
} // namespace impeller

‎engine/src/flutter/impeller/renderer/backend/vulkan/test/mock_vulkan.cc‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1314,8 +1314,7 @@ MockVulkanContextBuilder::MockVulkanContextBuilder()
13141314
}
13151315
}) {}
13161316

1317-
std::shared_ptr<ContextVK> MockVulkanContextBuilder::Build() {
1318-
auto message_loop = fml::ConcurrentMessageLoop::Create();
1317+
ContextVK::Settings MockVulkanContextBuilder::PrepareSettings() {
13191318
ContextVK::Settings settings;
13201319
settings.proc_address_callback = GetMockVulkanProcAddress;
13211320
if (settings_callback_) {
@@ -1334,8 +1333,17 @@ std::shared_ptr<ContextVK> MockVulkanContextBuilder::Build() {
13341333
g_mock_vulkan_state->compression_exhausted_create_image_failures =
13351334
compression_exhausted_create_image_failures_;
13361335
settings.embedder_data = embedder_data_;
1337-
std::shared_ptr<ContextVK> result = ContextVK::Create(std::move(settings));
1338-
return result;
1336+
return settings;
1337+
}
1338+
1339+
absl::StatusOr<ContextVK::DeviceSelection>
1340+
MockVulkanContextBuilder::SelectDevice() {
1341+
return ContextVK::SelectDevice(PrepareSettings());
1342+
}
1343+
1344+
std::shared_ptr<ContextVK> MockVulkanContextBuilder::Build() {
1345+
auto message_loop = fml::ConcurrentMessageLoop::Create();
1346+
return ContextVK::Create(PrepareSettings());
13391347
}
13401348

13411349
std::shared_ptr<std::vector<std::string>> GetMockVulkanFunctions(

0 commit comments

Comments
 (0)