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: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ Release notes on GitHub are taken from the matching section here.
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. Quick resizes
and window rebuilds no longer wait for those background destroys.
- With Vulkan, joining a game no longer freezes for about 44 seconds on laptops where NVIDIA's driver is
slow to replace a swapchain (seen with PRIME on X11). Nightcap now gives Roblox its existing swapchain
back when it rebuilds one that has not changed, so the driver never replaces it.
- With Vulkan, Nightcap no longer lands on the slow software renderer (lavapipe) when it cannot pin a GPU
driver. If no hardware Vulkan device exists at all, it starts with the OpenGL backend instead of
showing a blank window; `VK_DRIVER_FILES` forces Vulkan.
Expand Down
99 changes: 73 additions & 26 deletions include/mocktail/graphics/swapchain_retirement.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,67 +4,114 @@
#include <vulkan/vulkan.h>

#include <atomic>
#include <cstdint>
#include <mutex>
#include <optional>
#include <unordered_map>
#include <unordered_set>

namespace mocktail::graphics {

struct SwapchainShape {
VkSwapchainCreateFlagsKHR flags = 0;
std::uint32_t min_image_count = 0;
VkFormat format = VK_FORMAT_UNDEFINED;
VkColorSpaceKHR color_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
VkExtent2D extent{};
std::uint32_t array_layers = 0;
VkImageUsageFlags usage = 0;
VkSurfaceTransformFlagBitsKHR transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
VkCompositeAlphaFlagBitsKHR alpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
VkPresentModeKHR present_mode = VK_PRESENT_MODE_FIFO_KHR;
VkBool32 clipped = VK_FALSE;

// None for chained or concurrent-sharing creates, which are never reused.
static std::optional<SwapchainShape> From(const VkSwapchainCreateInfoKHR& info);
bool operator==(const SwapchainShape& other) const;
};

struct HeldSwapchain {
VkDevice device = VK_NULL_HANDLE;
VkSwapchainKHR swapchain = VK_NULL_HANDLE;
// The host surface the swapchain was created on.
VkSurfaceKHR surface = VK_NULL_HANDLE;
// A copy: the game's callbacks struct need not outlive its destroy call.
bool has_allocator = false;
VkAllocationCallbacks allocator{};
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;
std::optional<SwapchainShape> reusable;
explicit operator bool() const { return swapchain != VK_NULL_HANDLE; }
};

struct KeptSurface {
VkInstance instance = VK_NULL_HANDLE;
bool has_surface_allocator = false;
VkAllocationCallbacks surface_allocator{};
const VkAllocationCallbacks* SurfaceAllocator() const {
return has_surface_allocator ? &surface_allocator : nullptr;
VkSurfaceKHR surface = VK_NULL_HANDLE;
bool has_allocator = false;
VkAllocationCallbacks allocator{};
const VkAllocationCallbacks* Allocator() const {
return has_allocator ? &allocator : nullptr;
}
explicit operator bool() const { return swapchain != VK_NULL_HANDLE; }
explicit operator bool() const { return surface != 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.
// Keeps the driver from destroying and creating swapchains Roblox rebuilds
// unchanged. NVIDIA on X11 with PRIME blocks ~22 s in each swapchain destroy or
// retiring create. Roblox rebuilds an identical swapchain on every view change
// and destroys its swapchain and surface on every game join, so an identical
// create gets the current or the last destroyed swapchain back. Every surface
// is the one SDL window, so a swapchain may serve or retire into any surface;
// a surface the game destroys stays alive until no swapchain uses it.
class SwapchainRetirement final {
public:
void Enable() { enabled_.store(true, std::memory_order_relaxed); }
bool Enabled() const { return enabled_.load(std::memory_order_relaxed); }
// Drops the bookkeeping for a swapchain destroyed in place.
void Forget(VkSwapchainKHR swapchain);
void Created(VkSwapchainKHR swapchain, VkSurfaceKHR surface,
VkSwapchainKHR old_swapchain);
VkSwapchainKHR old_swapchain, VkDevice device = VK_NULL_HANDLE,
const std::optional<SwapchainShape>& shape = std::nullopt);
VkSwapchainKHR Reuse(VkDevice device, VkSwapchainKHR old_swapchain,
const SwapchainShape& shape);
// True when the game still holds another copy of a reused swapchain, so its
// destroy must not reach the driver.
bool DropReference(VkSwapchainKHR swapchain);
void NoteAcquired(VkSwapchainKHR swapchain, std::uint32_t image_index);
void NotePresented(VkSwapchainKHR swapchain, std::uint32_t image_index);
void NoteResult(VkSwapchainKHR swapchain, VkResult result);
// A failed create still retires its oldSwapchain.
void Retired(VkSwapchainKHR old_swapchain);
// Returns what to destroy now; a swapchain still owning the window is held.
// Returns what to destroy now; the last live swapchain is held instead.
HeldSwapchain Destroyed(VkDevice device, VkSwapchainKHR swapchain,
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 TakeForCreate(VkDevice device, VkSwapchainKHR* old_swapchain);
HeldSwapchain ReleaseIfDevice(VkDevice device);
HeldSwapchain Release();
// True when a swapchain still uses `surface`, so its host destroy waits.
bool SurfaceDestroyed(VkSurfaceKHR surface, VkInstance instance,
const VkAllocationCallbacks* allocator);
// Call once a swapchain on `surface` goes to the driver for destroy; returns
// the surface when the game destroyed it and nothing else uses it.
KeptSurface SwapchainGone(VkSurfaceKHR surface);

private:
struct Live {
VkSurfaceKHR surface = VK_NULL_HANDLE;
VkDevice device = VK_NULL_HANDLE;
std::optional<SwapchainShape> shape;
int references = 1;
std::uint64_t acquired = 0;
bool stale = false;
bool Reusable() const { return shape.has_value() && acquired == 0 && !stale; }
};
struct SurfaceUse {
int swapchains = 0;
bool destroyed = false;
KeptSurface kept;
};
std::mutex mutex_;
std::unordered_map<VkSwapchainKHR, VkSurfaceKHR> surfaces_;
std::unordered_map<VkSwapchainKHR, Live> live_;
std::unordered_set<VkSwapchainKHR> retired_;
std::unordered_map<VkSurfaceKHR, SurfaceUse> surfaces_;
HeldSwapchain held_;
std::atomic<bool> enabled_{false};
};
Expand Down
126 changes: 83 additions & 43 deletions src/graphics/bionic_vulkan_loader_adapter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1722,30 +1722,62 @@ void PostSwapchainDestroy(const mocktail::graphics::HeldSwapchain& held) {
host_destroy(held.device, held.swapchain, held.Allocator());
const std::uint64_t elapsed_ms = (MonotonicNanos() - start_ns) / 1000000;
if (elapsed_ms >= 100) {
Retirement().Enable();
std::fprintf(stderr,
" [vulkan] old swapchain destroyed in the background "
"after %llu ms\n",
static_cast<unsigned long long>(elapsed_ms));
}
ReleaseLibrary(library);
});
if (!held.surface_destroy_deferred) {
const mocktail::graphics::KeptSurface kept =
Retirement().SwapchainGone(held.surface);
if (!kept) {
return;
}
const auto host_destroy_surface = reinterpret_cast<PFN_vkDestroySurfaceKHR>(
HostInstanceProc(held.instance, "vkDestroySurfaceKHR"));
HostInstanceProc(kept.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());
Teardown().Post([kept, host_destroy_surface, surface_library] {
host_destroy_surface(kept.instance, kept.surface, kept.Allocator());
ReleaseLibrary(surface_library);
});
}

void RegisterOverlaySwapchain(VkDevice device, VkSwapchainKHR swapchain,
const VkSwapchainCreateInfoKHR& create_info) {
const auto host_get_images = reinterpret_cast<PFN_vkGetSwapchainImagesKHR>(
HostDeviceProc(device, "vkGetSwapchainImagesKHR"));
std::uint32_t image_count = 0;
if (host_get_images == nullptr ||
host_get_images(device, swapchain, &image_count, nullptr) != VK_SUCCESS ||
image_count == 0) {
return;
}
std::vector<VkImage> images(image_count);
const VkResult images_result =
host_get_images(device, swapchain, &image_count, images.data());
if (images_result == VK_SUCCESS || images_result == VK_INCOMPLETE) {
images.resize(image_count);
(void)State().text_overlay.RegisterSwapchain(
device, swapchain, create_info, images.data(), image_count);
}
}

void NoteAcquireResult(VkSwapchainKHR swapchain, VkResult result,
const std::uint32_t* image_index) {
if ((result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) &&
image_index != nullptr) {
Retirement().NoteAcquired(swapchain, *image_index);
}
Retirement().NoteResult(swapchain, result);
}

} // namespace

extern "C" {
Expand Down Expand Up @@ -1924,18 +1956,15 @@ vkDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface,
if (!EnsureInitialized()) {
return;
}
if (Retirement().Enabled() &&
Retirement().DeferSurfaceDestroy(surface, instance, allocator)) {
if (Retirement().SurfaceDestroyed(surface, instance, allocator)) {
std::fprintf(stderr,
" [vulkan] keeping the old surface until its swapchain "
"retires into the next one\n");
" [vulkan] keeping the old surface until its swapchain is "
"destroyed\n");
return;
}
PostSwapchainDestroy(Retirement().ReleaseIfSurface(surface));
const auto host_destroy = reinterpret_cast<PFN_vkDestroySurfaceKHR>(
HostInstanceProc(instance, "vkDestroySurfaceKHR"));
if (host_destroy == nullptr || !Retirement().Enabled() ||
!Teardown().Busy()) {
if (host_destroy == nullptr || !Teardown().Busy()) {
State().android_wsi.DestroySurface(instance, surface, allocator);
return;
}
Expand Down Expand Up @@ -2405,7 +2434,7 @@ vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* allocator) {
PostSwapchainDestroy(Retirement().ReleaseIfDevice(device));
State().etc2.DropParkedGpuDecoder(device);
if (host_destroy != nullptr) {
if (Retirement().Enabled() && Teardown().Busy()) {
if (Teardown().Busy()) {
std::fprintf(stderr,
" [vulkan] waiting for background destroys before "
"destroying the device\n");
Expand Down Expand Up @@ -2549,9 +2578,24 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR(
}
}
}
const std::optional<mocktail::graphics::SwapchainShape> shape =
mocktail::graphics::SwapchainShape::From(host_info);
if (shape) {
const VkSwapchainKHR reused =
Retirement().Reuse(device, create_info->oldSwapchain, *shape);
if (reused != VK_NULL_HANDLE) {
*swapchain = reused;
std::fprintf(stderr,
" [vulkan] reusing the %s swapchain for an identical "
"create\n",
reused == create_info->oldSwapchain ? "current" : "kept");
RegisterOverlaySwapchain(device, reused, *create_info);
observation.SetResult(VK_SUCCESS);
return VK_SUCCESS;
}
}
const mocktail::graphics::HeldSwapchain held =
Retirement().TakeForCreate(device, create_info->surface,
&host_info.oldSwapchain);
Retirement().TakeForCreate(device, &host_info.oldSwapchain);
const bool retires_held = held && host_info.oldSwapchain == held.swapchain;
if (!retires_held) {
PostSwapchainDestroy(held);
Expand All @@ -2568,7 +2612,7 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR(
first_attempt = false;
VkResult created = host_create(device, &info, allocator, swapchain);
if (created == VK_ERROR_NATIVE_WINDOW_IN_USE_KHR &&
Retirement().Enabled() && Teardown().Busy()) {
Teardown().Busy()) {
std::fprintf(stderr,
" [vulkan] waiting for the old swapchain's "
"background destroy to free the window\n");
Expand All @@ -2587,24 +2631,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateSwapchainKHR(
return result;
}
Retirement().Created(*swapchain, create_info->surface,
create_info->oldSwapchain);
const auto host_get_images = reinterpret_cast<PFN_vkGetSwapchainImagesKHR>(
HostDeviceProc(device, "vkGetSwapchainImagesKHR"));
std::uint32_t image_count = 0;
if (host_get_images == nullptr ||
host_get_images(device, *swapchain, &image_count, nullptr) !=
VK_SUCCESS ||
image_count == 0) {
return result;
}
std::vector<VkImage> images(image_count);
const VkResult images_result =
host_get_images(device, *swapchain, &image_count, images.data());
if (images_result == VK_SUCCESS || images_result == VK_INCOMPLETE) {
images.resize(image_count);
(void)State().text_overlay.RegisterSwapchain(
device, *swapchain, *create_info, images.data(), image_count);
}
create_info->oldSwapchain, device, shape);
RegisterOverlaySwapchain(device, *swapchain, *create_info);
return result;
}

Expand All @@ -2614,20 +2642,19 @@ vkDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain,
if (swapchain == VK_NULL_HANDLE) {
return;
}
if (Retirement().DropReference(swapchain)) {
return; // A reused swapchain the game still holds as its new one.
}
State().text_overlay.DestroySwapchain(device, swapchain);
if (Retirement().Enabled()) {
PostSwapchainDestroy(Retirement().Destroyed(device, swapchain, allocator));
const mocktail::graphics::HeldSwapchain now =
Retirement().Destroyed(device, swapchain, allocator);
if (!now) {
return;
}
Retirement().Forget(swapchain);
mocktail::graphics::HeldSwapchain held;
held.device = device;
held.swapchain = swapchain;
held.has_allocator = allocator != nullptr;
if (held.has_allocator) {
held.allocator = *allocator;
PostSwapchainDestroy(now);
if (Retirement().Enabled()) {
return;
}
PostSwapchainDestroy(held);
// A healthy driver finishes in a few ms; the slow NVIDIA case takes ~22 s.
constexpr std::chrono::milliseconds kInlineBudget{100};
if (!Teardown().WaitIdleFor(kInlineBudget)) {
Expand Down Expand Up @@ -2659,6 +2686,7 @@ VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImageKHR(
if (fps_trace) {
AcquireWaitTrace().Record(acquire_start_ns);
}
NoteAcquireResult(swapchain, host_result, image_index);
const VkResult result = NormalizeSwapchainResult(host_result);
NoteSwapchainResult(result, "vkAcquireNextImageKHR");
observation.SetResult(result);
Expand All @@ -2679,6 +2707,7 @@ VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImage2KHR(
"vkAcquireNextImage2KHR", "wait");
const VkResult host_result =
host_acquire(device, acquire_info, image_index);
NoteAcquireResult(acquire_info->swapchain, host_result, image_index);
const VkResult result = NormalizeSwapchainResult(host_result);
NoteSwapchainResult(result, "vkAcquireNextImage2KHR");
observation.SetResult(result);
Expand Down Expand Up @@ -3130,6 +3159,17 @@ vkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
const VkResult result = state.text_overlay.QueuePresent(
queue, present_info, ObservedHostQueuePresent);
scope.Arg("result", result);
if (present_info != nullptr) {
for (std::uint32_t index = 0; index < present_info->swapchainCount;
++index) {
const VkSwapchainKHR presented = present_info->pSwapchains[index];
Retirement().NotePresented(presented,
present_info->pImageIndices[index]);
Retirement().NoteResult(presented, present_info->pResults != nullptr
? present_info->pResults[index]
: result);
}
}
const VkResult normalized_result = NormalizeSwapchainResult(result);
NoteSwapchainResult(normalized_result, "vkQueuePresentKHR");
if (normalized_result == VK_SUCCESS && note_present != nullptr) {
Expand Down
Loading