From 29b04b66eb78eb7e5cb9b2943f60537138fd8992 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Tue, 1 Dec 2026 06:02:16 -0500 Subject: [PATCH] fix(gamescope): hold forwarded client buffers until the display finished scanning them out (#3516) * Return a forwarded client buffer to its client only after the display finished scanning it out * Test that a forwarded client buffer waits for scanout and composite images do not * Pin the gamescope build that holds forwarded client buffers until scanout ends --- tools/gamescope/PATCHES.md | 11 + ...7-forwarded-buffers-wait-for-scanout.patch | 351 ++++++++++++++++++ tools/gamescope/release.env | 4 +- ...test_gamescope_forwarded_buffer_scanout.py | 222 +++++++++++ 4 files changed, 586 insertions(+), 2 deletions(-) create mode 100644 tools/gamescope/patches/0147-forwarded-buffers-wait-for-scanout.patch create mode 100644 tools/tests/test_gamescope_forwarded_buffer_scanout.py diff --git a/tools/gamescope/PATCHES.md b/tools/gamescope/PATCHES.md index 68d83600d3..f322c5f38b 100644 --- a/tools/gamescope/PATCHES.md +++ b/tools/gamescope/PATCHES.md @@ -485,3 +485,14 @@ not wait on fences attached to a dma-buf, so the composite now checks each outpu It picks the next image that is neither held by the host nor still being scanned out. Only when every free image is still on the display does it wait for one, up to 100 ms. On kernels that cannot attach the fence, the host keeps waiting itself and nothing changes. `tools/gamescope/tests/nested-swapchain.cpp` covers the choice and the busy check. + +## 0147 Wayland backend: a forwarded client buffer goes back to its client only after scanout + +When no composite is needed, gamescope hands a client's own buffer to the host compositor as a plane. The host now +releases a buffer as soon as the display latches the next one and leaves its release fence on the buffer's dma-buf. +gamescope returned the buffer to the client on that release, and a client whose Vulkan driver does not wait on +fences attached to a dma-buf then drew into it while the display was still scanning it out, which showed as black +tiles in compressed buffers. A forwarded client buffer now stays held until `poll(POLLOUT)` on its dma-buf reports +that the display has finished with it, on a waiter thread so nothing else blocks. A release that arrives after the +buffer was shown again is dropped, so the later release decides. Composite output images keep the 0146 path, and a +host that waits for the fence itself releases buffers that are already idle, so nothing changes there. diff --git a/tools/gamescope/patches/0147-forwarded-buffers-wait-for-scanout.patch b/tools/gamescope/patches/0147-forwarded-buffers-wait-for-scanout.patch new file mode 100644 index 0000000000..928f1ba9b0 --- /dev/null +++ b/tools/gamescope/patches/0147-forwarded-buffers-wait-for-scanout.patch @@ -0,0 +1,351 @@ +diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp +index 12f0f50..a0fedd4 100644 +--- a/src/Backends/WaylandBackend.cpp ++++ b/src/Backends/WaylandBackend.cpp +@@ -3,24 +3,28 @@ + #include "wlserver.hpp" + #include "vblankmanager.hpp" + #include "steamcompmgr.hpp" + #include "edid.h" + #include "Utils/Defer.h" + #include "Utils/Algorithm.h" + #include "convar.h" + #include "refresh_rate.h" + #include "waitable.h" + #include "Utils/TempFiles.h" + #include "Utils/CursorRouting.h" + #include "Utils/WaylandScaling.h" ++#include "output_image_pick.hpp" ++ ++#include ++#include + + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #include "wlr_begin.hpp" +@@ -485,44 +489,82 @@ namespace gamescope + + // One backing plane plus every layer steamcompmgr can hand us. + CWaylandPlane m_Planes[k_nMaxLayers + 1]; + bool m_bVisible = true; + std::atomic m_bDesiredFullscreenState = { false }; + + bool m_bHostCompositorIsCurrentlyVRR = false; + }; + + class CWaylandFb final : public CBaseBackendFb + { + public: +- CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer ); ++ CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd = -1 ); + ~CWaylandFb(); + + void OnCompositorAcquire(); + void OnCompositorRelease(); ++ void OnScanoutDone( uint64_t ulAcquireSerial ); + + wl_buffer *GetHostBuffer() const { return m_pHostBuffer; } + wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; } + + bool HeldByHost() const override { return m_bCompositorAcquired; } + + void Wayland_Buffer_Release( wl_buffer *pBuffer ); + static const wl_buffer_listener s_BufferListener; + + private: + CWaylandBackend *m_pBackend = nullptr; + wl_buffer *m_pHostBuffer = nullptr; + wlr_buffer *m_pClientBuffer = nullptr; ++ int m_nDmabufFd = -1; ++ std::mutex m_AcquireMutex; ++ uint64_t m_ulAcquireSerial = 0; + bool m_bCompositorAcquired = false; + }; ++ ++ class CWaylandScanoutRelease final : public IWaitable ++ { ++ public: ++ CWaylandScanoutRelease( CWaylandFb *pFb, int nFd, uint64_t ulAcquireSerial ) ++ : m_pFb{ pFb } ++ , m_nFd{ nFd } ++ , m_ulAcquireSerial{ ulAcquireSerial } ++ { ++ } ++ ++ int GetFD() override { return m_nFd; } ++ void OnPollOut() override { Finish(); } ++ void OnPollHangUp() override { Finish(); } ++ ++ static CAsyncWaiter<> &Waiter() ++ { ++ static CAsyncWaiter<> s_Waiter{ "gamescope-scanout" }; ++ return s_Waiter; ++ } ++ ++ private: ++ void Finish() ++ { ++ Waiter().RemoveWaitable( this ); ++ m_pFb->OnScanoutDone( m_ulAcquireSerial ); ++ close( m_nFd ); ++ delete this; ++ } ++ ++ CWaylandFb *m_pFb; ++ int m_nFd; ++ uint64_t m_ulAcquireSerial; ++ }; + const wl_buffer_listener CWaylandFb::s_BufferListener = + { + .release = WAYLAND_USERDATA_TO_THIS( CWaylandFb, Wayland_Buffer_Release ), + }; + + class CWaylandInputThread + { + public: + CWaylandInputThread(); + ~CWaylandInputThread(); + + bool Init( CWaylandBackend *pBackend ); +@@ -969,73 +1011,108 @@ namespace gamescope + .action = WAYLAND_NULL(), + }; + const zwp_primary_selection_source_v1_listener CWaylandBackend::s_PrimarySelectionSourceListener = + { + .send = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Send ), + .cancelled = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Cancelled ), + }; + + ////////////////// + // CWaylandFb + ////////////////// + +- CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer ) ++ CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd ) + : CBaseBackendFb() + , m_pBackend { pBackend } + , m_pHostBuffer { pHostBuffer } ++ , m_nDmabufFd { nDmabufFd } + { + wl_buffer_add_listener( pHostBuffer, &s_BufferListener, this ); + } + + CWaylandFb::~CWaylandFb() + { + // I own the pHostBuffer. + wl_buffer_destroy( m_pHostBuffer ); + m_pHostBuffer = nullptr; ++ if ( m_nDmabufFd >= 0 ) ++ close( m_nDmabufFd ); + } + + void CWaylandFb::OnCompositorAcquire() + { +- // If the compositor has acquired us, track that +- // and increment the ref count. +- if ( !m_bCompositorAcquired ) ++ bool bTakeRef = false; + { ++ std::scoped_lock lock( m_AcquireMutex ); ++ m_ulAcquireSerial++; ++ bTakeRef = !m_bCompositorAcquired; + m_bCompositorAcquired = true; +- IncRef(); + } ++ ++ if ( bTakeRef ) ++ IncRef(); + } + + void CWaylandFb::OnCompositorRelease() + { +- // Compositor has released us, decrement rc. +- //assert( m_bCompositorAcquired ); ++ uint64_t ulSerial; ++ { ++ std::scoped_lock lock( m_AcquireMutex ); ++ ulSerial = m_ulAcquireSerial; ++ } ++ OnScanoutDone( ulSerial ); ++ } + +- if ( m_bCompositorAcquired ) ++ void CWaylandFb::OnScanoutDone( uint64_t ulAcquireSerial ) ++ { ++ bool bDropRef = false; + { ++ std::scoped_lock lock( m_AcquireMutex ); ++ if ( ulAcquireSerial != m_ulAcquireSerial ) ++ return; ++ bDropRef = m_bCompositorAcquired; + m_bCompositorAcquired = false; +- DecRef(); + } ++ ++ if ( bDropRef ) ++ DecRef(); + else +- { + xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." ); +- } + } + + void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer ) + { + assert( m_pHostBuffer ); + assert( m_pHostBuffer == pBuffer ); + + xdg_log.debugf( "buffer_release: %p", pBuffer ); + ++ if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) ) ++ { ++ int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 ); ++ if ( nFd >= 0 ) ++ { ++ uint64_t ulSerial; ++ { ++ std::scoped_lock lock( m_AcquireMutex ); ++ ulSerial = m_ulAcquireSerial; ++ } ++ auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial ); ++ if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) ) ++ return; ++ delete pWait; ++ close( nFd ); ++ } ++ } ++ + OnCompositorRelease(); + } + + ////////////////// + // CWaylandConnector + ////////////////// + + CWaylandConnector::CWaylandConnector( CWaylandBackend *pBackend, uint64_t ulVirtualConnectorKey ) + : CBaseBackendConnector{ ulVirtualConnectorKey } + , m_pBackend( pBackend ) + , m_Planes{ this, this, this, this, this, this, this, this, this } + { +@@ -2349,25 +2426,26 @@ namespace gamescope + pDmaBuf->format, + 0u ); + + if ( !pImportedBuffer ) + { + xdg_log.errorf( "Failed to import dmabuf" ); + zwp_linux_buffer_params_v1_destroy( pBufferParams ); + return nullptr; + } + + zwp_linux_buffer_params_v1_destroy( pBufferParams ); + +- return new CWaylandFb{ this, pImportedBuffer }; ++ int nDmabufFd = pDmaBuf->n_planes > 0 ? fcntl( pDmaBuf->fd[0], F_DUPFD_CLOEXEC, 0 ) : -1; ++ return new CWaylandFb{ this, pImportedBuffer, nDmabufFd }; + } + + bool CWaylandBackend::UsesModifiers() const + { + if ( !cv_wayland_use_modifiers ) + return false; + + return m_bCanUseModifiers; + } + std::span CWaylandBackend::GetSupportedModifiers( uint32_t uDrmFormat ) const + { + auto iter = m_FormatModifiers.find( uDrmFormat ); +diff --git a/src/backend.cpp b/src/backend.cpp +index cc91853..ec59c8b 100644 +--- a/src/backend.cpp ++++ b/src/backend.cpp +@@ -109,41 +109,47 @@ namespace gamescope + wlserver_unlock(); + } + + // Potentially release now! + DecRefPrivate(); + } + + return uRefCount; + } + + void CBaseBackendFb::SetBuffer( wlr_buffer *pClientBuffer ) + { ++ if ( pClientBuffer ) ++ m_bShowsClientBuffer = true; ++ + if ( m_pClientBuffer == pClientBuffer ) + return; + + assert( m_pClientBuffer == nullptr ); + m_pClientBuffer = pClientBuffer; + if ( GetRefCount() ) + { + wlserver_lock(); + wlr_buffer_lock( m_pClientBuffer ); + wlserver_unlock( false ); + } + + m_pReleasePoint = nullptr; + } + + void CBaseBackendFb::SetReleasePoint( std::shared_ptr pReleasePoint ) + { ++ if ( pReleasePoint ) ++ m_bShowsClientBuffer = true; ++ + if ( m_pReleasePoint == pReleasePoint ) + return; + + m_pReleasePoint = pReleasePoint; + + if ( m_pClientBuffer && GetRefCount() ) + { + wlserver_lock(); + wlr_buffer_unlock( m_pClientBuffer ); + wlserver_unlock(); + m_pClientBuffer = nullptr; + } +diff --git a/src/backend.h b/src/backend.h +index 30b42ca..9a27711 100644 +--- a/src/backend.h ++++ b/src/backend.h +@@ -303,26 +303,29 @@ namespace gamescope + public: + CBaseBackendFb(); + virtual ~CBaseBackendFb(); + + uint32_t IncRef() override; + uint32_t DecRef() override; + + void SetBuffer( wlr_buffer *pClientBuffer ) override; + void SetReleasePoint( std::shared_ptr pReleasePoint ) override; + + virtual IBackendFb *EnsureImported() override { return this; }; + ++ bool ShowsClientBuffer() const { return m_bShowsClientBuffer; } ++ + private: + wlr_buffer *m_pClientBuffer = nullptr; ++ std::atomic m_bShowsClientBuffer = { false }; + std::shared_ptr m_pReleasePoint; + }; + + class IBackend + { + public: + virtual ~IBackend() {} + + virtual bool Init() = 0; + virtual bool PostInit() = 0; + virtual std::span GetInstanceExtensions() const = 0; + virtual std::span GetDeviceExtensions( VkPhysicalDevice pVkPhysicalDevice ) const = 0; diff --git a/tools/gamescope/release.env b/tools/gamescope/release.env index 552ee708f5..f32967c4f2 100644 --- a/tools/gamescope/release.env +++ b/tools/gamescope/release.env @@ -1,3 +1,3 @@ GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components -GAMESCOPE_TAG=gamescope-3.16.29-f7dd44d2 -GAMESCOPE_SHA256=a034c36d44f9bca4abc804bda3958c8d303f1ce304fb677375e5d7aa233287a9 +GAMESCOPE_TAG=gamescope-3.16.29-cb9c4861 +GAMESCOPE_SHA256=89a3d70124a13bb5de0b4c67ff75d748a5d7ba6f29590194621754e3550b1f31 diff --git a/tools/tests/test_gamescope_forwarded_buffer_scanout.py b/tools/tests/test_gamescope_forwarded_buffer_scanout.py new file mode 100644 index 0000000000..77e6f32a30 --- /dev/null +++ b/tools/tests/test_gamescope_forwarded_buffer_scanout.py @@ -0,0 +1,222 @@ +from pathlib import Path +import os +import shutil +import subprocess +import tempfile +import unittest + + +ROOT = Path(__file__).resolve().parents[2] +PATCHES = ROOT / "tools/gamescope/patches" +PICK = PATCHES / "0146-composite-waits-for-scanout.patch" +FORWARD = PATCHES / "0147-forwarded-buffers-wait-for-scanout.patch" + + +def post_image(patch, name): + out, current = [], None + for line in patch.read_text().splitlines(): + if line.startswith("+++ "): + current = line[6:] if line.startswith("+++ b/") else line[4:] + continue + if current != name or line.startswith("--- ") or line.startswith("@@"): + continue + if line.startswith("+") or line.startswith(" "): + out.append(line[1:]) + elif line == "": + out.append("") + return "\n".join(out) + + +def block(text, start, end="\n }\n"): + begin = text.index(start) + return text[begin:text.index(end, begin) + len(end)] + + +PREAMBLE = r''' +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct wl_buffer {}; +static struct { void debugf(const char *, ...) {} void errorf(const char *, ...) { ++oh_no; } int oh_no = 0; } xdg_log; +namespace droiddeck::frame_trace { enum class Event { OutputRelease }; inline void Record(Event) {} } + +namespace gamescope +{ + PICK + + class IWaitable + { + public: + virtual ~IWaitable() {} + virtual int GetFD() { return -1; } + virtual void OnPollOut() {} + virtual void OnPollHangUp() {} + }; + + template + class CAsyncWaiter + { + public: + CAsyncWaiter( const char * ) {} + bool AddWaitable( IWaitable *p, uint32_t ) { waiting.push_back( p ); return true; } + void RemoveWaitable( IWaitable *p ) { std::erase( waiting, p ); } + std::vector waiting; + }; + + class CWaylandBackend; + + class CBaseBackendFb + { + public: + uint32_t IncRef() { return refs++; } + uint32_t DecRef() { return --refs; } + bool ShowsClientBuffer() const { return client; } + uint32_t refs = 1; + bool client = false; + }; + + class CWaylandFb final : public CBaseBackendFb + { + public: + CWaylandFb( int nDmabufFd ) : m_pHostBuffer{ &m_Buffer }, m_nDmabufFd{ nDmabufFd } {} + void OnCompositorAcquire(); + void OnCompositorRelease(); + void OnScanoutDone( uint64_t ulAcquireSerial ); + void Wayland_Buffer_Release( wl_buffer *pBuffer ); + wl_buffer m_Buffer; + wl_buffer *m_pHostBuffer; + int m_nDmabufFd = -1; + std::mutex m_AcquireMutex; + uint64_t m_ulAcquireSerial = 0; + bool m_bCompositorAcquired = false; + }; + + SCANOUT + + METHODS +} +''' + +MAIN = r''' +using namespace gamescope; + +static CAsyncWaiter<> &waiter() { return CWaylandScanoutRelease::Waiter(); } + +struct Display { + int fds[2]; + Display() { assert( pipe2( fds, O_NONBLOCK ) == 0 ); } + ~Display() { close( fds[0] ); close( fds[1] ); } + void scanning() { char b[4096] = {}; while ( write( fds[1], b, sizeof( b ) ) > 0 ) {} } + void done() { char b[4096]; while ( read( fds[0], b, sizeof( b ) ) > 0 ) {} } + int fd() { return fds[1]; } +}; + +static void fire() { + assert( waiter().waiting.size() == 1 ); + waiter().waiting.front()->OnPollOut(); + assert( waiter().waiting.empty() ); +} + +int main( int argc, char **argv ) { + std::string which = argv[1]; + Display d; + CWaylandFb fb{ fcntl( d.fd(), F_DUPFD_CLOEXEC, 0 ) }; + if ( which == "client-scanning" ) { + fb.client = true; + fb.OnCompositorAcquire(); + assert( fb.refs == 2 ); + d.scanning(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 2 && fb.m_bCompositorAcquired ); + d.done(); + fire(); + assert( fb.refs == 1 && !fb.m_bCompositorAcquired && xdg_log.oh_no == 0 ); + } else if ( which == "client-idle" ) { + fb.client = true; + fb.OnCompositorAcquire(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 1 && waiter().waiting.empty() ); + } else if ( which == "composite-scanning" ) { + fb.OnCompositorAcquire(); + d.scanning(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 1 && waiter().waiting.empty() ); + } else if ( which == "shown-again" ) { + fb.client = true; + fb.OnCompositorAcquire(); + d.scanning(); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + fb.OnCompositorAcquire(); + d.done(); + fire(); + assert( fb.refs == 2 && fb.m_bCompositorAcquired ); + fb.Wayland_Buffer_Release( fb.m_pHostBuffer ); + assert( fb.refs == 1 && !fb.m_bCompositorAcquired && xdg_log.oh_no == 0 ); + } else if ( which == "no-dmabuf" ) { + CWaylandFb plain{ -1 }; + plain.client = true; + plain.OnCompositorAcquire(); + plain.Wayland_Buffer_Release( plain.m_pHostBuffer ); + assert( plain.refs == 1 && waiter().waiting.empty() ); + } else { + return 2; + } + return 0; +} +''' + + +class ForwardedBufferScanoutTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cxx = shutil.which(os.environ.get("CXX", "c++")) + if not cxx: + raise AssertionError("C++ compiler required") + pick = post_image(PICK, "src/output_image_pick.hpp") + pick = pick[pick.index("struct OutputImagePick"):pick.rindex("}")] + wayland = post_image(FORWARD, "src/Backends/WaylandBackend.cpp") + scanout = block(wayland, " class CWaylandScanoutRelease", "\n };\n") + methods = "\n".join(block(wayland, " void CWaylandFb::" + name) for name in + ("OnCompositorAcquire()", "OnCompositorRelease()", "OnScanoutDone(", "Wayland_Buffer_Release(")) + source = PREAMBLE.replace("PICK", pick).replace("SCANOUT", scanout).replace("METHODS", methods) + MAIN + cls.tmp = tempfile.TemporaryDirectory(prefix="droiddeck-forwarded-scanout-") + cls.addClassCleanup(cls.tmp.cleanup) + probe = Path(cls.tmp.name) / "probe.cpp" + probe.write_text(source) + cls.binary = probe.with_suffix("") + built = subprocess.run([cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-UNDEBUG", + "-include", "string", str(probe), "-o", str(cls.binary)], capture_output=True, text=True) + if built.returncode: + raise AssertionError(built.stdout + built.stderr) + + def scenario(self, name): + result = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_forwarded_buffer_is_held_until_scanout_ends(self): + self.scenario("client-scanning") + + def test_idle_forwarded_buffer_is_released_at_once(self): + self.scenario("client-idle") + + def test_composite_output_image_keeps_the_release_at_latch(self): + self.scenario("composite-scanning") + + def test_buffer_shown_again_waits_for_its_next_release(self): + self.scenario("shown-again") + + def test_buffer_without_dmabuf_is_released_at_once(self): + self.scenario("no-dmabuf") + + +if __name__ == "__main__": + unittest.main()