diff --git a/CHANGELOG.md b/CHANGELOG.md index b8849df3..aabe2808 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,8 @@ Release notes on GitHub are taken from the matching section here. reported a 9-inch screen; it now reports the monitor's size at 96 dpi. - With Vulkan on NVIDIA, resizing the window no longer freezes for about 22 seconds each time on setups where the driver is slow to destroy the old swapchain. Nightcap now waits at most 100 ms for a destroy - and finishes slow ones in the background, so the first resize no longer freezes either. + and finishes slow ones in the background, so the first resize no longer freezes either. Quick resizes + and window rebuilds no longer wait for those background destroys. - On FreeBSD, Roblox downloads no longer fail with "error adding trust anchors" in a Fedora userspace. - On FreeBSD, sound plays through `/dev/dsp` without an `asound.conf`, once `alsa-plugins-oss` is installed in the Linux userspace. An existing `~/.asoundrc` or `/etc/asound.conf` is still used. diff --git a/include/mocktail/graphics/deferred_teardown.h b/include/mocktail/graphics/deferred_teardown.h index 178e19e1..dd9a3db4 100644 --- a/include/mocktail/graphics/deferred_teardown.h +++ b/include/mocktail/graphics/deferred_teardown.h @@ -18,20 +18,30 @@ class DeferredTeardown final { DeferredTeardown(const DeferredTeardown&) = delete; DeferredTeardown& operator=(const DeferredTeardown&) = delete; + // Runs after all earlier work, including earlier PostConcurrent work. void Post(std::function work); + // Runs at once on its own thread, alongside other concurrent work, up to + // kMaxConcurrent at a time; past that it queues like Post. + void PostConcurrent(std::function work); bool Busy(); void Drain(); // False if work is still queued or running after `timeout`. bool WaitIdleFor(std::chrono::milliseconds timeout); private: + static constexpr int kMaxConcurrent = 8; + void Run(); + bool IdleLocked() const { + return !running_ && queue_.empty() && concurrent_ == 0; + } std::mutex mutex_; std::condition_variable ready_; std::condition_variable idle_; std::deque> queue_; bool running_ = false; + int concurrent_ = 0; bool stopping_ = false; std::thread worker_; }; diff --git a/include/mocktail/graphics/swapchain_retirement.h b/include/mocktail/graphics/swapchain_retirement.h index 4b9d35c7..059a4484 100644 --- a/include/mocktail/graphics/swapchain_retirement.h +++ b/include/mocktail/graphics/swapchain_retirement.h @@ -20,6 +20,15 @@ struct HeldSwapchain { const VkAllocationCallbacks* Allocator() const { return has_allocator ? &allocator : nullptr; } + // The game destroyed `surface` while this swapchain still owned the window; + // the host surface is destroyed after the swapchain. + bool surface_destroy_deferred = false; + VkInstance instance = VK_NULL_HANDLE; + bool has_surface_allocator = false; + VkAllocationCallbacks surface_allocator{}; + const VkAllocationCallbacks* SurfaceAllocator() const { + return has_surface_allocator ? &surface_allocator : nullptr; + } explicit operator bool() const { return swapchain != VK_NULL_HANDLE; } }; @@ -27,6 +36,8 @@ struct HeldSwapchain { // X11 driver can block ~22 s in vkDestroySwapchainKHR. A swapchain the game // destroys while it still owns the window is held and passed as oldSwapchain // to the next create, so the window is free while the worker destroys it. +// If the game also destroys its surface, it may retire into any new surface on +// that device, since every surface maps to the one window. // Off until Enable(), so drivers that destroy promptly keep the old path. class SwapchainRetirement final { public: @@ -43,6 +54,9 @@ class SwapchainRetirement final { const VkAllocationCallbacks* allocator); HeldSwapchain TakeForCreate(VkDevice device, VkSurfaceKHR surface, VkSwapchainKHR* old_swapchain); + // True when `surface` belongs to the held swapchain and must outlive it. + bool DeferSurfaceDestroy(VkSurfaceKHR surface, VkInstance instance, + const VkAllocationCallbacks* allocator); HeldSwapchain ReleaseIfSurface(VkSurfaceKHR surface); HeldSwapchain ReleaseIfDevice(VkDevice device); HeldSwapchain Release(); diff --git a/src/graphics/bionic_vulkan_loader_adapter.cc b/src/graphics/bionic_vulkan_loader_adapter.cc index fb2133fb..3796540e 100644 --- a/src/graphics/bionic_vulkan_loader_adapter.cc +++ b/src/graphics/bionic_vulkan_loader_adapter.cc @@ -1678,6 +1678,8 @@ bool KeepHostDevice(VkDevice device, AdapterState::DeviceRecord record, return true; } +void PostSwapchainDestroy(const mocktail::graphics::HeldSwapchain& held); + // Destroys a kept device that a create with a different key could not reuse, // in the background, so the slot is free for the device replacing it. // Its parent instance stays alive, as every replaced instance does: @@ -1692,6 +1694,7 @@ void DestroyStaleKeptDevice(VkDevice device, PFN_vkDestroyDevice host_destroy, std::fprintf(stderr, " [vulkan] the kept host VkDevice does not match this create; " "destroying it in the background\n"); + PostSwapchainDestroy(Retirement().ReleaseIfDevice(device)); void* const library = HoldLibraryOf(reinterpret_cast(host_destroy)); Teardown().Post([device, host_destroy, library, has_allocator, allocator] { @@ -1712,7 +1715,9 @@ void PostSwapchainDestroy(const mocktail::graphics::HeldSwapchain& held) { } void* const library = HoldLibraryOf(reinterpret_cast(host_destroy)); - Teardown().Post([held, host_destroy, library] { + // Concurrent: a slow destroy must not delay the next one, or a new swapchain + // on the same window waits for every queued destroy in turn. + Teardown().PostConcurrent([held, host_destroy, library] { const std::uint64_t start_ns = MonotonicNanos(); host_destroy(held.device, held.swapchain, held.Allocator()); const std::uint64_t elapsed_ms = (MonotonicNanos() - start_ns) / 1000000; @@ -1724,6 +1729,21 @@ void PostSwapchainDestroy(const mocktail::graphics::HeldSwapchain& held) { } ReleaseLibrary(library); }); + if (!held.surface_destroy_deferred) { + return; + } + const auto host_destroy_surface = reinterpret_cast( + HostInstanceProc(held.instance, "vkDestroySurfaceKHR")); + if (host_destroy_surface == nullptr) { + return; + } + void* const surface_library = + HoldLibraryOf(reinterpret_cast(host_destroy_surface)); + // Queued, so it runs after the swapchain destroy above. + Teardown().Post([held, host_destroy_surface, surface_library] { + host_destroy_surface(held.instance, held.surface, held.SurfaceAllocator()); + ReleaseLibrary(surface_library); + }); } } // namespace @@ -1904,6 +1924,13 @@ vkDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface, if (!EnsureInitialized()) { return; } + if (Retirement().Enabled() && + Retirement().DeferSurfaceDestroy(surface, instance, allocator)) { + std::fprintf(stderr, + " [vulkan] keeping the old surface until its swapchain " + "retires into the next one\n"); + return; + } PostSwapchainDestroy(Retirement().ReleaseIfSurface(surface)); const auto host_destroy = reinterpret_cast( HostInstanceProc(instance, "vkDestroySurfaceKHR")); @@ -2349,9 +2376,9 @@ VKAPI_ATTR void VKAPI_CALL vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* allocator) { const auto host_destroy = reinterpret_cast( HostDeviceProc(device, "vkDestroyDevice")); - PostSwapchainDestroy(Retirement().ReleaseIfDevice(device)); State().text_overlay.DestroyDevice(device); if (State().etc2.EncoderBuilding(device)) { + PostSwapchainDestroy(Retirement().ReleaseIfDevice(device)); std::fprintf(stderr, " [vulkan] BC7 encoder still compiling; destroying the old " "device in the background\n"); @@ -2374,6 +2401,8 @@ vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* allocator) { " [vulkan] keeping the host VkDevice for the next " "create\n"); } else { + // A kept device keeps its held swapchain for the next create. + PostSwapchainDestroy(Retirement().ReleaseIfDevice(device)); State().etc2.DropParkedGpuDecoder(device); if (host_destroy != nullptr) { if (Retirement().Enabled() && Teardown().Busy()) { diff --git a/src/graphics/deferred_teardown.cc b/src/graphics/deferred_teardown.cc index 5e93ef51..907b1043 100644 --- a/src/graphics/deferred_teardown.cc +++ b/src/graphics/deferred_teardown.cc @@ -15,6 +15,8 @@ DeferredTeardown::~DeferredTeardown() { if (worker.joinable()) { worker.join(); } + std::unique_lock lock(mutex_); + idle_.wait(lock, [this] { return concurrent_ == 0; }); } void DeferredTeardown::Post(std::function work) { @@ -26,26 +28,51 @@ void DeferredTeardown::Post(std::function work) { ready_.notify_one(); } +void DeferredTeardown::PostConcurrent(std::function work) { + std::lock_guard lock(mutex_); + if (concurrent_ >= kMaxConcurrent) { + queue_.push_back(std::move(work)); + if (!worker_.joinable()) { + worker_ = std::thread([this] { Run(); }); + } + ready_.notify_one(); + return; + } + ++concurrent_; + std::thread([this, work = std::move(work)] { + work(); + std::lock_guard done(mutex_); + --concurrent_; + // Notified under the lock so the destructor cannot free them first. + ready_.notify_all(); + idle_.notify_all(); + }).detach(); +} + bool DeferredTeardown::Busy() { std::lock_guard lock(mutex_); - return running_ || !queue_.empty(); + return !IdleLocked(); } void DeferredTeardown::Drain() { std::unique_lock lock(mutex_); - idle_.wait(lock, [this] { return !running_ && queue_.empty(); }); + idle_.wait(lock, [this] { return IdleLocked(); }); } bool DeferredTeardown::WaitIdleFor(std::chrono::milliseconds timeout) { std::unique_lock lock(mutex_); - return idle_.wait_for(lock, timeout, - [this] { return !running_ && queue_.empty(); }); + return idle_.wait_for(lock, timeout, [this] { return IdleLocked(); }); } void DeferredTeardown::Run() { std::unique_lock lock(mutex_); for (;;) { - ready_.wait(lock, [this] { return stopping_ || !queue_.empty(); }); + // Queued work waits for earlier concurrent work, so a device is never + // destroyed while one of its swapchains still is. + ready_.wait(lock, [this] { + return (stopping_ && queue_.empty()) || + (!queue_.empty() && concurrent_ == 0); + }); if (queue_.empty()) { return; } @@ -56,7 +83,7 @@ void DeferredTeardown::Run() { work(); lock.lock(); running_ = false; - if (queue_.empty()) { + if (IdleLocked()) { idle_.notify_all(); } } diff --git a/src/graphics/swapchain_retirement.cc b/src/graphics/swapchain_retirement.cc index d596b4eb..11ea093e 100644 --- a/src/graphics/swapchain_retirement.cc +++ b/src/graphics/swapchain_retirement.cc @@ -53,7 +53,8 @@ HeldSwapchain SwapchainRetirement::TakeForCreate(VkDevice device, VkSurfaceKHR surface, VkSwapchainKHR* old_swapchain) { std::lock_guard lock(mutex_); - if (held_ && held_.device == device && held_.surface == surface && + if (held_ && held_.device == device && + (held_.surface == surface || held_.surface_destroy_deferred) && old_swapchain != nullptr && *old_swapchain == VK_NULL_HANDLE) { *old_swapchain = held_.swapchain; @@ -61,10 +62,27 @@ HeldSwapchain SwapchainRetirement::TakeForCreate(VkDevice device, return std::exchange(held_, HeldSwapchain{}); } +bool SwapchainRetirement::DeferSurfaceDestroy( + VkSurfaceKHR surface, VkInstance instance, + const VkAllocationCallbacks* allocator) { + std::lock_guard lock(mutex_); + if (!held_ || held_.surface != surface || held_.surface_destroy_deferred) { + return false; + } + held_.surface_destroy_deferred = true; + held_.instance = instance; + held_.has_surface_allocator = allocator != nullptr; + if (allocator != nullptr) { + held_.surface_allocator = *allocator; + } + return true; +} + HeldSwapchain SwapchainRetirement::ReleaseIfSurface(VkSurfaceKHR surface) { std::lock_guard lock(mutex_); - return held_.surface == surface ? std::exchange(held_, HeldSwapchain{}) - : HeldSwapchain{}; + return held_.surface == surface && !held_.surface_destroy_deferred + ? std::exchange(held_, HeldSwapchain{}) + : HeldSwapchain{}; } HeldSwapchain SwapchainRetirement::ReleaseIfDevice(VkDevice device) { diff --git a/tests/deferred_teardown_test.cc b/tests/deferred_teardown_test.cc index 09391476..b0992bf6 100644 --- a/tests/deferred_teardown_test.cc +++ b/tests/deferred_teardown_test.cc @@ -102,5 +102,66 @@ TEST(DeferredTeardownTest, WaitIdleForReturnsOnceQuickWorkFinishes) { EXPECT_TRUE(finished); } +// Slow swapchain destroys must overlap, so a wait for the newest one is not +// stuck behind older ones. +TEST(DeferredTeardownTest, ConcurrentWorkOverlaps) { + DeferredTeardown teardown; + std::promise release; + std::shared_future released = release.get_future().share(); + std::atomic started{0}; + for (int index = 0; index < 4; ++index) { + teardown.PostConcurrent([released, &started] { + ++started; + released.wait(); + }); + } + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (started < 4 && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + EXPECT_EQ(started, 4); + EXPECT_TRUE(teardown.Busy()); + EXPECT_FALSE(teardown.WaitIdleFor(std::chrono::milliseconds(20))); + + release.set_value(); + teardown.Drain(); + EXPECT_FALSE(teardown.Busy()); +} + +// A device destroy posted after its swapchain destroys must run after them. +TEST(DeferredTeardownTest, PostedWorkWaitsForEarlierConcurrentWork) { + DeferredTeardown teardown; + std::promise release; + std::shared_future released = release.get_future().share(); + std::atomic concurrent_done{false}; + std::atomic ran_after{false}; + teardown.PostConcurrent([released, &concurrent_done] { + released.wait(); + concurrent_done = true; + }); + teardown.Post([&concurrent_done, &ran_after] { + ran_after = concurrent_done.load(); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(30)); + release.set_value(); + teardown.Drain(); + EXPECT_TRUE(ran_after); +} + +TEST(DeferredTeardownTest, ConcurrentWorkBeyondTheCapStillRuns) { + std::atomic ran{0}; + { + DeferredTeardown teardown; + for (int index = 0; index < 20; ++index) { + teardown.PostConcurrent([&ran] { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + ++ran; + }); + } + } + EXPECT_EQ(ran, 20); +} + } } diff --git a/tests/swapchain_retirement_test.cc b/tests/swapchain_retirement_test.cc index f04276c9..f6d79f9b 100644 --- a/tests/swapchain_retirement_test.cc +++ b/tests/swapchain_retirement_test.cc @@ -150,4 +150,60 @@ TEST(SwapchainRetirementTest, ReleasesWhenItsSurfaceOrDeviceGoes) { EXPECT_FALSE(retirement.Release()); } +const VkInstance kInstance = Fake(0x40); + +// Roblox rebuilds its surface on the kept device. The held swapchain still +// owns the window, so it keeps its surface and retires into the new one. +TEST(SwapchainRetirementTest, KeepsAHeldSwapchainsSurfaceForTheNextSurface) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + + EXPECT_FALSE(retirement.DeferSurfaceDestroy(kOtherSurface, kInstance, nullptr)); + int user_data = 0; + { + VkAllocationCallbacks callbacks{}; + callbacks.pUserData = &user_data; + EXPECT_TRUE(retirement.DeferSurfaceDestroy(kSurface, kInstance, &callbacks)); + } + + VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; + const HeldSwapchain held = + retirement.TakeForCreate(kDevice, kOtherSurface, &old_swapchain); + EXPECT_EQ(old_swapchain, kFirst); + EXPECT_EQ(held.swapchain, kFirst); + EXPECT_TRUE(held.surface_destroy_deferred); + EXPECT_EQ(held.surface, kSurface); + EXPECT_EQ(held.instance, kInstance); + ASSERT_NE(held.SurfaceAllocator(), nullptr); + EXPECT_EQ(held.SurfaceAllocator()->pUserData, &user_data); + EXPECT_FALSE(retirement.Release()); +} + +TEST(SwapchainRetirementTest, AKeptSurfaceStillNeverRetiresIntoAnotherDevice) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + EXPECT_TRUE(retirement.DeferSurfaceDestroy(kSurface, kInstance, nullptr)); + + VkSwapchainKHR old_swapchain = VK_NULL_HANDLE; + const HeldSwapchain held = + retirement.TakeForCreate(kOtherDevice, kOtherSurface, &old_swapchain); + EXPECT_EQ(old_swapchain, VK_NULL_HANDLE); + EXPECT_EQ(held.swapchain, kFirst); + EXPECT_TRUE(held.surface_destroy_deferred); +} + +TEST(SwapchainRetirementTest, ReleasingTheDeviceReturnsTheKeptSurface) { + SwapchainRetirement retirement; + retirement.Created(kFirst, kSurface, VK_NULL_HANDLE); + EXPECT_FALSE(retirement.Destroyed(kDevice, kFirst, nullptr)); + EXPECT_TRUE(retirement.DeferSurfaceDestroy(kSurface, kInstance, nullptr)); + + const HeldSwapchain held = retirement.ReleaseIfDevice(kDevice); + EXPECT_EQ(held.swapchain, kFirst); + EXPECT_TRUE(held.surface_destroy_deferred); + EXPECT_EQ(held.SurfaceAllocator(), nullptr); +} + } // namespace