Gate direct Steam frames on verified producer acquire fences

This commit is contained in:
Kurt Himebauch committed 2026-12-03 14:23:21 -05:00
1 parent 18d735b4c4
commit b164212c8f
35 files changed
+2245 -35

No files matched your search

+12
View File
@@ -506,3 +506,15 @@ on a 120 Hz screen (frames alternately one and two refreshes apart). The first t
it is still being scanned out, the backend now composites every frame into its own output images. Those are reused at
latch under 0146, and the client's buffers return as soon as the composite has read them: the Steam UI then runs at
the full 120 fps. Hosts that release a buffer only after scanout never take this path and keep forwarding.
## 0149 Wayland backend: verified producer acquire fences for forwarded frames
When the app opts in and the parent Wayland registry actually advertises
`droiddeck_frame_acquire_v1`, Gamescope offers a separate v1 acquire global
to nested clients. A validated native sync_file stays with one matching
surface attachment and commit generation. Pending fences go through the
existing readiness waiter; a failed fence never marks a frame ready.
Only a forwarded, unchanged source buffer can carry its completed fence to
the parent. Composited output, unsupported clients, older hosts, and X11
continue through their existing paths. The host and producer do not need
to upgrade simultaneously to retain the existing copy fallback.
+8
View File
@@ -46,6 +46,9 @@ cd "$WORK"
g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \
tools/gamescope/tests/nested-swapchain.cpp -o pkg/test-nested-swapchain
pkg/test-nested-swapchain
g++ -std=c++17 -Wall -Wextra -Werror -UNDEBUG -I pkg/arch/src/gamescope/src \
tools/gamescope/tests/producer-acquire.cpp -o pkg/test-producer-acquire
env -u GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE pkg/test-producer-acquire
rm -rf out && mkdir -p out/usr/local/bin
PKG=$(ls pkg/arch/gamescope-*.pkg.tar.* | grep -v -- '-debug-' | head -1)
tar -xf "$PKG" -C out --strip-components=2 usr/bin/gamescope
@@ -60,6 +63,11 @@ echo "NEEDED: $NEEDED"
MISSING=""
for lib in $NEEDED; do grep -qx "$lib" tools/gamescope/runtime-sonames.txt || MISSING="$MISSING $lib"; done
if [ -n "$MISSING" ]; then echo "ERROR: not in the runtime:$MISSING"; exit 3; fi
# The signed APK can distinguish the negotiated release from earlier Gamescope
# assets; leave the feature unavailable rather than relying on a filename.
LC_ALL=C grep -aFq 'GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE' out/usr/local/bin/gamescope
mkdir -p out/usr/local/share/droiddeck
printf 'droiddeck-producer-acquire-v1\n' > out/usr/local/share/droiddeck/gamescope-producer-acquire-v1
(cd out && tar --use-compress-program='zstd -19' -cf ../gamescope.tzst usr)
sha256sum gamescope.tzst | tee gamescope.tzst.sha256
ls -l gamescope.tzst out/usr/local/bin/gamescope
@@ -0,0 +1,693 @@
diff --git a/protocol/droiddeck-frame-acquire-v1.xml b/protocol/droiddeck-frame-acquire-v1.xml
new file mode 100644
index 0000000..f056b6e
--- /dev/null
+++ b/protocol/droiddeck-frame-acquire-v1.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="droiddeck_frame_acquire_v1">
+ <interface name="droiddeck_frame_acquire_v1" version="1">
+ <description summary="DroidDeck producer write completion for a single Wayland attachment">
+ Optional explicit acquire sideband independent of DRM syncobj and buffer
+ allocation. Binding does not opt the client out of ordinary wl_buffer
+ release or existing synchronization protocols. The server advertises it
+ only when it implements all semantics for the selected display path.
+ </description>
+ <request name="destroy" type="destructor"/>
+ <enum name="error">
+ <entry name="invalid_attachment" value="0" summary="not the same client's pending DMA-BUF attachment"/>
+ <entry name="duplicate_fence" value="1" summary="that attachment already has an acquire fence"/>
+ <entry name="invalid_fence" value="2" summary="not a real successfully signaled Linux sync_file"/>
+ </enum>
+ <request name="set_acquire_fence">
+ <description summary="set a one-shot kernel sync_file for the pending attachment">
+ After wl_surface.attach of a non-null buffer, and before its next
+ wl_surface.commit, send the producer's final writer fence for that
+ exact attachment. This outer probe requires that fence to have already
+ successfully signaled. The fence must be a real Linux sync_file, not a
+ dma-buf, eventfd, or Vulkan OPAQUE_FD. The server consumes its received
+ descriptor once for that attachment; the caller closes its local FD
+ after marshalling.
+
+ The receiver validates the matching pending surface and buffer and
+ validates the descriptor. A duplicate, invalid, pending or mismatched
+ request is a protocol error; it is never downgraded to implicit sync. Another attach (even the same
+ wl_buffer), detach, surface/resource loss or supersession makes the
+ old proof inapplicable. Metadata-only commits may amend receiver-side
+ still-pending state but cannot introduce or re-use a fence themselves.
+ If no request was made, the receiver keeps its established safe path.
+ If a valid fence has been accepted and later the layer is ineligible,
+ the buffer must not be copied/read before that fence is satisfied or
+ imported as the source dependency. Transport never implies readiness
+ on missed deadlines and never changes release/retirement requirements.
+ </description>
+ <arg name="surface" type="object" interface="wl_surface"/>
+ <arg name="buffer" type="object" interface="wl_buffer"/>
+ <arg name="fence" type="fd" summary="producer's native acquire sync_file"/>
+ </request>
+ </interface>
+</protocol>
diff --git a/protocol/droiddeck-game-frame-acquire-v1.xml b/protocol/droiddeck-game-frame-acquire-v1.xml
new file mode 100644
index 0000000..1b8c2a5
--- /dev/null
+++ b/protocol/droiddeck-game-frame-acquire-v1.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<protocol name="droiddeck_game_frame_acquire_v1">
+ <interface name="droiddeck_game_frame_acquire_v1" version="1">
+ <description summary="guest producer acquire fence">
+ Immediately after wl_surface.attach and before the associated nonempty
+ commit, submit the successful or pending Linux sync_file representing the
+ final writer of that exact attachment. The caller closes its descriptor
+ after marshalling. This does not change wl_buffer release semantics.
+ Without a genuine positive descriptor, omit the sideband.
+ </description>
+ <request name="set_acquire_fence">
+ <arg name="surface" type="object" interface="wl_surface"/>
+ <arg name="buffer" type="object" interface="wl_buffer"/>
+ <arg name="fence" type="fd"/>
+ </request>
+ </interface>
+</protocol>
diff --git a/protocol/meson.build b/protocol/meson.build
index 71fe31b..1e56fbf 100644
--- a/protocol/meson.build
+++ b/protocol/meson.build
@@ -44,6 +44,8 @@ protocols = [
'gamescope-action-binding.xml',
'droiddeck-refresh-v1.xml',
+ 'droiddeck-game-frame-acquire-v1.xml',
+ 'droiddeck-frame-acquire-v1.xml',
# wlroots protocols
'wlr-layer-shell-unstable-v1.xml',
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 45e32f3..e5cb845 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -43,6 +43,7 @@
#include <fractional-scale-v1-client-protocol.h>
#include <xdg-toplevel-icon-v1-client-protocol.h>
#include <droiddeck-refresh-v1-client-protocol.h>
+#include <droiddeck-frame-acquire-v1-client-protocol.h>
#include "wlr_end.hpp"
#include "drm_include.h"
@@ -143,6 +144,7 @@ namespace gamescope
struct WaylandPlaneState
{
wl_buffer *pBuffer;
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
int32_t nDestX;
int32_t nDestY;
double flSrcX;
@@ -755,6 +757,8 @@ namespace gamescope
virtual bool HackTemporarySetDynamicRefresh( int nRefresh ) override;
std::span<const uint32_t> GetHostRefreshRates() const;
+ droiddeck_frame_acquire_v1 *GetHostAcquire() const { return m_pHostAcquire; }
+ bool SupportsDroidDeckProducerAcquire() const override { return m_pHostAcquire != nullptr; }
void SyncHostRefreshTarget();
virtual bool SupportsExplicitSync() const override;
@@ -893,6 +897,7 @@ namespace gamescope
OwningRc<CVulkanTexture> m_pBlackTexture;
wp_presentation *m_pPresentation = nullptr;
droiddeck_refresh_v1 *m_pHostRefresh = nullptr;
+ droiddeck_frame_acquire_v1 *m_pHostAcquire = nullptr;
std::array<uint32_t, 16> m_HostRefreshRates{};
std::atomic<uint32_t> m_uHostRefreshRateCount = { 0 };
std::vector<uint32_t> m_PendingHostRefreshRates;
@@ -1613,6 +1618,8 @@ namespace gamescope
{
std::unique_lock lock( m_PlaneStateLock );
m_oCurrentPlaneState = oState;
+ if (m_oCurrentPlaneState)
+ m_oCurrentPlaneState->pProducerFence.reset();
}
if ( oState )
@@ -1760,6 +1767,12 @@ namespace gamescope
// The x/y here does nothing? Why? What is it for...
// Use the subsurface set_position thing instead.
wl_surface_attach( m_pSurface, oState->pBuffer, 0, 0 );
+ if ( auto *manager = m_pBackend->GetHostAcquire(); manager && oState->pProducerFence )
+ {
+ const int fd = oState->pProducerFence->SignaledFd();
+ if (fd >= 0)
+ droiddeck_frame_acquire_v1_set_acquire_fence(manager, m_pSurface, oState->pBuffer, fd);
+ }
wl_surface_damage( m_pSurface, 0, 0, INT32_MAX, INT32_MAX );
wl_surface_set_opaque_region( m_pSurface, oState->bOpaque ? m_pBackend->GetFullRegion() : nullptr );
wl_surface_set_buffer_scale( m_pSurface, 1 );
@@ -1815,6 +1828,7 @@ namespace gamescope
ClipPlane( WaylandPlaneState
{
.pBuffer = pBuffer,
+ .pProducerFence = pLayer->pProducerFence,
.nDestX = int32_t( -pLayer->offset.x ),
.nDestY = int32_t( -pLayer->offset.y ),
.flSrcX = 0.0,
@@ -2812,6 +2826,12 @@ namespace gamescope
wl_output_add_listener( pOutput , &s_OutputListener, this );
m_pOutputs.emplace( std::make_pair<struct wl_output *, WaylandOutputInfo>( std::move( pOutput ), WaylandOutputInfo{} ) );
}
+ else if ( droiddeck::ProducerAcquireEnabled() &&
+ uVersion >= 1 && !strcmp( pInterface, droiddeck_frame_acquire_v1_interface.name ) && !m_pHostAcquire )
+ {
+ m_pHostAcquire = static_cast<droiddeck_frame_acquire_v1 *>(
+ wl_registry_bind( pRegistry, uName, &droiddeck_frame_acquire_v1_interface, 1u ) );
+ }
else if ( !strcmp( pInterface, droiddeck_refresh_v1_interface.name ) )
{
m_pHostRefresh = (droiddeck_refresh_v1 *)wl_registry_bind( pRegistry, uName, &droiddeck_refresh_v1_interface, 1u );
diff --git a/src/WaylandServer/WaylandServerLegacy.h b/src/WaylandServer/WaylandServerLegacy.h
index 63ee2ca..0164853 100644
--- a/src/WaylandServer/WaylandServerLegacy.h
+++ b/src/WaylandServer/WaylandServerLegacy.h
@@ -3,9 +3,11 @@
#include <wayland-server-core.h>
#include "WaylandDecls.h"
#include <memory>
+#include <unordered_map>
#include <optional>
#include <vector>
#include "vulkan_include.h"
+#include "droiddeck_producer_fence.hpp"
#include "wlr_begin.hpp"
@@ -57,6 +59,10 @@ struct wlserver_wl_surface_info
uint64_t desired_present_time = 0;
uint64_t last_refresh_cycle = 0;
+ const void *producerPendingAttachment = nullptr;
+ droiddeck::PendingProducerFence producerFence;
+ std::unordered_map<uint32_t, droiddeck::PendingProducerFence> committedProducerFences;
+ struct wl_listener producerFenceClientCommit;
};
wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf);
diff --git a/src/backend.h b/src/backend.h
index 9a27711..9fe0c15 100644
--- a/src/backend.h
+++ b/src/backend.h
@@ -377,6 +377,7 @@ namespace gamescope
virtual bool IsSessionBased() const = 0;
virtual bool SupportsExplicitSync() const = 0;
+ virtual bool SupportsDroidDeckProducerAcquire() const { return false; }
// Dumb helper we should remove to support multi display someday.
gamescope::GamescopeScreenType GetScreenType()
diff --git a/src/commit.cpp b/src/commit.cpp
index fbfb550..cd35202 100644
--- a/src/commit.cpp
+++ b/src/commit.cpp
@@ -55,7 +55,9 @@ void commit_t::OnPollIn()
{
std::unique_lock lock( m_WaitableCommitStateMutex );
- if ( !CloseFenceInternal() )
+ const bool bFailedProducerFence = m_bProducerFence &&
+ droiddeck::ProducerFenceStatus(m_nCommitFence) != 1;
+ if ( !CloseFenceInternal() || bFailedProducerFence )
return;
}
@@ -115,12 +117,13 @@ bool commit_t::CloseFenceInternal()
return true;
}
-void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame )
+void commit_t::SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame, bool bProducerFence )
{
std::unique_lock lock( m_WaitableCommitStateMutex );
CloseFenceInternal();
m_nCommitFence = nFence;
+ m_bProducerFence = bProducerFence;
m_bMangoNudge = bMangoNudge;
m_uMangoMsgType = uMangoMsgType;
m_bDroidDeckHudFrame = bDroidDeckHudFrame;
diff --git a/src/commit.h b/src/commit.h
index ae767b6..99b32ae 100644
--- a/src/commit.h
+++ b/src/commit.h
@@ -35,13 +35,14 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable,
// Returns true if we had a fence that was closed.
bool CloseFenceInternal();
- void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame = false );
+ void SetFence( int nFence, bool bMangoNudge, uint32_t uMangoMsgType, const std::shared_ptr<CommitDoneList_t> &pDoneCommits, bool bDroidDeckHudFrame = false, bool bProducerFence = false );
bool ShouldPreemptivelyUpscale( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler );
struct wlr_buffer *buf = nullptr;
gamescope::Rc<CVulkanTexture> vulkanTex;
std::optional<UpscaledTexture_t> upscaledTexture;
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
gamescope::Rc<CVulkanTexture> GetTexture( GamescopeUpscaleFilter eFilter, GamescopeUpscaleScaler eScaler, GamescopeAppTextureColorspace &colorspace )
{
@@ -79,6 +80,7 @@ struct commit_t final : public gamescope::RcObject, public gamescope::IWaitable,
std::mutex m_WaitableCommitStateMutex;
int m_nCommitFence = -1;
+ bool m_bProducerFence = false;
bool m_bMangoNudge = false;
// Typed mangoapp stream to nudge, 0 for none, never the legacy type.
uint32_t m_uMangoMsgType = 0;
diff --git a/src/droiddeck_producer_fence.hpp b/src/droiddeck_producer_fence.hpp
new file mode 100644
index 0000000..5e7dd9d
--- /dev/null
+++ b/src/droiddeck_producer_fence.hpp
@@ -0,0 +1,67 @@
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <linux/sync_file.h>
+#include <memory>
+#include <sys/ioctl.h>
+#include <unistd.h>
+#include <utility>
+
+namespace droiddeck
+{
+ inline bool ProducerAcquireEnabled()
+ {
+ static const bool enabled = [] {
+ const char *value = std::getenv("GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE");
+ return value && std::strcmp(value, "1") == 0;
+ }();
+ return enabled;
+ }
+
+ // Status 1 is success, 0 is pending, everything else is unsafe.
+ inline int ProducerFenceStatus(int fd)
+ {
+ sync_file_info info{};
+ if (fd < 0 || ioctl(fd, SYNC_IOC_FILE_INFO, &info) < 0 || !info.num_fences)
+ return -1;
+ return info.status;
+ }
+
+ class ProducerFence
+ {
+ public:
+ explicit ProducerFence(int fd) : m_fd(fd) {}
+ ProducerFence(ProducerFence &&other) noexcept : m_fd(other.TakeFd()) {}
+ ProducerFence(const ProducerFence &) = delete;
+ ProducerFence &operator=(const ProducerFence &) = delete;
+ ~ProducerFence() { if (m_fd >= 0) close(m_fd); }
+
+ int SyncStatus() const { return ProducerFenceStatus(m_fd); }
+ int Dup() const { return m_fd < 0 ? -1 : fcntl(m_fd, F_DUPFD_CLOEXEC, 0); }
+ int SignaledFd() const { return SyncStatus() == 1 ? m_fd : -1; }
+ int Fd() const { return m_fd; }
+ int TakeFd() { return std::exchange(m_fd, -1); }
+
+ private:
+ int m_fd;
+ };
+
+ // This slot belongs to one nested surface and is cleared by *every*
+ // attach request, even if the client reuses the same wl_buffer object.
+ struct PendingProducerFence
+ {
+ std::shared_ptr<ProducerFence> fence;
+ uint32_t sequence = 0;
+ const void *buffer = nullptr;
+
+ std::shared_ptr<ProducerFence> Consume(bool attached, uint32_t seq, const void *current)
+ {
+ auto owned = std::exchange(fence, {});
+ const bool same = attached && seq == sequence && current && current == buffer;
+ return same ? owned : nullptr;
+ }
+ };
+}
diff --git a/src/rendervulkan.hpp b/src/rendervulkan.hpp
index 8ae3b71..235cfc0 100644
--- a/src/rendervulkan.hpp
+++ b/src/rendervulkan.hpp
@@ -281,6 +281,8 @@ enum AlphaBlendingMode_t
//#define DRM_MODE_BLEND_COVERAGE 1
//#define DRM_MODE_BLEND_PIXEL_NONE 2
+namespace droiddeck { class ProducerFence; }
+
struct FrameInfo_t
{
bool useFSRLayer0;
@@ -309,6 +311,7 @@ struct FrameInfo_t
struct Layer_t
{
gamescope::Rc<CVulkanTexture> tex;
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
int zpos;
vec2_t offset;
@@ -378,6 +381,7 @@ struct FrameInfo_t
if ( m_nCount >= k_nMaxLayers )
return nullptr;
+ m_Layers[m_nCount].pProducerFence.reset();
return &m_Layers[ m_nCount++ ];
}
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index c2e04ab..f5b744b 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -2559,6 +2559,7 @@ paint_cached_base_layer(const gamescope::Rc<commit_t>& commit, const BaseLayerIn
layer->tex = commit->GetTexture( base.eUpscaleFilter, base.eUpscaleScaler, layer->colorspace );
layer->filter = base.filter;
+ layer->pProducerFence = layer->tex == commit->vulkanTex ? commit->pProducerFence : nullptr;
if ( layer->tex == commit->vulkanTex )
{
if ( base.uOutputWidth == currentOutputWidth && base.uOutputHeight == currentOutputHeight )
@@ -2670,6 +2671,7 @@ paint_window_commit( const gamescope::Rc<commit_t> &lastCommit, steamcompmgr_win
layer->filter = ( flags & PaintWindowFlag::NoFilter ) ? GamescopeUpscaleFilter::LINEAR : frameInfo->eUpscaleFilter;
layer->tex = lastCommit->GetTexture( layer->filter, frameInfo->eUpscaleScaler, layer->colorspace );
+ layer->pProducerFence = layer->tex == lastCommit->vulkanTex ? lastCommit->pProducerFence : nullptr;
if ( flags & PaintWindowFlag::NoScale )
{
@@ -8915,7 +8917,7 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
already_exists = true;
}
- if ( already_exists && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() )
+ if ( already_exists && !reslistentry.pProducerFence && !reslistentry.feedback && reslistentry.presentation_feedbacks.empty() )
{
wlserver_lock();
wlr_buffer_unlock( buf );
@@ -8957,6 +8959,8 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
droiddeck::frame_trace::Event::ImportSucceededOther,
bTraceCurrent );
+ newCommit->pProducerFence = std::move(reslistentry.pProducerFence);
+ const bool bProducerFence = bool(newCommit->pProducerFence);
int fence = -1;
global_focus_t *pCurrentFocus = GetCurrentFocus();
@@ -9104,7 +9108,24 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
pBackendFb->SetBuffer( buf );
}
- if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent )
+ if ( bProducerFence )
+ {
+ const int status = newCommit->pProducerFence->SyncStatus();
+ if ( status != 0 && status != 1 )
+ return; // A failed producer write may not be marked ready.
+ bKnownReady = status == 1;
+ if ( !bKnownReady )
+ {
+ fence = newCommit->pProducerFence->Dup();
+ if ( fence < 0 )
+ {
+ // Still wait on original; this commit cannot forward proof.
+ fence = newCommit->pProducerFence->TakeFd();
+ newCommit->pProducerFence.reset();
+ }
+ }
+ }
+ else if ( eventFd != gamescope::CAcquireTimelinePoint::k_InvalidEvent )
{
fence = eventFd.first;
bKnownReady = eventFd.second;
@@ -9127,13 +9148,13 @@ void update_wayland_res(const std::shared_ptr<CommitDoneList_t> &doneCommits, st
if ( cv_commit_ready_check )
{
- if ( !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) )
+ if ( !bProducerFence && !bKnownReady && fence >= 0 && commit_fence_ready_now( fence ) )
bKnownReady = true;
note_commit_fence( bKnownReady );
}
gpuvis_trace_printf( "pushing wait for commit %lu win %lx", newCommit->commitID, w->type == steamcompmgr_win_type_t::XWAYLAND ? w->xwayland().id : 0 );
{
- newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted() );
+ newCommit->SetFence( fence, mango_nudge, uMangoMsgType, doneCommits, bDroidDeckHudFrame && droiddeck_hud_frames_wanted(), bProducerFence );
if ( bKnownReady )
{
newCommit->Signal();
diff --git a/src/wlserver.cpp b/src/wlserver.cpp
index 84602c0..6a4f4da 100644
--- a/src/wlserver.cpp
+++ b/src/wlserver.cpp
@@ -57,6 +57,7 @@
#include "gamescope-private-protocol.h"
#include "gamescope-swapchain-protocol.h"
#include "presentation-time-protocol.h"
+#include "droiddeck-game-frame-acquire-v1-protocol.h"
#include "wlserver.hpp"
#include "hdmi.h"
@@ -136,7 +137,8 @@ std::vector<ResListEntry_t>& gamescope_xwayland_server_t::retrieve_commits()
gamescope::ConVar<bool> cv_drm_debug_syncobj_force_wait_on_commit( "drm_debug_syncobj_force_wait_on_commit", false, "Force a wait on DRM sync objects before committing buffers" );
-ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf )
+ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf,
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence )
{
auto wl_surf = get_wl_surface_info( surf );
@@ -168,7 +170,8 @@ ResListEntry_t PrepareCommit( struct wlr_surface *surf, struct wlr_buffer *buf )
wl_surf->present_id,
wl_surf->desired_present_time,
std::move( pAcquirePoint ),
- std::move( pReleasePoint )
+ std::move( pReleasePoint ),
+ bExplicitSync ? nullptr : std::move( pProducerFence )
};
wl_surf->present_id = std::nullopt;
wl_surf->desired_present_time = 0;
@@ -216,6 +219,12 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) {
? droiddeck::frame_trace::Event::SurfaceCommitBuffer
: droiddeck::frame_trace::Event::SurfaceCommitNoBuffer );
+ // Capture state before the existing damage/attach flags are reset.
+ const bool bAttached = wlr_surface->current.committed & WLR_SURFACE_STATE_BUFFER;
+ auto &proofs = get_wl_surface_info(wlr_surface)->committedProducerFences;
+ auto proof = proofs.extract(wlr_surface->current.seq);
+ auto pProducerFence = proof.empty() ? nullptr : proof.mapped().Consume(
+ bAttached, wlr_surface->current.seq, wlr_surface->current.buffer );
wlr_surface->current.committed = 0;
wlserver_x11_surface_info *wlserver_x11_surface_info = get_wl_surface_info(wlr_surface)->x11_surface;
@@ -249,7 +258,14 @@ void xwayland_surface_commit(struct wlr_surface *wlr_surface) {
gpuvis_trace_printf( "xwayland_surface_commit wlr_surface %p", wlr_surface );
- ResListEntry_t entry = PrepareCommit( wlr_surface, buf );
+ // A texture may still designate older storage after a rejected/no-op import.
+ if ( pProducerFence )
+ {
+ struct wlr_dmabuf_attributes dmabuf{};
+ if ( wlr_surface->current.buffer != buf || !wlr_buffer_get_dmabuf(buf, &dmabuf) )
+ pProducerFence.reset();
+ }
+ ResListEntry_t entry = PrepareCommit( wlr_surface, buf, std::move(pProducerFence) );
if (wlserver_x11_surface_info)
{
@@ -612,6 +628,31 @@ wlserver_wl_surface_info *get_wl_surface_info(struct wlr_surface *wlr_surf)
return reinterpret_cast<wlserver_wl_surface_info *>(wlr_surf->data);
}
+// This wlroots signal runs with its own pending.buffer lock, after the
+// pending object has been resolved and before the commit is applied or cached.
+static bool producer_fence_protocol_active();
+
+static void handle_producer_fence_client_commit(wl_listener *listener, void *)
+{
+ wlserver_wl_surface_info *info = wl_container_of(listener, info, producerFenceClientCommit);
+ wlr_surface *surface = info->wlr;
+ info->producerPendingAttachment = nullptr;
+ auto proof = std::exchange(info->producerFence, {});
+ if (!proof.fence || !surface->pending.buffer || proof.sequence != surface->pending.seq ||
+ !(surface->pending.committed & WLR_SURFACE_STATE_BUFFER))
+ return;
+ struct wlr_dmabuf_attributes dmabuf{};
+ if (!wlr_buffer_get_dmabuf(surface->pending.buffer, &dmabuf) ||
+ info->committedProducerFences.size() >= 64 ||
+ info->committedProducerFences.contains(proof.sequence))
+ {
+ wlr_surface_reject_pending(surface, surface->resource, 0, "invalid or excessive producer fence commits");
+ return;
+ }
+ proof.buffer = surface->pending.buffer; // Borrowed from the state lock, no extra release path.
+ info->committedProducerFences.emplace(proof.sequence, std::move(proof));
+}
+
static void handle_wl_surface_commit( struct wl_listener *l, void *data )
{
wlserver_wl_surface_info *surf = wl_container_of( l, surf, commit );
@@ -707,6 +748,7 @@ static void handle_wl_surface_destroy( struct wl_listener *l, void *data )
}
wl_list_remove( &surf->commit.link );
+ wl_list_remove(&surf->producerFenceClientCommit.link);
wl_list_remove( &surf->destroy.link );
delete surf;
@@ -725,6 +767,12 @@ static void wlserver_new_surface(struct wl_listener *l, void *data)
wl_surface_info->commit.notify = handle_wl_surface_commit;
wl_signal_add( &wlr_surf->events.commit, &wl_surface_info->commit );
+ wl_list_init(&wl_surface_info->producerFenceClientCommit.link);
+ if (producer_fence_protocol_active())
+ {
+ wl_surface_info->producerFenceClientCommit.notify = handle_producer_fence_client_commit;
+ wl_signal_add(&wlr_surf->events.client_commit, &wl_surface_info->producerFenceClientCommit);
+ }
wlr_surf->data = wl_surface_info;
@@ -1811,6 +1859,79 @@ static bool filter_global(const struct wl_client *client, const struct wl_global
return server && server->get_output() == output;
}
+static wl_protocol_logger *s_pProducerFenceLogger;
+static wl_global *s_pProducerFenceGlobal;
+
+static bool producer_fence_protocol_active()
+{
+ return s_pProducerFenceGlobal != nullptr;
+}
+
+static void producer_fence_protocol_log( void *, wl_protocol_logger_type direction,
+ const wl_protocol_logger_message *message )
+{
+ if ( direction != WL_PROTOCOL_LOGGER_REQUEST || std::strcmp(message->message->name, "attach") ||
+ std::strcmp(wl_resource_get_class(message->resource), wl_surface_interface.name) ||
+ message->arguments_count != 3 )
+ return;
+ auto *surf = wlr_surface_from_resource(message->resource);
+ if ( auto *info = get_wl_surface_info(surf) )
+ {
+ info->producerFence = {};
+ // Wayland's server demarshaller gives the wl_object at the start
+ // of the wl_resource. Compare identity only, never dereference it.
+ info->producerPendingAttachment = message->arguments[0].o;
+ }
+}
+
+static void set_producer_fence( wl_client *client, wl_resource *manager, wl_resource *surface,
+ wl_resource *buffer, int32_t fd )
+{
+ droiddeck::ProducerFence fence(fd);
+ wlr_surface *surf = surface && wl_resource_get_client(surface) == client
+ ? wlr_surface_from_resource(surface) : nullptr;
+ auto *info = get_wl_surface_info(surf);
+ if (!info || !buffer || wl_resource_get_client(buffer) != client ||
+ !(surf->pending.committed & WLR_SURFACE_STATE_BUFFER) ||
+ info->producerPendingAttachment != buffer || info->producerFence.fence)
+ {
+ wl_resource_post_error(manager, 0, "invalid or duplicate producer fence attachment");
+ return;
+ }
+
+ const int status = fence.SyncStatus();
+ if (status != 0 && status != 1)
+ {
+ wl_resource_post_error(manager, 0, "producer fence requires a real sync_file");
+ return;
+ }
+ info->producerFence = { std::make_shared<droiddeck::ProducerFence>(std::move(fence)),
+ surf->pending.seq };
+}
+
+static const struct droiddeck_game_frame_acquire_v1_interface producer_fence_impl = {
+ .set_acquire_fence = set_producer_fence,
+};
+
+static void bind_producer_fence(wl_client *client, void *, uint32_t, uint32_t id)
+{
+ auto *resource = wl_resource_create(client, &droiddeck_game_frame_acquire_v1_interface, 1, id);
+ if (!resource)
+ {
+ wl_client_post_no_memory(client);
+ return;
+ }
+ wl_resource_set_implementation(resource, &producer_fence_impl, nullptr, nullptr);
+}
+
+static void stop_producer_fence_protocol()
+{
+ if (s_pProducerFenceGlobal)
+ wl_global_destroy(std::exchange(s_pProducerFenceGlobal, nullptr));
+ if (s_pProducerFenceLogger)
+ wl_protocol_logger_destroy(std::exchange(s_pProducerFenceLogger, nullptr));
+}
+
bool wlsession_init( void ) {
static bool s_bInitted = false;
if ( s_bInitted )
@@ -1824,6 +1945,7 @@ bool wlsession_init( void ) {
wl_display_set_global_filter(wlserver.display, filter_global, nullptr);
+
const struct wlserver_output_info output_info = {
.description = "Virtual gamescope output",
};
@@ -2200,6 +2322,18 @@ void wlserver_set_keyboard_layout( const char *pszLayout )
bool wlserver_init( void ) {
assert( wlserver.display != nullptr );
+ // The backend has round-tripped its parent registry before wlserver_init.
+ // Older hosts, non-Wayland backends or an unarmed host keep the original
+ // producer conventions: do not advertise this inner protocol at all.
+ if (droiddeck::ProducerAcquireEnabled() && GetBackend()->SupportsDroidDeckProducerAcquire())
+ {
+ s_pProducerFenceLogger = wl_display_add_protocol_logger(wlserver.display, producer_fence_protocol_log, nullptr);
+ if (s_pProducerFenceLogger)
+ s_pProducerFenceGlobal = wl_global_create(wlserver.display, &droiddeck_game_frame_acquire_v1_interface, 1, nullptr, bind_producer_fence);
+ if (!s_pProducerFenceGlobal)
+ stop_producer_fence_protocol();
+ }
+
wl_list_init(&pending_surfaces);
wlserver.wlr.multi_backend = wlr_multi_backend_create( wlserver.event_loop );
@@ -2345,6 +2479,7 @@ bool wlserver_init( void ) {
{
wl_log.errorf("Failed to start backend");
wlr_backend_destroy( wlserver.wlr.multi_backend );
+ stop_producer_fence_protocol();
wl_display_destroy(wlserver.display);
return false;
}
@@ -2527,6 +2662,7 @@ void wlserver_run(void)
wl_list_remove( &wlserver.session_active.link );
#endif
+ stop_producer_fence_protocol();
wl_display_destroy_clients(wlserver.display);
wl_display_destroy(wlserver.display);
wlserver.display = NULL;
diff --git a/src/wlserver.hpp b/src/wlserver.hpp
index 63542ef..12141b6 100644
--- a/src/wlserver.hpp
+++ b/src/wlserver.hpp
@@ -50,6 +50,7 @@ struct ResListEntry_t {
uint64_t desired_present_time;
std::shared_ptr<gamescope::CAcquireTimelinePoint> pAcquirePoint;
std::shared_ptr<gamescope::CReleaseTimelinePoint> pReleasePoint;
+ std::shared_ptr<droiddeck::ProducerFence> pProducerFence;
};
struct wlserver_content_override;
@@ -0,0 +1,36 @@
#include "droiddeck_producer_fence.hpp"
#include <cassert>
#include <cerrno>
#include <utility>
int main()
{
using namespace droiddeck;
assert(!ProducerAcquireEnabled()); // normal startup, no opt-in
assert(ProducerFenceStatus(-1) < 0);
int ends[2];
assert(pipe(ends) == 0);
const int readEnd = ends[0];
auto fd = std::make_shared<ProducerFence>(readEnd);
assert(fd->SyncStatus() < 0); // ordinary pipe must never become a ready writer fence
assert(fd->SignaledFd() < 0);
int a, b;
PendingProducerFence old{fd, 21, &a};
assert(!old.Consume(true, 22, &a));
assert(!old.fence);
PendingProducerFence different{fd, 21, &a};
assert(!different.Consume(true, 21, &b));
PendingProducerFence empty{fd, 21, &a};
assert(!empty.Consume(false, 21, &a));
PendingProducerFence matching{std::move(fd), 21, &a};
auto consumed = matching.Consume(true, 21, &a);
assert(consumed && !matching.Consume(true, 21, &a)); // never clonable across commits
int dup = consumed->Dup();
assert(dup >= 0 && fcntl(dup, F_GETFD) == FD_CLOEXEC);
consumed.reset();
assert(fcntl(readEnd, F_GETFD) == -1 && errno == EBADF);
assert(fcntl(dup, F_GETFD) == FD_CLOEXEC);
close(dup);
close(ends[1]);
}
@@ -15,7 +15,7 @@ import tempfile
from pathlib import Path
GAME_PREFIX = "DROIDDECK_GAME_"
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR")
GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR", "DROIDDECK_GAME_FRAME_ACQUIRE")
CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"}
SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
+51
View File
@@ -0,0 +1,51 @@
#define _GNU_SOURCE
#include "frame_worker_peer.h"
#include <assert.h>
#include <fcntl.h>
#include <poll.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#include <sys/wait.h>
#include <unistd.h>
static uint64_t start_ticks(pid_t id) {
char proc[64], line[4096]; snprintf(proc,sizeof(proc),"/proc/%d/stat",id);
FILE *f=fopen(proc,"r");assert(f);assert(fgets(line,sizeof(line),f));fclose(f);
uint64_t ticks=0;
assert(dd_worker_parse_start(line,&ticks)==DD_WORKER_STAT_OK);
return ticks;
}
static bool check_maps(const struct dd_worker_grant *g,pid_t id,uint64_t ticks) {
char proc[64],line[4096];snprintf(proc,sizeof(proc),"/proc/%d/maps",id);
FILE *f=fopen(proc,"r");assert(f);bool found=false;
while(fgets(line,sizeof(line),f)) if(dd_worker_grant_matches(g,4,getuid(),id,ticks,4,line)){ found=true;break;}
fclose(f);return found;
}
int main(void){
char p[]="/tmp/dd-live-map.XXXXXX";int fd=mkstemp(p);assert(fd>=0);
assert(ftruncate(fd,4096)==0);struct stat st;assert(fstat(fd,&st)==0);
int a[2],b[2];assert(pipe(a)==0&&pipe(b)==0);pid_t id=fork();assert(id>=0);
if(id==0){
close(a[0]);close(b[1]);
void *m=mmap(NULL,4096,PROT_READ|PROT_EXEC,MAP_PRIVATE,fd,0);assert(m!=MAP_FAILED);
assert(write(a[1],"y",1)==1);
char c;assert(read(b[0],&c,1)==1);assert(mprotect(m,4096,PROT_READ)==0);
assert(write(a[1],"y",1)==1);assert(read(b[0],&c,1)==1);_exit(0);
}
close(a[1]);close(b[0]);char c;assert(read(a[0],&c,1)==1);
int pfd=syscall(SYS_pidfd_open,id,0);assert(pfd>=0);
struct pollfd pfd_poll={.fd=pfd,.events=POLLIN};assert(poll(&pfd_poll,1,0)==0);
uint64_t start=start_ticks(id);assert(start);
struct dd_worker_grant g={.owner=4,.uid=getuid(),.pid=id,.dev_major=major(st.st_dev),.dev_minor=minor(st.st_dev),.ino=st.st_ino,.start_ticks=start,.expires=10,.canonical_file=p,.app_launch_verified=true,.final_go=true};
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED,0,start+1));
assert(!check_maps(&g,id,start+1)); // A forged self receipt fails against live post-exec ticks.
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK,start,start));
assert(check_maps(&g,id,start));
g.final_go=false;assert(!check_maps(&g,id,start));g.final_go=true;
assert(write(b[1],"n",1)==1);assert(read(a[0],&c,1)==1);assert(!check_maps(&g,id,start));
assert(write(b[1],"n",1)==1);assert(poll(&pfd_poll,1,2000)==1);
assert(pfd_poll.revents&POLLIN);int status;assert(waitpid(id,&status,0)==id&&WIFEXITED(status)&&WEXITSTATUS(status)==0);
close(fd); close(pfd);unlink(p); puts("Live executable map, start-time reuse rejection, no-GO revocation, non-executable map rejection, and pidfd exit readiness passed.");
}
+48
View File
@@ -0,0 +1,48 @@
#include "frame_worker_peer.h"
#include <assert.h>
static const char file[]="/app/private/linuxfs/opt/droiddeck-agent/bin/gamescope";
static const char good[]="1000-2000 r-xp 00001000 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope\n";
int main(void) {
uint64_t ticks = 0;
assert(dd_worker_parse_start("650 (with ) parens) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 251191 123\n", &ticks) == DD_WORKER_STAT_OK);
assert(ticks == 251191);
assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 0 123\n", &ticks) == DD_WORKER_STAT_ZERO);
assert(dd_worker_parse_start("650 (x) S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 18446744073709551616 123\n", &ticks) == DD_WORKER_STAT_PARSE);
assert(dd_worker_parse_start("650 (x) S 1 2 3", &ticks) == DD_WORKER_STAT_PARSE);
assert(dd_worker_open_failure(EACCES) == DD_WORKER_STAT_DENIED);
assert(dd_worker_open_failure(EPERM) == DD_WORKER_STAT_DENIED);
assert(dd_worker_open_failure(ENOENT) == DD_WORKER_STAT_HIDDEN);
assert(dd_worker_open_failure(ESRCH) == DD_WORKER_STAT_HIDDEN);
assert(dd_worker_open_failure(EMFILE) == DD_WORKER_STAT_OPEN);
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251191, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OK, 251192, 251191));
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 251191));
assert(dd_worker_receipt_allows_reserve(DD_WORKER_STAT_HIDDEN, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_DENIED, 0, 0));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_OPEN, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_READ, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_PARSE, 0, 251191));
assert(!dd_worker_receipt_allows_reserve(DD_WORKER_STAT_ZERO, 0, 251191));
struct dd_worker_grant g={.owner=3,.uid=10197,.pid=650,.dev_major=254,.dev_minor=21,
.start_ticks=251191,.ino=5502,.expires=1000,.canonical_file=file,.app_launch_verified=true,.final_go=true};
assert(dd_worker_grant_matches(&g,3,10197,650,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,1000,good));
assert(!dd_worker_grant_matches(&g,4,10197,650,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10198,650,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,651,251191,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,650,251192,999,good));
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,NULL));
const char *invalid[]={
"1000-2000 r--p 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope",
"1000-2000 r-xp 0 fe:15 5503 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope",
"1000-2000 r-xp 0 fe:16 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope",
"1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope (deleted)",
"1000-2000 r-xp 0 fe:15 5502 /app/private/linuxfs/opt/droiddeck-agent/bin/gamescope.bak",
"1000-2000 r-xp 0 fe:15 5502 /system/lib64/libddexec.so", "", NULL};
for (int i=0;invalid[i];i++) assert(!dd_worker_map_matches(&g,invalid[i]));
g.final_go=false;
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good));
g.final_go=true; g.app_launch_verified=false;
assert(!dd_worker_grant_matches(&g,3,10197,650,251191,999,good));
}
+2
View File
@@ -26,6 +26,8 @@ struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, v
struct wl_resource { struct wl_list listeners; int acquired, releases, errors; };
struct dmabuf_buffer { int unused; };
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE };
/* These release fixtures exercise legacy attachments, which own no acquire FD. */
#define dd_frame_acquire_clear(slot) ((void)0)
struct surface {
struct wl_list link;
struct wl_resource *dmabuf;
@@ -74,6 +74,11 @@ static int poll(struct pollfd *p, unsigned n, int timeout) {
}
static int fcntl(int fd, int cmd, int arg) { (void)cmd; (void)arg; dup_of[next_dup] = fd; return next_dup++; }
static int close(int fd) { closed[fd]++; return 0; }
struct dd_frame_acquire { int fd_plus_one; };
static void dd_frame_acquire_clear(struct dd_frame_acquire *f) {
if (f->fd_plus_one) close(f->fd_plus_one - 1);
f->fd_plus_one = 0;
}
struct wl_event_source { int fd; int (*fd_cb)(int, uint32_t, void *); int (*timer_cb)(void *); void *data; int armed_ms, removed; };
struct wl_event_loop;
@@ -121,6 +126,7 @@ struct surface {
struct wl_resource *resource, *xdg_toplevel;
int toplevel_committed;
struct wl_resource *pending_buffer;
struct dd_frame_acquire pending_frame_acquire;
struct wl_listener pending_buffer_destroy;
int pending_attach, pending_src_set, pending_dst_set, pending_opaque_set;
float pending_src[4];
@@ -146,6 +152,7 @@ FUNCTIONS
static void surface_state_apply(struct surface *s, struct surface_state *st) {
(void)s;
dd_frame_acquire_clear(&st->frame_acquire);
applies++;
applied_attach = st->attach;
applied_buffer = st->attach ? st->buffer : NULL;
@@ -0,0 +1,81 @@
"""Focused worker-grant contract; no Android or guest boot required."""
import os
import sys
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT=Path(__file__).resolve().parents[2]
SRC=ROOT/'app/src/main/cpp/waylandcomp/src'
JAVA=ROOT/'app/src/main/java/com/droiddeck/launcher'
class FrameAcquirePeerGateTest(unittest.TestCase):
def test_app_issued_identity_and_executable_mapping(self):
with tempfile.TemporaryDirectory() as tmp:
image=Path(tmp)/'probe'
subprocess.run([os.environ.get('CC','cc'), '-std=c11','-Wall','-Wextra','-Werror',
'-I',str(SRC),str(Path(__file__).with_name('frame_worker_peer_test.c')),
'-o',str(image)],check=True)
subprocess.run([str(image)],check=True,timeout=10)
@unittest.skipUnless(sys.platform.startswith("linux"), "Requires Linux procfs and pidfd")
def test_live_worker_mapping_starttime_and_revocation(self):
with tempfile.TemporaryDirectory() as tmp:
image = Path(tmp) / "probe"
subprocess.run([os.environ.get("CC", "cc"), "-std=c11", "-Wall", "-Wextra", "-Werror",
"-I", str(SRC), str(Path(__file__).with_name("frame_worker_peer_live_test.c")),
"-o", str(image)], check=True)
subprocess.run([str(image)], check=True, timeout=10)
def test_publish_before_worker_go_and_require_map_at_bind(self):
workers=(JAVA/'runtime/GuestWorkers.kt').read_text()
broker=workers.split("private fun start(",1)[1].split("private fun takeWarm",1)[0]
check=broker.index("if (stopping() || !confirmed())")
publish=broker.index("FrameAcquireWorkerProbe.publish",check)
self.assertLess(publish,broker.index("Os.write(go[1]",check))
self.assertIn("if (slot.service === service) startTicks else 0L",broker)
self.assertIn("val size = reply.dataAvail()",broker)
self.assertIn("if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)",broker)
service=workers.split("override fun onTransact",1)[1].split("Handler(",1)[0]
self.assertIn("data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG",service)
self.assertIn("Binder.getCallingUid() == Process.myUid()",service)
self.assertIn("data.dataAvail() == Int.SIZE_BYTES",service)
self.assertIn("reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))",service)
self.assertIn('if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke',workers)
comp=(SRC/'compositor.c').read_text()
bind=comp.split('static void bind_frame_acquire',1)[1].split('#endif',1)[0]
self.assertIn('frame_acquire_peer_allowed(client, true, true)',bind)
self.assertIn('poll(&alive, 1, 0) == 0',comp)
def test_admission_diagnostics_are_coarse_bounded_and_probe_only(self):
kt=(JAVA/'runtime/FrameAcquireWorkerProbe.kt').read_text()
comp=(SRC/'compositor.c').read_text()
jni=(SRC/'waylandcomp_jni.c').read_text()
prepare=kt.split('fun prepare(',1)[1].split('fun arm(',1)[0]
match=kt.split('fun match(',1)[1].split('fun publish(',1)[0]
self.assertIn('!WaylandCompositor.frameWorkerProbeEnabled()',prepare)
self.assertIn('context.assets.open("linuxfs" + PATH)',prepare)
self.assertIn('context.assets.open("linuxfs" + SESSION_SCRIPT)',prepare)
svc=(JAVA/'session/SessionService.kt').read_text()
self.assertIn('SessionPrefs.producerAcquireFences(this)',svc)
self.assertIn('nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment',svc)
prefs=(JAVA/'session/SessionPrefs.kt').read_text()
self.assertIn('getBoolean("producerAcquireFences", false)',prefs)
self.assertLess(match.index('?: return null'),match.index('breadcrumb('))
self.assertIn('"--version" !in argv',match)
self.assertIn('if (reported.add(stage))',kt)
self.assertIn('"worker_admission=" + reason.name',kt)
for name in ('MATCH_ACK','MATCH_OWNER','MATCH_EXPIRED','MATCH_PATH','MATCH_ROOT',
'MATCH_ARGV','MATCH_FILE','MATCH_DIGEST','QUALIFIED','PUBLISH_TICKET',
'PUBLISH_RESTAT','PUBLISH_NATIVE','PUBLISH_RECEIPT','RESERVED'):
self.assertIn('Reason.'+name,kt)
self.assertIn(' return JNI_FALSE;\n#endif',jni.split('frameWorkerProbeEnabled(',1)[1])
self.assertIn('if (!frame_worker_map_reported)',comp)
for name in ('NATIVE_FILE','NATIVE_PIDFD','NATIVE_STAT_OPEN_DENIED','NATIVE_STAT_OPEN_HIDDEN',
'NATIVE_STAT_OPEN_OTHER','NATIVE_STAT_READ','NATIVE_STAT_PARSE','NATIVE_STAT_ZERO',
'NATIVE_STAT_MISMATCH','NATIVE_PIDFD_NOT_LIVE','NATIVE_ALREADY_RESERVED',
'MAP_STARTTIME','MAP_OPEN','MAP_IDENTITY'):
self.assertIn('"worker_admission='+name+'"',comp)
+166
View File
@@ -0,0 +1,166 @@
"""Exercise production receiver and attachment replacement with Unix FD passing.
This Linux fixture stubs Wayland resources and only the success/status values of
SYNC_IOC_FILE_INFO. It does not claim a Vulkan or SurfaceFlinger hardware test.
"""
import os
from pathlib import Path
import platform
import subprocess
import tempfile
import unittest
from test_vk_pending_completion import function
SRC = Path(__file__).resolve().parents[2] / 'app/src/main/cpp/waylandcomp/src'
HEAD = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <errno.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/sync_file.h>
static int query_status, query_result;
static unsigned query_count;
static int test_ioctl(int fd, unsigned long request, void *arg) {
assert(fd >= 0 && request == SYNC_IOC_FILE_INFO);
struct sync_file_info *info = arg;
assert(!info->flags && !info->sync_fence_info);
query_count++;
info->status = query_status;
info->num_fences = 1;
return query_result;
}
#define ioctl test_ioctl
#include "frame_acquire.h"
#undef ioctl
#include "wayland-util.h"
void wl_list_init(struct wl_list *list) { list->prev = list->next = list; }
void wl_list_remove(struct wl_list *list) { (void)list; }
struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); };
struct wl_client { int identity; };
struct wl_resource { struct wl_client *owner; void *data; int type; unsigned error; };
struct surface {
struct wl_resource *pending_buffer;
struct wl_listener pending_buffer_destroy;
struct dd_frame_acquire pending_frame_acquire;
int pending_attach;
};
static int wl_surface_interface, surface_impl;
static int peer_allowed=1;
static int frame_acquire_peer_allowed(const struct wl_client *c, bool verify_exec, bool bind) { (void)c; (void)verify_exec; (void)bind; return peer_allowed; }
static struct wl_client *wl_resource_get_client(struct wl_resource *r) { return r->owner; }
static void *wl_resource_get_user_data(struct wl_resource *r) { return r->data; }
static int wl_resource_instance_of(struct wl_resource *r, const void *iface, const void *impl) {
assert(iface == &wl_surface_interface && impl == &surface_impl);
return r->type == 1;
}
static int get_dmabuf(struct wl_resource *r) { return r->type == 2; }
static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { (void)r; (void)l; }
static void wl_resource_post_error(struct wl_resource *r, unsigned err, const char *why) {
assert(why && !r->error);
r->error = err+1;
}
'''
TAIL = r'''
/* Real descriptor transfer and sender close; before dispatch, receiver owns it. */
static int tx(int fd) {
int conn[2]; char byte = 'F';
assert(socketpair(AF_UNIX, SOCK_DGRAM, 0, conn) == 0);
union { struct cmsghdr a; char bytes[CMSG_SPACE(sizeof(fd))]; } control = {0};
struct iovec payload = {.iov_base=&byte, .iov_len=1};
struct msghdr msg = {.msg_iov=&payload, .msg_iovlen=1, .msg_control=control.bytes,
.msg_controllen=sizeof(control.bytes)};
struct cmsghdr *h = CMSG_FIRSTHDR(&msg);
h->cmsg_len=CMSG_LEN(sizeof(fd)); h->cmsg_level=SOL_SOCKET; h->cmsg_type=SCM_RIGHTS;
memcpy(CMSG_DATA(h), &fd, sizeof(fd));
assert(sendmsg(conn[0], &msg, 0) == 1);
assert(close(fd) == 0);
memset(&control, 0, sizeof(control));
assert(recvmsg(conn[1], &msg, MSG_CMSG_CLOEXEC) == 1);
assert(!(msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) && byte == 'F');
h=CMSG_FIRSTHDR(&msg);
assert(h && h->cmsg_len==CMSG_LEN(sizeof(fd)) && h->cmsg_level==SOL_SOCKET && h->cmsg_type==SCM_RIGHTS);
memcpy(&fd, CMSG_DATA(h), sizeof(fd));
close(conn[0]); close(conn[1]);
return fd;
}
static int transmit_fd(void) {
int p[2]; assert(pipe(p) == 0); close(p[1]); return tx(p[0]);
}
static void closed(int fd) {
assert(fcntl(fd, F_GETFD) == -1 && errno == EBADF);
}
int main(void) {
struct wl_client client={1}, unrelated={2};
struct surface s={0};
struct wl_resource manager={.owner=&client}, surf={.owner=&client,.data=&s,.type=1};
struct wl_resource buf={.owner=&client,.type=2}, other={.owner=&client,.type=2};
struct wl_resource wrong_owner={.owner=&unrelated,.type=2}, not_dmabuf={.owner=&client,.type=3};
int fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(manager.error == 1 && !query_count); closed(fd);
surface_attach(&client,&surf,&buf,0,0);
struct wl_resource *bad[] = {&other, &wrong_owner, &not_dmabuf, NULL};
for (unsigned i=0; i<sizeof(bad)/sizeof(*bad); i++) {
fd=transmit_fd(); manager.error=0;
frame_acquire_set(&client,&manager,&surf,bad[i],fd);
assert(manager.error == 1 && !query_count); closed(fd);
}
manager.error=0; query_status=1; fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(!manager.error && query_count==1 && s.pending_frame_acquire.fd_plus_one==fd+1);
int display_fd=dd_frame_acquire_dup(&s.pending_frame_acquire);
assert(display_fd>=0 && display_fd!=fd && (fcntl(display_fd,F_GETFD)&FD_CLOEXEC));
close(display_fd);
int duplicate=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,duplicate);
assert(manager.error==2 && query_count==1); closed(duplicate);
/* The same Wayland buffer, attached a second time, is a different write. */
surface_attach(&client,&surf,&buf,0,0);
assert(dd_frame_acquire_dup(&s.pending_frame_acquire)==-1); closed(fd);
for (int status=0; status>=-2; status--) {
manager.error=0; query_status=status;
if (status==-2) query_result=-1; /* non-sync file ioctl failure */
fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(manager.error == 3 && !s.pending_frame_acquire.fd_plus_one); closed(fd);
}
manager.error=0; query_result=0; query_status=1;
fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(!manager.error);
on_pending_buffer_destroyed(&s.pending_buffer_destroy,NULL);
assert(!s.pending_buffer && !s.pending_frame_acquire.fd_plus_one); closed(fd);
peer_allowed=0; manager.error=0;
surface_attach(&client,&surf,&buf,0,0);
fd=transmit_fd();
frame_acquire_set(&client,&manager,&surf,&buf,fd);
assert(manager.error==4&&!s.pending_frame_acquire.fd_plus_one);closed(fd);
return 0;
}
'''
@unittest.skipUnless(platform.system() == 'Linux', 'Linux sync_file UAPI')
class FrameAcquireProtocolTest(unittest.TestCase):
def test_production_receiver_rejects_invalid_and_keeps_exact_attachment(self):
comp = (SRC / 'compositor.c').read_text()
protocol = (SRC.parent / 'generated/droiddeck-frame-acquire-v1-server-protocol.h').read_text()
errors = protocol.split('enum droiddeck_frame_acquire_v1_error {', 1)[1].split('};', 1)[0]
actual = '\n'.join(function(comp, name) for name in (
'on_pending_buffer_destroyed', 'surface_attach', 'frame_acquire_set'))
with tempfile.TemporaryDirectory(prefix='droiddeck-frame-acquire-') as tmp:
probe = Path(tmp) / 'probe.c'
exe = Path(tmp) / 'probe'
probe.write_text(HEAD + '\nenum droiddeck_frame_acquire_v1_error {' + errors + '};\n' + actual + TAIL)
subprocess.run([os.environ.get('CC', 'cc'), '-std=gnu11', '-Wall', '-Wextra',
'-Werror', '-Wno-unused-parameter', '-UNDEBUG', '-fsanitize=address,undefined',
'-I', str(SRC), '-I', str(SRC.parent / 'prebuilt/include'),
str(probe), '-o', str(exe)], check=True)
subprocess.run([str(exe)], check=True, timeout=10)
+10
View File
@@ -24,6 +24,16 @@ STATE = tempfile.TemporaryDirectory()
COMPAT["main"].__globals__["COMPAT_DIR"] = STATE.name
class ProducerAcquireGameEnvironmentTest(unittest.TestCase):
def test_prefixed_opt_in_enters_only_the_game_environment(self):
key = "DROIDDECK_GAME_FRAME_ACQUIRE"
scope = MODULE["GAME_PREFIX"] + key
self.assertEqual({}, MODULE["game_gpu"]({scope: "1"}, keep=True))
self.assertEqual({key: "1"}, MODULE["game_gpu"]({scope: "1"}))
self.assertEqual({}, MODULE["game_gpu"]({key: "1", scope: ""}))
self.assertEqual({}, MODULE["game_gpu"]({}))
class SupergiantDotnetReporterTest(unittest.TestCase):
def test_allows_the_builtin_mscoree_for_supergiant_reporter(self):
game = mock.Mock(files={"basecampbugreporter.native.dll"})
+28 -4
View File
@@ -38,6 +38,7 @@ static unsigned g_stat_zero_copy;
static int g_export_failed_logged;
static struct surface *g_announced;
static volatile int64_t g_last_zero_copy_ns;
static int explicit_proof;
static int export_ok, exports, presents, presented_acquire, logs, polls;
static int fake_ioctl(int fd, unsigned long req, void *arg) {
struct droiddeck_dma_buf_sync_file *f = arg;
@@ -57,6 +58,13 @@ static int fake_poll(struct pollfd *p, nfds_t n, int timeout) {
static int64_t now_ns(void) { return 1; }
static void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b) { return &b->slot; }
static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; }
static int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) {
assert(s && b);
if (explicit_proof != 1) return explicit_proof ? -2 : -1;
int fd = dup(0);
assert(fd >= 0);
return fd;
}
static const void *droiddeck_surface_color(struct surface *s) { (void)s; return NULL; }
static void droiddeck_surface_describe(struct surface *s, char *out, size_t n) { (void)s; snprintf(out, n, "game"); }
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; ++logs; }
@@ -79,7 +87,15 @@ static void run(int fd, int can_export, int copyable) {
b.slot = &ab;
export_ok = can_export;
int r = ahb_swapchain_present(&b, &s, 64, 64, draw);
if (fd >= 0 && can_export) {
if (explicit_proof) {
assert(exports == 0 && polls == 0);
if (explicit_proof == 1) {
assert(r == 0 && presents == 1 && presented_acquire >= 0 && ab.on_layer);
assert(fcntl(presented_acquire, F_GETFD) == -1 && errno == EBADF);
} else {
assert(r == -1 && presents == 0 && !ab.on_layer);
}
} else if (fd >= 0 && can_export) {
assert(r == 0 && presents == 1 && presented_acquire >= 0 && ab.on_layer && g_stat_zero_copy == 1 && polls == 0);
} else if (copyable) {
assert(r == -1 && presents == 0 && !ab.on_layer && g_stat_zero_copy == 0 && polls == (fd >= 0));
@@ -90,7 +106,8 @@ static void run(int fd, int can_export, int copyable) {
}
}
int main(int argc, char **argv) {
assert(argc == 4);
assert(argc == 5);
explicit_proof = atoi(argv[4]);
run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]));
return 0;
}
@@ -121,11 +138,18 @@ class ZeroCopyAcquireFenceTest(unittest.TestCase):
if built.returncode:
raise AssertionError(built.stdout + built.stderr)
def scenario(self, fd, can_export, copyable=1):
result = subprocess.run([str(self.binary), str(fd), str(can_export), str(copyable)], capture_output=True, text=True,
def scenario(self, fd, can_export, copyable=1, explicit_proof=0):
result = subprocess.run([str(self.binary), str(fd), str(can_export), str(copyable), str(explicit_proof)], capture_output=True, text=True,
timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_explicit_fence_goes_to_display_without_dmabuf_ioctl(self):
self.scenario(5, 0, explicit_proof=1)
def test_failed_explicit_dup_never_falls_through_to_legacy(self):
self.scenario(5, 1, explicit_proof=2)
self.scenario(5, 0, copyable=0, explicit_proof=2)
def test_exported_fence_goes_to_the_display(self):
self.scenario(5, 1)
+2
View File
@@ -26,6 +26,8 @@ struct dmabuf_buffer {
void *ahb_state;
};
enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE };
/* These release fixtures exercise legacy attachments, which own no acquire FD. */
#define dd_frame_acquire_clear(slot) ((void)0)
struct surface {
enum surface_role role;
struct surface *parent;