diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 21ef1d23f9..1ad78ea62d 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -164,6 +164,18 @@ static void wl_log_to_session(const char *fmt, va_list ap) { droiddeck_log("program", "libwayland: %s", line); } +static void log_protocol_error(void *data, enum wl_protocol_logger_type type, + const struct wl_protocol_logger_message *m) { + if (type != WL_PROTOCOL_LOGGER_EVENT || m->message != &wl_display_interface.events[WL_DISPLAY_ERROR] || + m->arguments_count < 3) return; + struct wl_resource *object = (struct wl_resource *)m->arguments[0].o; + const char *message = m->arguments[2].s; + droiddeck_log("program", "protocol error sent to %s: %s@%u error %u: %s", + client_name(wl_resource_get_client(m->resource)), + object ? wl_resource_get_class(object) : "?", object ? wl_resource_get_id(object) : 0, + m->arguments[1].u, message ? message : ""); +} + static void on_client_created(struct wl_listener *l, void *data) { struct wl_client *client = data; struct client_info *ci = calloc(1, sizeof(*ci)); @@ -3918,6 +3930,7 @@ int droiddeck_wayland_run(void) { } droiddeck_log("display", "Wayland compositor listening on %s/wayland-0", rt ? rt : "?"); wl_log_set_handler_server(wl_log_to_session); + wl_display_add_protocol_logger(display, log_protocol_error, NULL); /* A client that falls behind reading (gamescope at a few fps) must not be dropped for a full * event buffer: libwayland's default is 4 KB per direction. */ wl_display_set_default_max_buffer_size(display, 1u << 20); diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 8608d7c260..7e1792b6d4 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -131,6 +131,14 @@ app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the the Mali bridge rejected both of the backend's modifiers for AR24, so the session ended at start (0933's "no usable modifier"); the bridge makes such images without the handle type and exports them through a dma-heap. +- `0936-nested-swapchain-remake-retries.patch`: recreating the nested swapchain asserted + `bRet` (`vulkan_remake_swapchain`) on the first failure and logged no VkResult. A Pixel 10 Pro + (PowerVR D-Series through libhybris) built two swapchains and aborted on the third, as Steam's + Big Picture took focus. Failed `vkCreateSwapchainKHR`, `vkGetPhysicalDeviceSurfaceCapabilitiesKHR`, + `vkQueuePresentKHR` and `vkAcquireNextImageKHR` calls now log their VkResult. A failed attempt + releases whatever it created, so a retry never finds the surface still owned by a half-built + swapchain, and is retried up to 10 times, 100 ms apart. A swapchain that still cannot be made + ends gamescope with a logged reason instead of the assertion. The shared DroidDeck patch also includes `0116-release-cursor-shm-buffers.patch`: pointer cursor surfaces have no X11/xdg window association, so routing their commits through `g_PendingCommits` diff --git a/tools/gamescope/patches/0936-nested-swapchain-remake-retries.patch b/tools/gamescope/patches/0936-nested-swapchain-remake-retries.patch new file mode 100644 index 0000000000..95248e86ba --- /dev/null +++ b/tools/gamescope/patches/0936-nested-swapchain-remake-retries.patch @@ -0,0 +1,159 @@ +diff --git a/src/rendervulkan.cpp b/src/rendervulkan.cpp +index 0835bfe..21a287d 100644 +--- a/src/rendervulkan.cpp ++++ b/src/rendervulkan.cpp +@@ -9,12 +9,16 @@ + #include + #include + #include ++#include ++#include + #include + #include ++#include + #include "vulkan_include.h" + #include "nested_swapchain.hpp" + #include "dmabuf_import.hpp" + #include "nested_surface_format.hpp" ++#include "swapchain_remake.hpp" + #include "Utils/Algorithm.h" + + #if defined(__linux__) +@@ -3224,7 +3228,10 @@ bool acquire_next_image( void ) + { + VkResult res = g_device.vk.AcquireNextImageKHR( g_device.device(), g_output.swapChain, UINT64_MAX, VK_NULL_HANDLE, g_output.acquireFence, &g_output.nOutImage ); + if ( res != VK_SUCCESS && res != VK_SUBOPTIMAL_KHR ) ++ { ++ vk_errorf( res, "vkAcquireNextImageKHR failed" ); + return false; ++ } + if ( g_device.vk.WaitForFences( g_device.device(), 1, &g_output.acquireFence, false, UINT64_MAX ) != VK_SUCCESS ) + return false; + return g_device.vk.ResetFences( g_device.device(), 1, &g_output.acquireFence ) == VK_SUCCESS; +@@ -3330,7 +3337,8 @@ void vulkan_present_to_window( void ) + .pImageIndices = &g_output.nOutImage, + }; + +- if ( g_device.vk.QueuePresentKHR( g_device.queue(), &presentInfo ) == VK_SUCCESS ) ++ VkResult presentResult = g_device.vk.QueuePresentKHR( g_device.queue(), &presentInfo ); ++ if ( presentResult == VK_SUCCESS ) + { + if ( g_device.supportsPresentWait() ) + { +@@ -3339,7 +3347,11 @@ void vulkan_present_to_window( void ) + } + } + else ++ { ++ if ( presentResult < 0 ) ++ vk_errorf( presentResult, "vkQueuePresentKHR failed" ); + vulkan_remake_swapchain(); ++ } + + while ( !acquire_next_image() ) + vulkan_remake_swapchain(); +@@ -3461,2 +3473,6 @@ +- if ( g_device.vk.GetPhysicalDeviceSurfaceCapabilitiesKHR( g_device.physDev(), pOutput->surface, &pOutput->surfaceCaps ) != VK_SUCCESS ) +- return false; ++ VkResult capsResult = g_device.vk.GetPhysicalDeviceSurfaceCapabilitiesKHR( g_device.physDev(), pOutput->surface, &pOutput->surfaceCaps ); ++ if ( capsResult != VK_SUCCESS ) ++ { ++ vk_errorf( capsResult, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR failed" ); ++ return false; ++ } +@@ -3559,7 +3575,12 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput ) + .clipped = VK_TRUE, + }; + +- if (g_device.vk.CreateSwapchainKHR( g_device.device(), &createInfo, nullptr, &pOutput->swapChain) != VK_SUCCESS ) { ++ VkResult createResult = g_device.vk.CreateSwapchainKHR( g_device.device(), &createInfo, nullptr, &pOutput->swapChain ); ++ if ( createResult != VK_SUCCESS ) ++ { ++ pOutput->swapChain = VK_NULL_HANDLE; ++ vk_errorf( createResult, "vkCreateSwapchainKHR failed (%ux%u, %u images, usage 0x%x)", ++ createInfo.imageExtent.width, createInfo.imageExtent.height, imageCount, createInfo.imageUsage ); + return false; + } + +@@ -3606,6 +3627,19 @@ bool vulkan_make_swapchain( VulkanOutput_t *pOutput ) + return true; + } + ++static void vulkan_release_swapchain( VulkanOutput_t *pOutput ) ++{ ++ pOutput->outputImages.clear(); ++ pOutput->presentationImages.clear(); ++ if ( pOutput->acquireFence ) ++ g_device.vk.DestroyFence( g_device.device(), pOutput->acquireFence, nullptr ); ++ pOutput->acquireFence = VK_NULL_HANDLE; ++ ++ if ( pOutput->swapChain ) ++ g_device.vk.DestroySwapchainKHR( g_device.device(), pOutput->swapChain, nullptr ); ++ pOutput->swapChain = VK_NULL_HANDLE; ++} ++ + bool vulkan_remake_swapchain( void ) + { + std::unique_lock lock(present_wait_lock); +@@ -3618,9 +3652,3 @@ bool vulkan_remake_swapchain( void ) + +- pOutput->outputImages.clear(); +- pOutput->presentationImages.clear(); +- if ( pOutput->acquireFence ) +- g_device.vk.DestroyFence( g_device.device(), pOutput->acquireFence, nullptr ); +- pOutput->acquireFence = VK_NULL_HANDLE; +- +- g_device.vk.DestroySwapchainKHR( g_device.device(), pOutput->swapChain, nullptr ); ++ vulkan_release_swapchain( pOutput ); + +@@ -3630,9 +3658,18 @@ bool vulkan_remake_swapchain( void ) + for (auto& pCaptureTexture : pOutput->pCaptureTextures) + pCaptureTexture = nullptr; + +- bool bRet = vulkan_make_swapchain( pOutput ); +- assert( bRet ); // Something has gone horribly wrong! +- return bRet; ++ uint32_t attempts = gamescope::RemakeSwapchainWithRetries( ++ [pOutput]() { return vulkan_make_swapchain( pOutput ); }, ++ [pOutput]() { vulkan_release_swapchain( pOutput ); }, ++ []( uint32_t delayMs ) { std::this_thread::sleep_for( std::chrono::milliseconds( delayMs ) ); } ); ++ if ( !attempts ) ++ { ++ vk_log.errorf( "Nested swapchain could not be recreated in %u attempts", gamescope::k_unSwapchainRemakeAttempts ); ++ std::abort(); ++ } ++ if ( attempts > 1 ) ++ vk_log.infof( "Nested swapchain recreated on attempt %u", attempts ); ++ return true; + } + + static bool vulkan_make_output_images( VulkanOutput_t *pOutput ) +diff --git a/src/swapchain_remake.hpp b/src/swapchain_remake.hpp +new file mode 100644 +index 0000000..99d688b +--- /dev/null ++++ b/src/swapchain_remake.hpp +@@ -0,0 +1,23 @@ ++#pragma once ++ ++#include ++ ++namespace gamescope ++{ ++constexpr uint32_t k_unSwapchainRemakeAttempts = 10; ++constexpr uint32_t k_unSwapchainRemakeDelayMs = 100; ++ ++template ++inline uint32_t RemakeSwapchainWithRetries( Make make, Release release, Wait wait ) ++{ ++ for ( uint32_t attempt = 1; attempt <= k_unSwapchainRemakeAttempts; ++attempt ) ++ { ++ if ( make() ) ++ return attempt; ++ release(); ++ if ( attempt < k_unSwapchainRemakeAttempts ) ++ wait( k_unSwapchainRemakeDelayMs ); ++ } ++ return 0; ++} ++} diff --git a/tools/gamescope/tests/nested-swapchain.cpp b/tools/gamescope/tests/nested-swapchain.cpp index a2054aa746..0345c0b138 100644 --- a/tools/gamescope/tests/nested-swapchain.cpp +++ b/tools/gamescope/tests/nested-swapchain.cpp @@ -2,6 +2,7 @@ #include "nested_surface_format.hpp" #include "dmabuf_import.hpp" #include "sdl_refresh.hpp" +#include "swapchain_remake.hpp" #include #include @@ -152,5 +153,51 @@ int main() assert(DmabufMemoryType(memory, 7, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == UINT32_MAX); assert(DmabufMemoryType(memory, 7, 4, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == UINT32_MAX); + using gamescope::RemakeSwapchainWithRetries; + using gamescope::k_unSwapchainRemakeAttempts; + using gamescope::k_unSwapchainRemakeDelayMs; + struct RemakeTrace + { + uint32_t makes = 0; + uint32_t releases = 0; + uint32_t waits = 0; + uint32_t waitedMs = 0; + bool live = false; + bool makeOverLive = false; + }; + auto remake = [](RemakeTrace &trace, uint32_t failures) + { + return RemakeSwapchainWithRetries( + [&trace, failures]() + { + trace.makeOverLive |= trace.live; + trace.live = true; + return ++trace.makes > failures; + }, + [&trace]() { trace.live = false; ++trace.releases; }, + [&trace](uint32_t delayMs) { ++trace.waits; trace.waitedMs += delayMs; }); + }; + + RemakeTrace first; + assert(remake(first, 0) == 1); + assert(first.makes == 1 && first.releases == 0 && first.waits == 0 && first.live); + + RemakeTrace transient; + assert(remake(transient, 3) == 4); + assert(transient.makes == 4 && transient.releases == 3 && transient.waits == 3); + assert(transient.waitedMs == 3 * k_unSwapchainRemakeDelayMs); + assert(transient.live && !transient.makeOverLive); + + RemakeTrace lastChance; + assert(remake(lastChance, k_unSwapchainRemakeAttempts - 1) == k_unSwapchainRemakeAttempts); + assert(lastChance.live && !lastChance.makeOverLive); + + RemakeTrace persistent; + assert(remake(persistent, UINT32_MAX) == 0); + assert(persistent.makes == k_unSwapchainRemakeAttempts); + assert(persistent.releases == k_unSwapchainRemakeAttempts); + assert(persistent.waits == k_unSwapchainRemakeAttempts - 1); + assert(!persistent.live && !persistent.makeOverLive); + std::puts("Gamescope presentation and DMA-BUF import tests passed"); } diff --git a/tools/tests/protocol_error_log_harness.c b/tools/tests/protocol_error_log_harness.c new file mode 100644 index 0000000000..805c7397ac --- /dev/null +++ b/tools/tests/protocol_error_log_harness.c @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include + +#define WL_DISPLAY_ERROR 0 +enum wl_protocol_logger_type { WL_PROTOCOL_LOGGER_REQUEST, WL_PROTOCOL_LOGGER_EVENT }; +struct wl_message { const char *name, *signature; const void **types; }; +struct wl_interface { const char *name; int version, method_count; const struct wl_message *methods; + int event_count; const struct wl_message *events; }; +union wl_argument { int32_t i; uint32_t u; const char *s; void *o; }; +struct wl_client { const char *name; }; +struct wl_resource { const char *cls; uint32_t id; struct wl_client *client; }; +struct wl_protocol_logger_message { + struct wl_resource *resource; + int message_opcode; + const struct wl_message *message; + int arguments_count; + const union wl_argument *arguments; +}; + +static const struct wl_message display_events[] = {{"error", "ous", NULL}, {"delete_id", "u", NULL}}; +static const struct wl_interface wl_display_interface = {"wl_display", 1, 0, NULL, 2, display_events}; +static const struct wl_message buffer_events[] = {{"release", "", NULL}}; + +static char g_logged[1024]; +static int g_lines; +static void droiddeck_log(const char *tag, const char *fmt, ...) { + va_list ap; + int n = snprintf(g_logged, sizeof(g_logged), "[%s] ", tag); + va_start(ap, fmt); + vsnprintf(g_logged + n, sizeof(g_logged) - (size_t)n, fmt, ap); + va_end(ap); + g_lines++; +} +static const char *client_name(struct wl_client *client) { return client->name; } +static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->client; } +static const char *wl_resource_get_class(struct wl_resource *r) { return r->cls; } +static uint32_t wl_resource_get_id(struct wl_resource *r) { return r->id; } + +#include "log_protocol_error.inc" + +int main(int argc, char **argv) { + assert(argc == 2); + struct wl_client gamescope = {"gamescope"}; + struct wl_resource display = {"wl_display", 1, &gamescope}; + struct wl_resource handle = {"android_wlegl", 12, &gamescope}; + struct wl_resource buffer = {"wl_buffer", 40, &gamescope}; + union wl_argument error[3] = {{.o = &handle}, {.u = 2}, {.s = "Android buffer allocation failed"}}; + struct wl_protocol_logger_message sent = {&display, WL_DISPLAY_ERROR, &display_events[0], 3, error}; + + if (!strcmp(argv[1], "error")) { + log_protocol_error(NULL, WL_PROTOCOL_LOGGER_EVENT, &sent); + assert(g_lines == 1); + assert(!strcmp(g_logged, "[program] protocol error sent to gamescope: " + "android_wlegl@12 error 2: Android buffer allocation failed")); + } else if (!strcmp(argv[1], "anonymous")) { + union wl_argument bare[3] = {{.o = NULL}, {.u = 1}, {.s = NULL}}; + sent.arguments = bare; + log_protocol_error(NULL, WL_PROTOCOL_LOGGER_EVENT, &sent); + assert(g_lines == 1); + assert(!strcmp(g_logged, "[program] protocol error sent to gamescope: ?@0 error 1: ")); + } else if (!strcmp(argv[1], "quiet")) { + log_protocol_error(NULL, WL_PROTOCOL_LOGGER_REQUEST, &sent); + struct wl_protocol_logger_message deleted = {&display, 1, &display_events[1], 1, error}; + log_protocol_error(NULL, WL_PROTOCOL_LOGGER_EVENT, &deleted); + struct wl_protocol_logger_message release = {&buffer, 0, &buffer_events[0], 0, NULL}; + log_protocol_error(NULL, WL_PROTOCOL_LOGGER_EVENT, &release); + assert(g_lines == 0); + } else { + return 2; + } + puts("ok"); + return 0; +} diff --git a/tools/tests/test_protocol_error_log.py b/tools/tests/test_protocol_error_log.py new file mode 100644 index 0000000000..187da62e45 --- /dev/null +++ b/tools/tests/test_protocol_error_log.py @@ -0,0 +1,50 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +REPO = Path(__file__).resolve().parents[2] + + +class ProtocolErrorLogTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which(os.environ.get('CC', 'cc')) + if compiler is None: + raise unittest.SkipTest('A host C compiler is required') + source = (REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c').read_text() + start = source.index('static void log_protocol_error(') + end = source.index('\n}\n', start) + 3 + cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-protocol-error-') + cls.addClassCleanup(cls.temp.cleanup) + folder = Path(cls.temp.name) + (folder / 'log_protocol_error.inc').write_text(source[start:end]) + cls.binary = folder / 'protocol-error-test' + subprocess.run([compiler, '-std=c11', '-Wall', '-Wno-unused-parameter', '-I', str(folder), + str(REPO / 'tools/tests/protocol_error_log_harness.c'), + '-o', str(cls.binary)], check=True, capture_output=True, text=True) + + def check_case(self, case): + result = subprocess.run([str(self.binary), case], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_error_names_client_object_code_and_message(self): + self.check_case('error') + + def test_error_without_object_or_message_still_logs(self): + self.check_case('anonymous') + + def test_requests_and_other_events_are_not_logged(self): + self.check_case('quiet') + + +class ProtocolErrorLoggerRegistrationTest(unittest.TestCase): + def test_logger_is_registered_with_the_display(self): + source = (REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c').read_text() + self.assertIn('wl_display_add_protocol_logger(display, log_protocol_error, NULL);', source) + + +if __name__ == '__main__': + unittest.main()