Compare commits

..
Author SHA1 Message Date
maxjivi05 544a28518e fix(display): limit the modifier-layout guard to layer buffers so client dma-buf imports keep main's path 2026-12-01 14:06:26 -05:00
maxjivi05 577824383d Merge remote-tracking branch 'droiddeck/main' into fix/adreno720-screen-corruption 2026-12-01 09:11:30 -05:00
MaxsTechReview bf772b7c55 ci(desktop): build KWin 6.8.3 to match the Arch Linux ARM package (#3526) 2026-12-01 09:09:51 -05:00
maxjivi05 2ce59fe0c2 Merge remote-tracking branch 'droiddeck/main' into fix/adreno720-screen-corruption 2026-12-01 08:43:49 -05:00
MaxsTechReview 29b04b66eb 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
2026-12-01 06:02:16 -05:00
MaxsTechReview 044c8ee475 fix(gamescope): a composited cursor no longer forwards the default arrow to the host (#3510) 2026-12-01 03:55:33 -05:00
MaxsTechReview ca499115ac fix(zero-copy): merge a second release fence into the pending fence wait (#3509)
When the kernel cannot attach a display release fence to the buffer, the
compositor waits on the fence itself. A second release of the same buffer
before that fence signalled overwrote the pending wait, so the first wait
removed the second one and then fired again with no source to remove,
crashing the compositor and losing the session.

A second unsignalled fence is now merged into the pending wait, and a
signalled or attached one leaves the pending wait in charge of the
deferred release.
2026-12-01 02:55:37 -05:00
The412BannerandThe412Banner d7898360e3 fix(input): keep the glibc-only __chk_fail out of the bionic build (#3492)
DroidDeck-Bionic preloads libfakeinput.so into its Wine processes
(tools/bionic-runtime/build.sh builds fakeinput_steam.cpp for bionic). The
fortified read/poll/ppoll entry points (#2916) call glibc's __chk_fail, which
bionic does not export, so the bionic build of the library cannot be loaded:
"CANNOT LINK EXECUTABLE .../wine: cannot locate symbol "__chk_fail"" and no
Wine program starts. Every DroidDeck-Bionic pack built from main since #2916 is
affected (r67 predates it).

The bounds failures now go through fakeinput_chk_fail(): abort() on bionic,
__chk_fail() as before on glibc. tools/tests/test_fakeinput_bionic.py fails if
__chk_fail is named outside the non-bionic branch again.

Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
2026-11-30 19:48:33 -05:00
LunaDL fcd197934a test: fix effects source cache harness initialization (#3490) 2026-11-30 18:15:04 -05:00
The412Banner ceb4c18531 fix(display): UBWC layer buffers fall back to linear on drivers without explicit modifier layouts 2026-11-26 17:15:24 +00:00
22 changed files with 787 additions and 79 deletions

No files matched your search

+10 -3
View File
@@ -4130,13 +4130,20 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
return read_input(fd, buf, count);
}
// glibc's fortify failure; bionic (DroidDeck-Bionic preloads this library into its Wine processes) has no
// __chk_fail, and a library naming it there cannot be loaded, which stops every Wine program from starting.
#if defined(__BIONIC__)
[[noreturn]] static void fakeinput_chk_fail(void) { abort(); }
#else
extern "C" [[noreturn]] void __chk_fail(void);
[[noreturn]] static void fakeinput_chk_fail(void) { __chk_fail(); }
#endif
/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll
* and ppoll, and glibc's versions go straight to the kernel. */
EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) {
static auto next_read_chk = reinterpret_cast<ssize_t (*)(int, void *, size_t, size_t)>(dlsym(RTLD_NEXT, "__read_chk"));
if (count > buflen) __chk_fail();
if (count > buflen) fakeinput_chk_fail();
if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen);
return read_input(fd, buf, count);
}
@@ -4390,13 +4397,13 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
}
EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
return poll(fds, nfds, timeout);
}
EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout,
const sigset_t *sigmask, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
return ppoll(fds, nfds, timeout, sigmask);
}
@@ -7,6 +7,7 @@
#include "droiddeck-ahb-v1-server-protocol.h"
#include <android/hardware_buffer.h>
#include <errno.h>
#include <linux/sync_file.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
@@ -145,6 +146,12 @@ static void handle_released(uint64_t id, int fd) {
if (poll(&p, 1, 0) > 0) {
close(fd);
} else {
if (ab->fence_src) {
struct sync_merge_data m = {.name = "droiddeck-release", .fd2 = fd};
if (ioctl(ab->fence_fd, SYNC_IOC_MERGE, &m) == 0) { close(fd); fd = m.fence; }
wl_event_source_remove(ab->fence_src);
close(ab->fence_fd);
}
ab->fence_fd = fd;
ab->fence_src = wl_event_loop_add_fd(g_loop, fd, WL_EVENT_READABLE, on_fence_readable, ab);
if (!ab->fence_src) { close(fd); ab->fence_fd = -1; }
@@ -152,6 +159,7 @@ static void handle_released(uint64_t id, int fd) {
}
}
}
if (ab->fence_src) return;
send_deferred_release(ab);
maybe_free(ab);
}
@@ -8,6 +8,10 @@ static inline int vkp_linear_dmabuf_through_buffer(int drm_modifiers, uint64_t m
return !drm_modifiers && modifier == 0 && !blit_dst;
}
static inline int vkp_dmabuf_layout_describable(int drm_modifiers, uint64_t modifier) {
return drm_modifiers || modifier == 0;
}
static inline int vkp_linear_dmabuf_foreign_image(int dmabuf, int staged) {
return dmabuf && !staged;
}
@@ -1834,6 +1834,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
uint32_t stride, uint32_t offset, int as_blit_dst) {
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
if (dev_init() != 0) return NULL;
if (as_blit_dst && !vkp_dmabuf_layout_describable(g_drm_modifiers, modifier)) {
LOGE("layer: the driver has no VK_EXT_image_drm_format_modifier to lay out the %s %dx%d dma-buf",
vkp_modifier_name(modifier), w, h);
return NULL;
}
const VkFormat format = drm_to_vk(drm_format);
const int padded_target = as_blit_dst &&
@@ -133,7 +133,6 @@ object NativeGuest {
* Rescanned when dpkg's state or a library directory changes.
*/
fun syncLibraryDirs(root: File) {
includeRunpathConf(root)
val conf = File(root, RUNPATH_CONF)
val signature = (listOf("var/lib/dpkg/status", "usr/lib", "usr/local/lib", "usr/lib/aarch64-linux-gnu")
.joinToString(",") { File(root, it).lastModified().toString() }) + "," + conf.parentFile.list()?.size
@@ -151,23 +150,6 @@ object NativeGuest {
stamp.writeText(signature)
}
private fun includeRunpathConf(root: File) {
val ldConf = File(root, "etc/ld.so.conf")
val text = if (ldConf.isFile) ldConf.readText() else ""
if (ldConfIncludes(text, "/$RUNPATH_CONF")) return
ldConf.parentFile?.mkdirs()
ldConf.writeText(text + (if (text.isEmpty() || text.endsWith("\n")) "" else "\n") + "include /$RUNPATH_CONF\n")
}
internal fun ldConfIncludes(text: String, file: String): Boolean {
val target = java.nio.file.Paths.get(file)
return text.lineSequence().map { it.substringBefore('#').trim() }
.filter { it.length > 8 && it.startsWith("include") && it[7].isWhitespace() }
.flatMap { it.substring(8).trim().split(Regex("\\s+")).asSequence() }
.map { if (it.startsWith("/")) it else "/etc/$it" }
.any { pattern -> runCatching { java.nio.file.FileSystems.getDefault().getPathMatcher("glob:$pattern").matches(target) }.getOrDefault(false) }
}
/** What a rootfs needs before anything runs in it natively; cheap once done. */
@Synchronized
fun prepare(context: Context, root: File) {
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.runtime
import java.io.File
import java.nio.file.Files
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -136,38 +135,4 @@ class NativeGuestTest {
assertEquals("/mnt/droiddeck-sd/steamapps/compatdata/2",
NativeGuest.guestLinkTarget("/data/user/0/app/files/steam-libraries/x/steamapps/compatdata/2", linkRoot, binds))
}
@Test
fun aRuntimeWhoseLdSoConfListsOnlyItsDirectoriesIncludesTheRunpathDirectories() {
val root = rootWithLoader()
File(root, "etc").mkdirs()
File(root, "etc/ld.so.conf").writeText("/usr/local/lib\n/usr/lib\n/usr/lib32")
NativeGuest.syncLibraryDirs(root)
assertEquals("/usr/local/lib\n/usr/lib\n/usr/lib32\ninclude /etc/ld.so.conf.d/zz-droiddeck-native.conf\n",
File(root, "etc/ld.so.conf").readText())
NativeGuest.syncLibraryDirs(root)
assertEquals(1, File(root, "etc/ld.so.conf").readLines().count { it.startsWith("include") })
}
@Test
fun aRuntimeThatAlreadyIncludesLdSoConfDKeepsItsLdSoConf() {
val root = rootWithLoader()
File(root, "etc").mkdirs()
val ubuntu = "include /etc/ld.so.conf.d/*.conf\n\n"
File(root, "etc/ld.so.conf").writeText(ubuntu)
NativeGuest.syncLibraryDirs(root)
assertEquals(ubuntu, File(root, "etc/ld.so.conf").readText())
}
@Test
fun anIncludeReachesTheRunpathConfThroughAbsoluteAndRelativePatterns() {
val conf = "/etc/ld.so.conf.d/zz-droiddeck-native.conf"
assertTrue(NativeGuest.ldConfIncludes("include /etc/ld.so.conf.d/*.conf", conf))
assertTrue(NativeGuest.ldConfIncludes("include ld.so.conf.d/*.conf", conf))
assertTrue(NativeGuest.ldConfIncludes("/usr/lib\ninclude\t/etc/other.conf /etc/ld.so.conf.d/zz-*.conf", conf))
assertFalse(NativeGuest.ldConfIncludes("/usr/local/lib\n/usr/lib\n", conf))
assertFalse(NativeGuest.ldConfIncludes("# include /etc/ld.so.conf.d/*.conf", conf))
assertFalse(NativeGuest.ldConfIncludes("include /etc/ld.so.conf.d/*.cfg", conf))
assertFalse(NativeGuest.ldConfIncludes("include /usr/lib/ld.so.conf.d/*.conf", conf))
}
}
+1 -1
View File
@@ -71,7 +71,7 @@ both build jobs verify the Arch Linux ARM signature and pinned SHA-256 as for ev
The desktop workflow replaces the same-version `kwin_wayland` executable and `libkwin.so`; the rest
comes from the signature-checked Arch packages. `desktop-kde.kwin.txt` records the source, patch,
executable, library and build package hashes. Corresponding source is
https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz plus the patch in this repository.
https://download.kde.org/stable/plasma/6.8.3/kwin-6.8.3.tar.xz plus the patch in this repository.
The inventories use `.gzip` rather than `.gz`: Android's asset packer expands `.gz` and strips
its suffix. The shared local/CI runtime payload check verifies the exact APK names and bytes.
+1 -1
View File
@@ -6,7 +6,7 @@ here=$(cd "$(dirname "$0")" && pwd)
source "$here/kwin.env"
source "$here/mesa.env"
version=$DESKTOP_KWIN_VERSION
source_sha=ea5e68d957c7d70abed97222a592d4445fda29129e20942658badd224ee138b4
source_sha=fd5cb783f220ea4526a9afee2f72b582c3e87ef7f91b19bc5c7a6662ffe7fbdc
mirror=https://fl.us.mirror.archlinuxarm.org/aarch64
builder=68B3537F39A313B3E574D06777193F152BDBE6A6
work=$(mktemp -d)
+1 -1
View File
@@ -1 +1 @@
DESKTOP_KWIN_VERSION=6.8.2
DESKTOP_KWIN_VERSION=6.8.3
@@ -8,8 +8,8 @@ Third-party files in DroidDeck's KDE desktop package (tools/desktop-kde/overlay)
- steam.svg: Papirus icon theme (https://github.com/PapirusDevelopmentTeam/papirus-icon-theme),
GPL-3.0.
- kwin_wayland: KWin 6.8.2, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
Corresponding source: https://download.kde.org/stable/plasma/6.8.2/kwin-6.8.2.tar.xz and
- kwin_wayland: KWin 6.8.3, GPL-2.0-or-later. Built with DroidDeck's nested desktop scale patch.
Corresponding source: https://download.kde.org/stable/plasma/6.8.3/kwin-6.8.3.tar.xz and
https://github.com/Droid-Deck/DroidDeck/tree/fix/kde-desktop-followups/tools/desktop-kde/patches
(the source and patch hashes are recorded in desktop-kde.kwin.txt beside the package).
+15 -3
View File
@@ -21,9 +21,10 @@ library list, before anything is published.
trip to Xwayland on the paint thread; with no image, wlserver's position is used as upstream does.
- `0101-nested-wayland-cursor-routing.patch` - this app: `gamescope_cursor_composite=2` lets the
nested Wayland session paint its cursor in the output using the real X pointer position; client
cursor surfaces are cleared to prevent a duplicate at the host pointer, while Gamescope's original
default host-cursor fallback is preserved when its no-keyboard-focus policy selects it. Empty
client cursor images and Gamescope's hidden flag still suppress the painted cursor.
cursor surfaces are cleared to prevent a duplicate at the host pointer, and so is Gamescope's
default host-cursor fallback, which would otherwise show a second arrow until Gamescope gets
keyboard focus. Empty client cursor images and Gamescope's hidden flag still suppress the
painted cursor.
- `0110-wayland-backend-touch.patch` - this app: the nested Wayland backend bound only the host's
pointer and keyboard, so a finger on the phone's screen never reached Steam. It now binds
`wl_touch` too and hands each finger to wlserver's touch path (`wlserver_touchdown` / `motion` /
@@ -484,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.
@@ -74,7 +74,7 @@ index 0000000..d7c21da
+
+ constexpr bool CursorShouldBeForwardedToHost( int cursorCompositeMode, bool useHostCursorFallback )
+ {
+ return cursorCompositeMode != 2 || useHostCursorFallback;
+ return cursorCompositeMode != 2;
+ }
+
+ constexpr bool CursorImageShouldBePainted( bool imageEmpty, bool cursorHidden )
@@ -176,10 +176,10 @@ index 0000000..9c622db
+ REQUIRE( CursorShouldBeComposited( 2, false, false, true, false ) );
+}
+
+TEST_CASE("manual composition retains only the no-focus default cursor fallback", "[cursor_routing]")
+TEST_CASE("manual composition never forwards a cursor to the host", "[cursor_routing]")
+{
+ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, false ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 2, true ) );
+ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, true ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 1, false ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 0, false ) );
+}
@@ -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 <fcntl.h>
+#include <mutex>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <csignal>
#include <sys/mman.h>
#include <poll.h>
#include <linux/input-event-codes.h>
#include <xkbcommon/xkbcommon.h>
#include <libdecor.h>
#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<bool> 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<const uint64_t> 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<CReleaseTimelinePoint> 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<CReleaseTimelinePoint> pReleasePoint ) override;
virtual IBackendFb *EnsureImported() override { return this; };
+ bool ShowsClientBuffer() const { return m_bShowsClientBuffer; }
+
private:
wlr_buffer *m_pClientBuffer = nullptr;
+ std::atomic<bool> m_bShowsClientBuffer = { false };
std::shared_ptr<CReleaseTimelinePoint> m_pReleasePoint;
};
class IBackend
{
public:
virtual ~IBackend() {}
virtual bool Init() = 0;
virtual bool PostInit() = 0;
virtual std::span<const char *const> GetInstanceExtensions() const = 0;
virtual std::span<const char *const> GetDeviceExtensions( VkPhysicalDevice pVkPhysicalDevice ) const = 0;
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-f3a45b31
GAMESCOPE_SHA256=3908af87b2ee8a328e9780fc805c6a7bddd11d7405b9992d717b94e16c019313
GAMESCOPE_TAG=gamescope-3.16.29-cb9c4861
GAMESCOPE_SHA256=89a3d70124a13bb5de0b4c67ff75d748a5d7ba6f29590194621754e3550b1f31
@@ -84,6 +84,9 @@ static void check_generated_settings_and_layout(void) {
g_vk.CmdBindPipeline = bind_pipeline; g_vk.CmdBindDescriptorSets = bind_sets;
g_vk.CmdPushConstants = push; g_vk.CmdDraw = draw; g_vk.CmdEndRenderPass = end_pass;
g_vk.CmdBlitImage = blit;
g_rp = (VkRenderPass)(uintptr_t)5;
g_pipe[P_SGSR] = (VkPipeline)(uintptr_t)6;
g_pipe[P_COLOR] = (VkPipeline)(uintptr_t)7;
g_ready = 1;
for (int k = 0; k < 2; k++) {
struct fx_target *t = &g_contexts[1].targets[k];
+1 -1
View File
@@ -32,7 +32,7 @@ class LazyEffectPipelineSourceTest(unittest.TestCase):
self.assertIn("effect pipelines are created when needed", body)
def test_pipelines_are_prepared_before_effect_chain_resources_and_draws(self):
body = function_body(self.source, "VkImage vkp_effects_run(")
body = function_body(self.source, "static VkImage effects_run(")
prepare = body.index("pipelines_ensure(spatial, s)")
scene = body.index("scene_ensure(scene, scene_w, scene_h)")
self.assertLess(prepare, scene)
+30
View File
@@ -0,0 +1,30 @@
from pathlib import Path
import re
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
def code_only(text):
"""The source without its comments and string literals."""
text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S)
text = re.sub(r"//[^\n]*", " ", text)
return re.sub(r'"(?:\\.|[^"\\\n])*"', '""', text)
class FakeinputBionicTest(unittest.TestCase):
# DroidDeck-Bionic preloads this library into its Wine processes (tools/bionic-runtime/build.sh). bionic
# exports no __chk_fail: a library that names it there cannot be loaded, so no Wine program starts
# ("cannot locate symbol "__chk_fail"").
def test_glibcs_fortify_failure_is_named_only_off_bionic(self):
code = code_only(SOURCE.read_text())
guarded = re.compile(r"#if defined\(__BIONIC__\)\n(?P<bionic>.*?)#else\n(?P<glibc>.*?)#endif\n", re.S)
blocks = [m for m in guarded.finditer(code) if "__chk_fail" in m.group("glibc")]
self.assertTrue(blocks, "the glibc-only __chk_fail is behind #if defined(__BIONIC__) ... #else")
for block in blocks:
self.assertNotIn("__chk_fail", block.group("bionic"))
self.assertNotIn("__chk_fail", guarded.sub("", code))
if __name__ == "__main__":
unittest.main()
@@ -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 <atomic>
#include <cassert>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <fcntl.h>
#include <mutex>
#include <poll.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <vector>
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 <typename T = int>
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<IWaitable *> 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()
+31 -3
View File
@@ -109,9 +109,11 @@ static struct droiddeck_native_handle handle = {.numFds = 1, .data = {3}};
static AHardwareBuffer *buffer = (AHardwareBuffer *)&handle;
static struct vkp_image image;
static int allocations, imports_10_bit, imports_8_bit, accept_10_bit, accept_8_bit;
static int qti_handle, refuse_compressed, compressed_imports;
static uint64_t allocated_usage;
static int AHardwareBuffer_allocate(const AHardwareBuffer_Desc *d, AHardwareBuffer **out) {
(void)d; allocations++; *out = buffer; return 0;
allocations++; allocated_usage = d->usage; *out = buffer; return 0;
}
static void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_Desc *d) {
(void)b; d->stride = 1920; d->usage = 0;
@@ -119,14 +121,20 @@ static void AHardwareBuffer_describe(const AHardwareBuffer *b, AHardwareBuffer_D
static void AHardwareBuffer_release(AHardwareBuffer *b) { (void)b; }
static const void *native_handle(const AHardwareBuffer *b) { (void)b; return &handle; }
static struct { const void *(*getNativeHandle)(const AHardwareBuffer *); } api = {native_handle};
static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) { (void)h; (void)mod; return 0; }
static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) {
(void)h;
if (!qti_handle) return 0;
*mod = (allocated_usage & SC_LAYER_AHB_USAGE_VENDOR_UBWC) ? MOD_QCOM_COMPRESSED : MOD_LINEAR;
return 1;
}
static int vkp_can_import_ahb(void) { return 0; }
static struct vkp_image *vkp_image_import_ahb(AHardwareBuffer *b, char *info, size_t n) {
(void)b; (void)info; (void)n; return NULL;
}
static struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm, uint64_t mod, int w, int h, uint32_t pitch,
uint32_t offset, int planes) {
(void)fd; (void)mod; (void)w; (void)h; (void)pitch; (void)offset; (void)planes;
(void)fd; (void)w; (void)h; (void)pitch; (void)offset; (void)planes;
if (mod != MOD_LINEAR) { compressed_imports++; return refuse_compressed ? NULL : &image; }
if (drm == DRM_ABGR2101010) { imports_10_bit++; return accept_10_bit ? &image : NULL; }
imports_8_bit++;
return accept_8_bit ? &image : NULL;
@@ -187,6 +195,26 @@ int main(void) {
assert(frame(&nothing_imports) == -1 && g_alloc_failed);
assert(allocations == tried);
assert(imports_10_bit == 1 && imports_8_bit == 1);
int fd;
struct layer ubwc_without_modifiers = {.name = "game", .pool_n = 3};
reset(0, 1);
qti_handle = 1; refuse_compressed = 1; compressed_imports = 0;
assert(take_free_slot(&ubwc_without_modifiers, 1558, 720, AHB_RGBA8, &fd) == 0);
assert(compressed_imports == 1 && imports_8_bit == 1);
assert(ubwc_without_modifiers.alloc_tier == TIER_PLAIN);
assert(ubwc_without_modifiers.pool_modifier == MOD_LINEAR);
assert(!(allocated_usage & SC_LAYER_AHB_USAGE_VENDOR_UBWC));
assert(take_free_slot(&ubwc_without_modifiers, 1558, 720, AHB_RGBA8, &fd) == 0);
assert(compressed_imports == 1 && imports_8_bit == 2);
struct layer ubwc_with_modifiers = {.name = "game", .pool_n = 3};
reset(0, 1);
refuse_compressed = 0; compressed_imports = 0;
assert(take_free_slot(&ubwc_with_modifiers, 1558, 720, AHB_RGBA8, &fd) == 0);
assert(compressed_imports == 1 && imports_8_bit == 0);
assert(ubwc_with_modifiers.alloc_tier == TIER_UBWC);
assert(ubwc_with_modifiers.pool_modifier == MOD_QCOM_COMPRESSED);
return 0;
}
'''
+13
View File
@@ -124,6 +124,19 @@ class VkLinearDmabufTest(unittest.TestCase):
self.assertIn("!as_blit_dst", terms)
self.assertIn("g_vk.GetPhysicalDeviceImageFormatProperties2", terms)
def test_client_imports_are_not_refused_by_the_layer_guard(self):
body = function((SRC / "vk_present.c").read_text(), "vkp_image_import_dmabuf")
self.assertEqual(body.count("vkp_dmabuf_layout_describable("), 1)
self.assertIn("as_blit_dst && !vkp_dmabuf_layout_describable(", body)
def test_undescribable_layout_is_refused_before_any_image_is_made(self):
body = function((SRC / "vk_present.c").read_text(), "vkp_image_import_dmabuf")
guard = body.index("if (as_blit_dst && !vkp_dmabuf_layout_describable(g_drm_modifiers, modifier))")
self.assertLess(body.index("dev_init()"), guard)
self.assertIn("return NULL;", body[guard:body.index("drm_to_vk(drm_format)")])
self.assertLess(guard, body.index("calloc(1, sizeof(*img))"))
self.assertLess(guard, body.index("VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT"))
def test_staged_client_image_stays_layer_candidate(self):
vk = (SRC / "vk_present.c").read_text()
comp = (SRC / "compositor.c").read_text()
+71 -6
View File
@@ -35,13 +35,21 @@ STRUCT
static struct wl_list g_bufs;
static struct wl_event_loop *g_loop;
static int g_import_failed_logged;
static int import_ok, imports, imported_flags, deferred_releases, frees, sources;
static struct wl_event_source g_source;
static int import_ok, imports, imported_flags, deferred_releases, frees, sources, removes, merge_ok, merges;
static struct wl_event_source g_sources[4];
static struct wl_event_source *g_removed;
void wl_list_init(struct wl_list *l) { l->prev = l; l->next = l; }
void wl_list_insert(struct wl_list *l, struct wl_list *e) {
e->next = l->next; e->prev = l; l->next->prev = e; l->next = e;
}
static int fake_ioctl(int fd, unsigned long req, void *arg) {
if (req == SYNC_IOC_MERGE) {
struct sync_merge_data *m = arg;
assert(fd >= 0 && m->fd2 >= 0 && fd != m->fd2);
++merges;
if (!merge_ok) { errno = ENOTTY; return -1; }
m->fence = dup(m->fd2); return 0;
}
struct droiddeck_dma_buf_sync_file *f = arg;
(void)fd;
assert(req == DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE);
@@ -54,13 +62,17 @@ static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; }
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
static struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, uint32_t m,
int (*cb)(int, uint32_t, void *), void *d) {
(void)l; (void)fd; (void)m; (void)cb; (void)d; ++sources; return &g_source;
(void)l; (void)fd; (void)m; (void)cb; (void)d; return &g_sources[sources++];
}
static void wl_event_source_remove(struct wl_event_source *s) { assert(s); ++removes; g_removed = s; }
static int on_fence_readable(int fd, uint32_t mask, void *data) { (void)fd; (void)mask; (void)data; return 0; }
static void send_deferred_release(struct ahb_buf *ab) { ++deferred_releases; ab->release_pending = 0; }
static void maybe_free(struct ahb_buf *ab) { (void)ab; ++frees; }
FUNCTIONS
static void reset(void) { import_ok = imports = imported_flags = deferred_releases = frees = sources = 0; }
static void reset(void) {
import_ok = imports = imported_flags = deferred_releases = frees = sources = removes = merge_ok = merges = 0;
g_removed = NULL;
}
static void run(int display, int can_import, int fence_signalled) {
reset();
wl_list_init(&g_bufs);
@@ -78,12 +90,48 @@ static void run(int display, int can_import, int fence_signalled) {
assert(deferred_releases == 1 && frees == 1 && !ab.fence_src && ab.fence_fd == -1);
errno = 0; assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
} else {
assert(deferred_releases == 0 && sources == 1 && ab.fence_src == &g_source && ab.fence_fd == fds[0]);
assert(deferred_releases == 0 && sources == 1 && ab.fence_src == &g_sources[0] && ab.fence_fd == fds[0]);
close(fds[0]);
}
close(fds[1]);
}
static int closed(int fd) { errno = 0; return fcntl(fd, F_GETFD) == -1 && errno == EBADF; }
static void rerelease(int can_merge, int second_import, int second_signalled) {
reset();
wl_list_init(&g_bufs);
struct dmabuf_buffer b = {.fd = 7};
struct ahb_buf ab;
memset(&ab, 0, sizeof(ab));
ab.id = 42; ab.b = &b; ab.on_layer = 1; ab.release_pending = 1; ab.fence_fd = -1;
wl_list_insert(&g_bufs, &ab.link);
int first[2], second[2];
assert(pipe(first) == 0 && pipe(second) == 0);
handle_released(42, first[0]);
assert(ab.fence_src == &g_sources[0] && ab.fence_fd == first[0] && deferred_releases == 0);
ab.on_layer = 1;
if (second_signalled) assert(write(second[1], "x", 1) == 1);
import_ok = second_import; merge_ok = can_merge;
handle_released(42, second[0]);
assert(!ab.on_layer && deferred_releases == 0 && frees == 0);
if (second_import || second_signalled) {
assert(removes == 0 && merges == 0 && sources == 1 && ab.fence_src == &g_sources[0] && ab.fence_fd == first[0]);
assert(closed(second[0]));
close(first[0]);
} else {
assert(merges == 1 && removes == 1 && g_removed == &g_sources[0]);
assert(sources == 2 && ab.fence_src == &g_sources[1] && ab.fence_fd >= 0);
assert(closed(first[0]));
if (can_merge) assert(closed(second[0]) && ab.fence_fd != second[0]);
else assert(ab.fence_fd == second[0]);
close(ab.fence_fd);
}
close(first[1]); close(second[1]);
}
int main(int argc, char **argv) {
if (argc == 5 && !strcmp(argv[1], "rerelease")) {
rerelease(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]));
return 0;
}
assert(argc == 4);
run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]));
return 0;
@@ -103,7 +151,7 @@ class ZeroCopyReleaseAtLatchTest(unittest.TestCase):
ahb, re.M))
struct = re.search(r'struct ahb_buf \{.*?\n\};', ahb, re.S).group()
functions = '\n'.join(function(ahb, n) for n in ('find_buf', 'handle_released'))
source = HARNESS.replace('DEFINES', '#include <fcntl.h>\n#include <sys/ioctl.h>\n' + defines)
source = HARNESS.replace('DEFINES', '#include <fcntl.h>\n#include <linux/sync_file.h>\n#include <sys/ioctl.h>\n' + defines)
source = source.replace('STRUCT', struct).replace('FUNCTIONS', functions)
cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-release-latch-')
cls.addClassCleanup(cls.tmp.cleanup)
@@ -136,6 +184,23 @@ class ZeroCopyReleaseAtLatchTest(unittest.TestCase):
def test_signalled_fence_releases_without_waiting(self):
self.scenario(1, 0, 1)
def rerelease(self, can_merge, second_import, second_signalled):
result = subprocess.run([str(self.binary), 'rerelease', str(can_merge), str(second_import), str(second_signalled)],
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_second_unsignalled_fence_merges_into_the_pending_wait(self):
self.rerelease(1, 0, 0)
def test_second_unsignalled_fence_replaces_the_wait_when_merge_fails(self):
self.rerelease(0, 0, 0)
def test_second_imported_fence_keeps_the_pending_wait(self):
self.rerelease(1, 1, 0)
def test_second_signalled_fence_keeps_the_pending_wait(self):
self.rerelease(1, 0, 1)
if __name__ == '__main__':
unittest.main()
+13
View File
@@ -56,6 +56,18 @@ static void check_path_choice(void) {
assert(!vkp_linear_dmabuf_through_buffer(1, linear, 1));
}
static void check_describable_layouts(void) {
const uint64_t linear = 0;
const uint64_t qcom_compressed = 0x0500000000000001ULL;
const uint64_t arm_afbc = 0x0800000000000001ULL;
assert(vkp_dmabuf_layout_describable(0, linear));
assert(vkp_dmabuf_layout_describable(1, linear));
assert(vkp_dmabuf_layout_describable(1, qcom_compressed));
assert(vkp_dmabuf_layout_describable(1, arm_afbc));
assert(!vkp_dmabuf_layout_describable(0, qcom_compressed));
assert(!vkp_dmabuf_layout_describable(0, arm_afbc));
}
static void check_foreign_image(void) {
assert(vkp_linear_dmabuf_foreign_image(1, 0));
assert(!vkp_linear_dmabuf_foreign_image(1, 1));
@@ -117,6 +129,7 @@ int main(void) {
check_rejected_layouts();
check_path_choice();
check_padded_layer_targets();
check_describable_layouts();
check_foreign_image();
check_readback_order();
check_ownership();