Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 10 additions & 0 deletions include/mocktail/graphics/deferred_teardown.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<void()> 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<void()> 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<std::function<void()>> queue_;
bool running_ = false;
int concurrent_ = 0;
bool stopping_ = false;
std::thread worker_;
};
Expand Down
14 changes: 14 additions & 0 deletions include/mocktail/graphics/swapchain_retirement.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,24 @@ 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; }
};

// Decides when a destroyed swapchain may go to the background worker. NVIDIA's
// 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:
Expand All @@ -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();
Expand Down
33 changes: 31 additions & 2 deletions src/graphics/bionic_vulkan_loader_adapter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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<const void*>(host_destroy));
Teardown().Post([device, host_destroy, library, has_allocator, allocator] {
Expand All @@ -1712,7 +1715,9 @@ void PostSwapchainDestroy(const mocktail::graphics::HeldSwapchain& held) {
}
void* const library =
HoldLibraryOf(reinterpret_cast<const void*>(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;
Expand All @@ -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<PFN_vkDestroySurfaceKHR>(
HostInstanceProc(held.instance, "vkDestroySurfaceKHR"));
if (host_destroy_surface == nullptr) {
return;
}
void* const surface_library =
HoldLibraryOf(reinterpret_cast<const void*>(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
Expand Down Expand Up @@ -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<PFN_vkDestroySurfaceKHR>(
HostInstanceProc(instance, "vkDestroySurfaceKHR"));
Expand Down Expand Up @@ -2349,9 +2376,9 @@ VKAPI_ATTR void VKAPI_CALL
vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* allocator) {
const auto host_destroy = reinterpret_cast<PFN_vkDestroyDevice>(
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");
Expand All @@ -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()) {
Expand Down
39 changes: 33 additions & 6 deletions src/graphics/deferred_teardown.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ DeferredTeardown::~DeferredTeardown() {
if (worker.joinable()) {
worker.join();
}
std::unique_lock<std::mutex> lock(mutex_);
idle_.wait(lock, [this] { return concurrent_ == 0; });
}

void DeferredTeardown::Post(std::function<void()> work) {
Expand All @@ -26,26 +28,51 @@ void DeferredTeardown::Post(std::function<void()> work) {
ready_.notify_one();
}

void DeferredTeardown::PostConcurrent(std::function<void()> work) {
std::lock_guard<std::mutex> 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<std::mutex> 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<std::mutex> lock(mutex_);
return running_ || !queue_.empty();
return !IdleLocked();
}

void DeferredTeardown::Drain() {
std::unique_lock<std::mutex> 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<std::mutex> 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<std::mutex> 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;
}
Expand All @@ -56,7 +83,7 @@ void DeferredTeardown::Run() {
work();
lock.lock();
running_ = false;
if (queue_.empty()) {
if (IdleLocked()) {
idle_.notify_all();
}
}
Expand Down
24 changes: 21 additions & 3 deletions src/graphics/swapchain_retirement.cc
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,36 @@ HeldSwapchain SwapchainRetirement::TakeForCreate(VkDevice device,
VkSurfaceKHR surface,
VkSwapchainKHR* old_swapchain) {
std::lock_guard<std::mutex> 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;
}
return std::exchange(held_, HeldSwapchain{});
}

bool SwapchainRetirement::DeferSurfaceDestroy(
VkSurfaceKHR surface, VkInstance instance,
const VkAllocationCallbacks* allocator) {
std::lock_guard<std::mutex> 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<std::mutex> 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) {
Expand Down
61 changes: 61 additions & 0 deletions tests/deferred_teardown_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> release;
std::shared_future<void> released = release.get_future().share();
std::atomic<int> 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<void> release;
std::shared_future<void> released = release.get_future().share();
std::atomic<bool> concurrent_done{false};
std::atomic<bool> 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<int> 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);
}

}
}
Loading