mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Gate direct Steam frames on verified producer acquire fences
This commit is contained in:
1 parent
18d735b4c4
commit
b164212c8f
35 files changed
+2245
-35
No files matched your search
@@ -42,6 +42,11 @@ add_library(droiddeckwayland SHARED
|
||||
src/hudframes.c
|
||||
src/hudframes_jni.c
|
||||
)
|
||||
option(DROIDDECK_FRAME_ACQUIRE_PROBE "Build opt-in signaled producer acquire protocol support" ON)
|
||||
if (DROIDDECK_FRAME_ACQUIRE_PROBE)
|
||||
target_sources(droiddeckwayland PRIVATE generated/droiddeck-frame-acquire-v1-protocol.c)
|
||||
target_compile_definitions(droiddeckwayland PRIVATE DROIDDECK_FRAME_ACQUIRE_PROBE=1)
|
||||
endif()
|
||||
target_compile_options(droiddeckwayland PRIVATE
|
||||
$<$<COMPILE_LANGUAGE:C>:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
|
||||
target_include_directories(droiddeckwayland PRIVATE
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/* Generated by wayland-scanner 1.22.0 */
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include "wayland-util.h"
|
||||
|
||||
#ifndef __has_attribute
|
||||
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
|
||||
#endif
|
||||
|
||||
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
|
||||
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
|
||||
#else
|
||||
#define WL_PRIVATE
|
||||
#endif
|
||||
|
||||
extern const struct wl_interface wl_buffer_interface;
|
||||
extern const struct wl_interface wl_surface_interface;
|
||||
|
||||
static const struct wl_interface *droiddeck_frame_acquire_v1_types[] = {
|
||||
&wl_surface_interface,
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message droiddeck_frame_acquire_v1_requests[] = {
|
||||
{ "destroy", "", droiddeck_frame_acquire_v1_types + 0 },
|
||||
{ "set_acquire_fence", "ooh", droiddeck_frame_acquire_v1_types + 0 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface droiddeck_frame_acquire_v1_interface = {
|
||||
"droiddeck_frame_acquire_v1", 1,
|
||||
2, droiddeck_frame_acquire_v1_requests,
|
||||
0, NULL,
|
||||
};
|
||||
@@ -0,0 +1,128 @@
|
||||
/* Generated by wayland-scanner 1.22.0 */
|
||||
|
||||
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H
|
||||
#define DROIDDECK_FRAME_ACQUIRE_V1_SERVER_PROTOCOL_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "wayland-server.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
struct wl_client;
|
||||
struct wl_resource;
|
||||
|
||||
/**
|
||||
* @page page_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 protocol
|
||||
* @section page_ifaces_droiddeck_frame_acquire_v1 Interfaces
|
||||
* - @subpage page_iface_droiddeck_frame_acquire_v1 - DroidDeck producer write completion for a single Wayland attachment
|
||||
*/
|
||||
struct droiddeck_frame_acquire_v1;
|
||||
struct wl_buffer;
|
||||
struct wl_surface;
|
||||
|
||||
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE
|
||||
#define DROIDDECK_FRAME_ACQUIRE_V1_INTERFACE
|
||||
/**
|
||||
* @page page_iface_droiddeck_frame_acquire_v1 droiddeck_frame_acquire_v1
|
||||
* @section page_iface_droiddeck_frame_acquire_v1_desc Description
|
||||
*
|
||||
* 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.
|
||||
* @section page_iface_droiddeck_frame_acquire_v1_api API
|
||||
* See @ref iface_droiddeck_frame_acquire_v1.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_droiddeck_frame_acquire_v1 The droiddeck_frame_acquire_v1 interface
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
extern const struct wl_interface droiddeck_frame_acquire_v1_interface;
|
||||
#endif
|
||||
|
||||
#ifndef DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM
|
||||
#define DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM
|
||||
enum droiddeck_frame_acquire_v1_error {
|
||||
/**
|
||||
* not the same client's pending DMA-BUF attachment
|
||||
*/
|
||||
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT = 0,
|
||||
/**
|
||||
* that attachment already has an acquire fence
|
||||
*/
|
||||
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE = 1,
|
||||
/**
|
||||
* not a real successfully signaled Linux sync_file
|
||||
*/
|
||||
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE = 2,
|
||||
/**
|
||||
* not the paired test peer
|
||||
*/
|
||||
DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER = 3,
|
||||
};
|
||||
#endif /* DROIDDECK_FRAME_ACQUIRE_V1_ERROR_ENUM */
|
||||
|
||||
/**
|
||||
* @ingroup iface_droiddeck_frame_acquire_v1
|
||||
* @struct droiddeck_frame_acquire_v1_interface
|
||||
*/
|
||||
struct droiddeck_frame_acquire_v1_interface {
|
||||
/**
|
||||
*/
|
||||
void (*destroy)(struct wl_client *client,
|
||||
struct wl_resource *resource);
|
||||
/**
|
||||
* 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.
|
||||
* @param fence producer's native acquire sync_file
|
||||
*/
|
||||
void (*set_acquire_fence)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
struct wl_resource *surface,
|
||||
struct wl_resource *buffer,
|
||||
int32_t fence);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_droiddeck_frame_acquire_v1
|
||||
*/
|
||||
#define DROIDDECK_FRAME_ACQUIRE_V1_DESTROY_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_droiddeck_frame_acquire_v1
|
||||
*/
|
||||
#define DROIDDECK_FRAME_ACQUIRE_V1_SET_ACQUIRE_FENCE_SINCE_VERSION 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,45 @@
|
||||
<?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 and
|
||||
only to the test fixture's app-authorized Gamescope worker.
|
||||
</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"/>
|
||||
<entry name="unauthorized_peer" value="3" summary="not the paired test peer"/>
|
||||
</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>
|
||||
@@ -54,6 +54,7 @@ static struct wl_list g_clients;
|
||||
static uint64_t g_next_id = 1;
|
||||
static struct wl_event_loop *g_loop;
|
||||
static unsigned g_stat_zero_copy;
|
||||
static unsigned g_stat_producer_fence;
|
||||
static int g_export_failed_logged, g_import_failed_logged;
|
||||
static int g_advertised;
|
||||
static int g_mode_sent = -1;
|
||||
@@ -201,31 +202,47 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
|
||||
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL;
|
||||
if (!ab) return -1;
|
||||
int dmabuf_fd = droiddeck_dmabuf_fd(b);
|
||||
int acquire = -1;
|
||||
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
|
||||
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
|
||||
acquire = exp.fd;
|
||||
} else {
|
||||
if (!g_export_failed_logged) {
|
||||
g_export_failed_logged = 1;
|
||||
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
|
||||
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
|
||||
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
|
||||
int acquire = droiddeck_surface_dup_acquire(s, b);
|
||||
if (acquire == -2) return -1;
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
const int explicit_acquire = acquire >= 0;
|
||||
#endif
|
||||
if (acquire < 0) {
|
||||
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
|
||||
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
|
||||
acquire = exp.fd;
|
||||
} else {
|
||||
if (!g_export_failed_logged) {
|
||||
g_export_failed_logged = 1;
|
||||
droiddeck_log("layer", "zero-copy: no acquire fence from the game's dma-buf (%s): %s",
|
||||
dmabuf_fd >= 0 ? strerror(errno) : "no dma-buf fd",
|
||||
draw ? "its frames are copied instead" : "it cannot be copied, so each frame is waited for on the CPU");
|
||||
}
|
||||
if (dmabuf_fd >= 0) {
|
||||
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
|
||||
int r;
|
||||
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
|
||||
}
|
||||
if (draw) return -1;
|
||||
}
|
||||
if (dmabuf_fd >= 0) {
|
||||
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN};
|
||||
int r;
|
||||
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
|
||||
}
|
||||
if (draw) return -1;
|
||||
}
|
||||
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h, draw,
|
||||
s ? droiddeck_surface_color(s) : NULL, ab->format);
|
||||
if (r < 0) return -1;
|
||||
if (r == 1) return 0;
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
static int explicit_logged;
|
||||
if (explicit_acquire && !explicit_logged) {
|
||||
explicit_logged = 1;
|
||||
droiddeck_log("layer", "probe: SurfaceControl accepted a verified producer acquire fence");
|
||||
}
|
||||
#endif
|
||||
if (!ab->on_layer) {
|
||||
ab->on_layer = 1;
|
||||
g_stat_zero_copy++;
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
if (explicit_acquire) g_stat_producer_fence++;
|
||||
#endif
|
||||
g_last_zero_copy_ns = now_ns();
|
||||
}
|
||||
if (s && g_announced != s) {
|
||||
@@ -265,6 +282,12 @@ unsigned ahb_swapchain_stats_take(void) {
|
||||
return n;
|
||||
}
|
||||
|
||||
unsigned ahb_swapchain_producer_fence_stats_take(void) {
|
||||
unsigned n = g_stat_producer_fence;
|
||||
g_stat_producer_fence = 0;
|
||||
return n;
|
||||
}
|
||||
|
||||
int ahb_swapchain_advertised(void) { return g_advertised; }
|
||||
|
||||
uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) {
|
||||
|
||||
@@ -20,7 +20,9 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
|
||||
int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced);
|
||||
void ahb_swapchain_surface_gone(struct surface *s);
|
||||
unsigned ahb_swapchain_stats_take(void);
|
||||
unsigned ahb_swapchain_producer_fence_stats_take(void);
|
||||
int ahb_swapchain_advertised(void);
|
||||
int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b);
|
||||
uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b);
|
||||
|
||||
void ahb_swapchain_layer_released(void *token, int release_fd);
|
||||
|
||||
@@ -24,6 +24,14 @@
|
||||
#include "linux-dmabuf-v1-server-protocol.h"
|
||||
#include "sc_layer.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "frame_acquire.h"
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
#include "droiddeck-frame-acquire-v1-server-protocol.h"
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/sysmacros.h>
|
||||
#include <sys/stat.h>
|
||||
#include "frame_worker_peer.h"
|
||||
#endif
|
||||
#include "display_buffers.h"
|
||||
#include "viewporter-server-protocol.h"
|
||||
#include "droiddeck-desktop-v1-server-protocol.h"
|
||||
@@ -211,6 +219,7 @@ struct surface {
|
||||
struct wl_list link;
|
||||
|
||||
struct wl_resource *pending_buffer;
|
||||
struct dd_frame_acquire pending_frame_acquire, frame_acquire;
|
||||
struct wl_listener pending_buffer_destroy;
|
||||
int pending_attach;
|
||||
int pending_src_set, pending_dst_set;
|
||||
@@ -827,6 +836,7 @@ static void unmap_toplevel(struct surface *s) {
|
||||
}
|
||||
|
||||
static void drop_dmabuf(struct surface *s, int paced) {
|
||||
dd_frame_acquire_clear(&s->frame_acquire);
|
||||
if (s->dmabuf) {
|
||||
wl_list_remove(&s->dmabuf_destroy.link);
|
||||
if (buffer_shown_elsewhere(s->dmabuf, s)) {
|
||||
@@ -842,18 +852,21 @@ static void drop_dmabuf(struct surface *s, int paced) {
|
||||
|
||||
static void on_dmabuf_destroyed(struct wl_listener *l, void *data) {
|
||||
struct surface *s = wl_container_of(l, s, dmabuf_destroy);
|
||||
dd_frame_acquire_clear(&s->frame_acquire);
|
||||
wl_list_remove(&s->dmabuf_destroy.link);
|
||||
s->dmabuf = NULL;
|
||||
}
|
||||
|
||||
static void on_pending_buffer_destroyed(struct wl_listener *l, void *data) {
|
||||
struct surface *s = wl_container_of(l, s, pending_buffer_destroy);
|
||||
dd_frame_acquire_clear(&s->pending_frame_acquire);
|
||||
wl_list_remove(&s->pending_buffer_destroy.link);
|
||||
wl_list_init(&s->pending_buffer_destroy.link);
|
||||
s->pending_buffer = NULL;
|
||||
}
|
||||
|
||||
struct surface_state {
|
||||
struct dd_frame_acquire frame_acquire;
|
||||
struct wl_resource *buffer;
|
||||
struct wl_listener buffer_destroy;
|
||||
int attach;
|
||||
@@ -866,6 +879,7 @@ struct surface_state {
|
||||
|
||||
static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
|
||||
struct surface_state *st = wl_container_of(l, st, buffer_destroy);
|
||||
dd_frame_acquire_clear(&st->frame_acquire);
|
||||
wl_list_remove(&st->buffer_destroy.link);
|
||||
wl_list_init(&st->buffer_destroy.link);
|
||||
st->buffer = NULL;
|
||||
@@ -874,6 +888,8 @@ static void on_state_buffer_destroyed(struct wl_listener *l, void *data) {
|
||||
|
||||
static void surface_state_take(struct surface *s, struct surface_state *st) {
|
||||
st->attach = s->pending_attach;
|
||||
st->frame_acquire = s->pending_frame_acquire;
|
||||
s->pending_frame_acquire.fd_plus_one = 0;
|
||||
st->buffer = s->pending_buffer;
|
||||
wl_list_init(&st->buffer_destroy.link);
|
||||
if (st->buffer) {
|
||||
@@ -1186,6 +1202,7 @@ static void surface_attach(struct wl_client *c, struct wl_resource *r,
|
||||
if (s->pending_buffer) wl_list_remove(&s->pending_buffer_destroy.link);
|
||||
wl_list_init(&s->pending_buffer_destroy.link);
|
||||
s->pending_buffer = buffer;
|
||||
dd_frame_acquire_clear(&s->pending_frame_acquire);
|
||||
s->pending_attach = 1;
|
||||
if (buffer) {
|
||||
s->pending_buffer_destroy.notify = on_pending_buffer_destroyed;
|
||||
@@ -1451,6 +1468,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
|
||||
|
||||
surface_drop_idle(s);
|
||||
buf_trace_attach(buffer);
|
||||
dd_frame_acquire_clear(&s->frame_acquire);
|
||||
if (s->role == ROLE_CURSOR) {
|
||||
if (!buffer) {
|
||||
cursor_publish_hidden();
|
||||
@@ -1462,6 +1480,8 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
|
||||
if (buffer) surface_hold_idle(s, buffer);
|
||||
} else if (db) {
|
||||
take_dmabuf(s, db, buffer);
|
||||
s->frame_acquire = st->frame_acquire;
|
||||
st->frame_acquire.fd_plus_one = 0;
|
||||
} else if (shm) {
|
||||
drop_dmabuf(s, 1);
|
||||
take_shm(s, shm, buffer);
|
||||
@@ -1474,6 +1494,7 @@ static void surface_state_apply(struct surface *s, struct surface_state *st) {
|
||||
if (buffer) send_buffer_release(buffer);
|
||||
}
|
||||
}
|
||||
dd_frame_acquire_clear(&st->frame_acquire);
|
||||
pending_releases_apply(s);
|
||||
|
||||
wl_list_for_each(child, &s->children, child_link) {
|
||||
@@ -1538,6 +1559,7 @@ static void settle_unwaited(void) {
|
||||
}
|
||||
|
||||
static void surface_state_discard(struct surface_state *st) {
|
||||
dd_frame_acquire_clear(&st->frame_acquire);
|
||||
struct wl_resource *cb, *tmp;
|
||||
wl_list_remove(&st->buffer_destroy.link);
|
||||
wl_resource_for_each_safe(cb, tmp, &st->frames) wl_resource_destroy(cb);
|
||||
@@ -1549,6 +1571,8 @@ static void surface_state_merge(struct surface_state *older, struct surface_stat
|
||||
if (older->attach && !newer->attach) {
|
||||
newer->attach = 1;
|
||||
newer->buffer = older->buffer;
|
||||
newer->frame_acquire = older->frame_acquire;
|
||||
older->frame_acquire.fd_plus_one = 0;
|
||||
wl_list_remove(&older->buffer_destroy.link);
|
||||
wl_list_init(&older->buffer_destroy.link);
|
||||
if (newer->buffer) {
|
||||
@@ -1700,6 +1724,210 @@ static const struct wl_surface_interface surface_impl = {
|
||||
.offset = surface_offset,
|
||||
};
|
||||
|
||||
int droiddeck_surface_dup_acquire(const struct surface *s, const struct dmabuf_buffer *b) {
|
||||
return s && s->dmabuf && s->dmabuf_buf == b ? dd_frame_acquire_dup(&s->frame_acquire) : -1;
|
||||
}
|
||||
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
// Private signed fixture: only the app-owned worker decision may issue a grant.
|
||||
static pthread_mutex_t frame_worker_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static char frame_worker_file[PATH_MAX];
|
||||
static struct dd_worker_grant frame_worker_grant;
|
||||
static int frame_worker_pidfd = -1;
|
||||
static bool frame_worker_map_reported;
|
||||
|
||||
static enum dd_worker_stat_result frame_worker_starttime(pid_t pid, uint64_t *out) {
|
||||
char proc[64], line[4096];
|
||||
snprintf(proc, sizeof(proc), "/proc/%d/stat", pid);
|
||||
FILE *f = fopen(proc, "re");
|
||||
if (!f) return dd_worker_open_failure(errno);
|
||||
// Proc writes one bounded line; truncation is a read failure, not invisibility.
|
||||
bool read = fgets(line, sizeof(line), f) != NULL && strchr(line, '\n') != NULL;
|
||||
fclose(f);
|
||||
return read ? dd_worker_parse_start(line, out) : DD_WORKER_STAT_READ;
|
||||
}
|
||||
|
||||
void droiddeck_frame_worker_revoke(int owner, int pid) {
|
||||
pthread_mutex_lock(&frame_worker_lock);
|
||||
if (frame_worker_grant.owner == (uint32_t)owner &&
|
||||
(!pid || frame_worker_grant.pid == (uint32_t)pid)) {
|
||||
if (frame_worker_pidfd >= 0) close(frame_worker_pidfd);
|
||||
frame_worker_pidfd = -1;
|
||||
frame_worker_grant = (struct dd_worker_grant){0};
|
||||
}
|
||||
pthread_mutex_unlock(&frame_worker_lock);
|
||||
}
|
||||
|
||||
int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path,
|
||||
uint64_t expected_dev, uint64_t expected_ino, uint64_t receipt) {
|
||||
struct stat st;
|
||||
if (owner <= 0 || pid <= 1 || !receipt || !path ||
|
||||
strlen(path) >= sizeof(frame_worker_file) || lstat(path, &st) < 0 || !S_ISREG(st.st_mode) ||
|
||||
(uint64_t)st.st_dev != expected_dev || (uint64_t)st.st_ino != expected_ino ||
|
||||
st.st_uid != getuid()) {
|
||||
droiddeck_log("probe", "worker_admission=NATIVE_FILE");
|
||||
return 0;
|
||||
}
|
||||
int pidfd = syscall(__NR_pidfd_open, pid, 0);
|
||||
if (pidfd < 0) {
|
||||
droiddeck_log("probe", "worker_admission=NATIVE_PIDFD");
|
||||
return 0; // No fallback to a recyclable PID.
|
||||
}
|
||||
struct pollfd alive = {.fd = pidfd, .events = POLLIN};
|
||||
uint64_t raw_start = 0;
|
||||
enum dd_worker_stat_result stat = frame_worker_starttime(pid, &raw_start);
|
||||
switch (stat) {
|
||||
case DD_WORKER_STAT_OK:
|
||||
if (raw_start != receipt) droiddeck_log("probe", "worker_admission=NATIVE_STAT_MISMATCH");
|
||||
break;
|
||||
case DD_WORKER_STAT_DENIED: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_DENIED"); break;
|
||||
case DD_WORKER_STAT_HIDDEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_HIDDEN"); break;
|
||||
case DD_WORKER_STAT_OPEN: droiddeck_log("probe", "worker_admission=NATIVE_STAT_OPEN_OTHER"); break;
|
||||
case DD_WORKER_STAT_READ: droiddeck_log("probe", "worker_admission=NATIVE_STAT_READ"); break;
|
||||
case DD_WORKER_STAT_PARSE: droiddeck_log("probe", "worker_admission=NATIVE_STAT_PARSE"); break;
|
||||
case DD_WORKER_STAT_ZERO: droiddeck_log("probe", "worker_admission=NATIVE_STAT_ZERO"); break;
|
||||
}
|
||||
if (!dd_worker_receipt_allows_reserve(stat, raw_start, receipt)) { close(pidfd); return 0; }
|
||||
if (poll(&alive, 1, 0) != 0) {
|
||||
droiddeck_log("probe", "worker_admission=NATIVE_PIDFD_NOT_LIVE");
|
||||
close(pidfd);
|
||||
return 0;
|
||||
}
|
||||
pthread_mutex_lock(&frame_worker_lock);
|
||||
if (frame_worker_pidfd < 0) {
|
||||
strcpy(frame_worker_file, path);
|
||||
frame_worker_grant = (struct dd_worker_grant){
|
||||
.owner = owner, .uid = getuid(), .pid = pid, .start_ticks = receipt, .expires = expires,
|
||||
.dev_major = major(st.st_dev), .dev_minor = minor(st.st_dev), .ino = st.st_ino,
|
||||
.canonical_file = frame_worker_file, .app_launch_verified = true, .final_go = true,
|
||||
};
|
||||
frame_worker_map_reported = false;
|
||||
frame_worker_pidfd = pidfd;
|
||||
pidfd = -1;
|
||||
}
|
||||
pthread_mutex_unlock(&frame_worker_lock);
|
||||
if (pidfd >= 0) {
|
||||
droiddeck_log("probe", "worker_admission=NATIVE_ALREADY_RESERVED");
|
||||
close(pidfd);
|
||||
return 0;
|
||||
}
|
||||
droiddeck_log("probe", "frame acquire reserved one app-verified worker");
|
||||
return 1;
|
||||
}
|
||||
|
||||
static bool frame_worker_verified_exec_locked(const struct dd_worker_grant *g, uint64_t now) {
|
||||
char proc[64], line[PATH_MAX + 128];
|
||||
const char *failure = "worker_admission=MAP_STARTTIME";
|
||||
uint64_t raw_start = 0;
|
||||
if (frame_worker_starttime(g->pid, &raw_start) != DD_WORKER_STAT_OK || raw_start != g->start_ticks)
|
||||
goto reject;
|
||||
snprintf(proc, sizeof(proc), "/proc/%u/maps", g->pid);
|
||||
FILE *f = fopen(proc, "re");
|
||||
failure = "worker_admission=MAP_OPEN";
|
||||
if (!f) goto reject;
|
||||
bool matched = false;
|
||||
size_t budget = 2 * 1024 * 1024;
|
||||
while (budget && fgets(line, sizeof(line), f)) {
|
||||
size_t n = strlen(line);
|
||||
if (!n || line[n - 1] != '\n' || n > budget) break;
|
||||
budget -= n;
|
||||
if (dd_worker_grant_matches(g, g->owner, g->uid, g->pid, raw_start, now, line)) {
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
if (matched) return true;
|
||||
failure = "worker_admission=MAP_IDENTITY";
|
||||
reject:
|
||||
if (!frame_worker_map_reported) {
|
||||
frame_worker_map_reported = true;
|
||||
droiddeck_log("probe", "%s", failure);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static int frame_acquire_peer_allowed(const struct wl_client *client, bool verify_exec, bool bind) {
|
||||
pid_t pid = 0;
|
||||
uid_t uid = (uid_t)-1;
|
||||
wl_client_get_credentials(client, &pid, &uid, NULL);
|
||||
struct timespec t;
|
||||
if (clock_gettime(CLOCK_BOOTTIME, &t) < 0) return 0;
|
||||
uint64_t now = (uint64_t)t.tv_sec * 1000 + (uint64_t)t.tv_nsec / 1000000;
|
||||
pthread_mutex_lock(&frame_worker_lock);
|
||||
const struct dd_worker_grant *g = &frame_worker_grant;
|
||||
struct pollfd alive = {.fd = frame_worker_pidfd, .events = POLLIN};
|
||||
bool allowed = frame_worker_pidfd >= 0 && uid == getuid() && pid > 1 &&
|
||||
g->pid == (uint32_t)pid && g->uid == uid && now < g->expires &&
|
||||
poll(&alive, 1, 0) == 0 && (!verify_exec ||
|
||||
(frame_worker_verified_exec_locked(g, now) && poll(&alive, 1, 0) == 0));
|
||||
// The short startup authorization may not be renewed by registry enumeration.
|
||||
// Only an authenticated bind activates the grant for the lifetime of this live,
|
||||
// unreplaced worker; session teardown revokes it independently of process exit.
|
||||
if (allowed && bind) frame_worker_grant.expires = UINT64_MAX;
|
||||
pthread_mutex_unlock(&frame_worker_lock);
|
||||
return allowed;
|
||||
}
|
||||
|
||||
static bool frame_acquire_global_filter(const struct wl_client *client, const struct wl_global *global, void *data) {
|
||||
return wl_global_get_interface(global) != &droiddeck_frame_acquire_v1_interface ||
|
||||
frame_acquire_peer_allowed(client, true, false);
|
||||
}
|
||||
|
||||
static void frame_acquire_destroy(struct wl_client *client, struct wl_resource *resource) {
|
||||
wl_resource_destroy(resource);
|
||||
}
|
||||
|
||||
static void frame_acquire_set(struct wl_client *client, struct wl_resource *resource,
|
||||
struct wl_resource *surface, struct wl_resource *buffer, int32_t fd) {
|
||||
if (!frame_acquire_peer_allowed(client, false, false)) {
|
||||
close(fd);
|
||||
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_UNAUTHORIZED_PEER,
|
||||
"paired capture peer is not authorized");
|
||||
return;
|
||||
}
|
||||
struct surface *s = NULL;
|
||||
if (surface && buffer && wl_resource_get_client(surface) == client &&
|
||||
wl_resource_get_client(buffer) == client &&
|
||||
wl_resource_instance_of(surface, &wl_surface_interface, &surface_impl) &&
|
||||
get_dmabuf(buffer))
|
||||
s = wl_resource_get_user_data(surface);
|
||||
if (!s || !s->pending_attach || s->pending_buffer != buffer) {
|
||||
close(fd);
|
||||
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_ATTACHMENT,
|
||||
"fence does not match pending DMA-BUF attachment");
|
||||
return;
|
||||
}
|
||||
enum dd_frame_acquire_result result = dd_frame_acquire_set(&s->pending_frame_acquire, fd);
|
||||
if (result == DD_ACQUIRE_DUPLICATE)
|
||||
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_DUPLICATE_FENCE,
|
||||
"pending attachment already has a fence");
|
||||
else if (result == DD_ACQUIRE_INVALID)
|
||||
wl_resource_post_error(resource, DROIDDECK_FRAME_ACQUIRE_V1_ERROR_INVALID_FENCE,
|
||||
"expected an already signaled Linux sync_file");
|
||||
}
|
||||
|
||||
static const struct droiddeck_frame_acquire_v1_interface frame_acquire_impl = {
|
||||
.destroy = frame_acquire_destroy,
|
||||
.set_acquire_fence = frame_acquire_set,
|
||||
};
|
||||
|
||||
static void bind_frame_acquire(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
|
||||
if (!frame_acquire_peer_allowed(client, true, true)) {
|
||||
wl_client_post_implementation_error(client, "paired capture peer is not authorized");
|
||||
return;
|
||||
}
|
||||
struct wl_resource *resource =
|
||||
wl_resource_create(client, &droiddeck_frame_acquire_v1_interface, 1, id);
|
||||
if (!resource) {
|
||||
wl_client_post_no_memory(client);
|
||||
return;
|
||||
}
|
||||
wl_resource_set_implementation(resource, &frame_acquire_impl, NULL, NULL);
|
||||
droiddeck_log("probe", "frame acquire bound to app-issued worker and exact executable map");
|
||||
}
|
||||
#endif
|
||||
|
||||
static void detach_from_parent(struct surface *s) {
|
||||
if (!s->parent) return;
|
||||
wl_list_remove(&s->child_link);
|
||||
@@ -1709,6 +1937,7 @@ static void detach_from_parent(struct surface *s) {
|
||||
|
||||
static void surface_resource_destroy(struct wl_resource *r) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
dd_frame_acquire_clear(&s->pending_frame_acquire);
|
||||
struct surface *child, *tmp;
|
||||
struct wl_resource *cb, *cbtmp;
|
||||
|
||||
@@ -4804,6 +5033,7 @@ static int on_stats_timer(void *data) {
|
||||
struct surface *s;
|
||||
wl_list_for_each(s, &g_toplevels, toplevel_link) windows++;
|
||||
unsigned zero_copy = ahb_swapchain_stats_take();
|
||||
unsigned verified = ahb_swapchain_producer_fence_stats_take();
|
||||
unsigned layer_frames = sc_layer_frames_take();
|
||||
g_zero_copy_last = zero_copy;
|
||||
unsigned generated = vkp_framegen_stats_take();
|
||||
@@ -4812,7 +5042,8 @@ static int on_stats_timer(void *data) {
|
||||
int off = 0;
|
||||
if (g_zero_copy || zero_copy) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u zero-copy frames", zero_copy);
|
||||
if (layer_frames) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u layer frames", layer_frames);
|
||||
if (generated) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated);
|
||||
if (generated) off += snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u generated frames", generated);
|
||||
if (verified) snprintf(extra + off, sizeof(extra) - (size_t)off, " | %u verified acquire frames", verified);
|
||||
droiddeck_log("stats", "last 10 s: %u frames on screen (%.1f fps) | %u GPU frames from games | %u window redraws | %d windows open%s",
|
||||
g_stat_frames + generated, (g_stat_frames + generated) / 10.0, g_stat_dmabuf, g_stat_shm, windows, extra);
|
||||
}
|
||||
@@ -5013,6 +5244,12 @@ int droiddeck_wayland_run(void) {
|
||||
wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager);
|
||||
droiddeck_ext_init(display);
|
||||
ahb_swapchain_init(display);
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
if (ahb_swapchain_advertised()) {
|
||||
wl_display_set_global_filter(display, frame_acquire_global_filter, NULL);
|
||||
wl_global_create(display, &droiddeck_frame_acquire_v1_interface, 1, NULL, bind_frame_acquire);
|
||||
}
|
||||
#endif
|
||||
display_buffers_init(display);
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#ifndef DD_FRAME_ACQUIRE_H
|
||||
#define DD_FRAME_ACQUIRE_H
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <linux/sync_file.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <unistd.h>
|
||||
|
||||
/* A zero-initialized slot owns no descriptor. Only an already successful
|
||||
* sync_file can enter this slot; display-side release ownership is separate. */
|
||||
struct dd_frame_acquire { int fd_plus_one; };
|
||||
enum dd_frame_acquire_result { DD_ACQUIRE_OK, DD_ACQUIRE_DUPLICATE, DD_ACQUIRE_INVALID };
|
||||
|
||||
static inline 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;
|
||||
}
|
||||
|
||||
static inline enum dd_frame_acquire_result
|
||||
dd_frame_acquire_set(struct dd_frame_acquire *f, int fd) {
|
||||
enum dd_frame_acquire_result result;
|
||||
struct sync_file_info info = {0};
|
||||
if (f->fd_plus_one) result = DD_ACQUIRE_DUPLICATE;
|
||||
else if (fd < 0 || fd == INT_MAX || ioctl(fd, SYNC_IOC_FILE_INFO, &info) != 0 ||
|
||||
info.status != 1 || info.num_fences == 0) result = DD_ACQUIRE_INVALID;
|
||||
else {
|
||||
f->fd_plus_one = fd + 1;
|
||||
return DD_ACQUIRE_OK;
|
||||
}
|
||||
if (fd >= 0) close(fd);
|
||||
return result;
|
||||
}
|
||||
|
||||
static inline int dd_frame_acquire_dup(const struct dd_frame_acquire *f) {
|
||||
if (!f->fd_plus_one) return -1; /* Legacy: no explicit attachment proof. */
|
||||
int fd = fcntl(f->fd_plus_one - 1, F_DUPFD_CLOEXEC, 0);
|
||||
return fd < 0 ? -2 : fd; /* Do not re-enter the legacy direct path. */
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,81 @@
|
||||
#ifndef DD_WORKER_PEER_H
|
||||
#define DD_WORKER_PEER_H
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <inttypes.h>
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Model of one app-issued, session-bound authorization record. No callers,
|
||||
* property access, proc traversal, or authorization is installed by this file. */
|
||||
struct dd_worker_grant {
|
||||
uint32_t owner, uid, pid, dev_major, dev_minor;
|
||||
uint64_t start_ticks, ino, expires;
|
||||
const char *canonical_file;
|
||||
bool app_launch_verified, final_go;
|
||||
};
|
||||
|
||||
enum dd_worker_stat_result {
|
||||
DD_WORKER_STAT_OK, DD_WORKER_STAT_DENIED, DD_WORKER_STAT_HIDDEN, DD_WORKER_STAT_OPEN,
|
||||
DD_WORKER_STAT_READ, DD_WORKER_STAT_PARSE, DD_WORKER_STAT_ZERO,
|
||||
};
|
||||
|
||||
static inline enum dd_worker_stat_result dd_worker_parse_start(const char *line, uint64_t *out) {
|
||||
const char *p = strrchr(line, ')');
|
||||
if (!p || p[1] != ' ' || !p[2] || p[3] != ' ') return DD_WORKER_STAT_PARSE;
|
||||
p += 2;
|
||||
// State is field 3. The starttime (22) is always followed by vsize (23).
|
||||
for (int field = 3; field < 22; ++field) {
|
||||
p = strchr(p, ' ');
|
||||
if (!p) return DD_WORKER_STAT_PARSE;
|
||||
while (*p == ' ') ++p;
|
||||
}
|
||||
char *end;
|
||||
if (*p < '0' || *p > '9') return DD_WORKER_STAT_PARSE;
|
||||
errno = 0;
|
||||
uint64_t value = strtoull(p, &end, 10);
|
||||
if (errno || end == p || *end != ' ') return DD_WORKER_STAT_PARSE;
|
||||
if (!value) return DD_WORKER_STAT_ZERO;
|
||||
*out = value;
|
||||
return DD_WORKER_STAT_OK;
|
||||
}
|
||||
|
||||
static inline enum dd_worker_stat_result dd_worker_open_failure(int error) {
|
||||
if (error == EACCES || error == EPERM) return DD_WORKER_STAT_DENIED;
|
||||
if (error == ENOENT || error == ESRCH) return DD_WORKER_STAT_HIDDEN;
|
||||
return DD_WORKER_STAT_OPEN;
|
||||
}
|
||||
|
||||
static inline bool dd_worker_receipt_allows_reserve(enum dd_worker_stat_result stat,
|
||||
uint64_t raw, uint64_t receipt) {
|
||||
if (!receipt) return false;
|
||||
if (stat == DD_WORKER_STAT_OK) return raw == receipt;
|
||||
// Only a visibility denial can defer the broker-side stat check, not any
|
||||
// bad read, malformed record, mismatched timestamp, or other open error.
|
||||
return stat == DD_WORKER_STAT_DENIED || stat == DD_WORKER_STAT_HIDDEN;
|
||||
}
|
||||
|
||||
static inline bool dd_worker_map_matches(const struct dd_worker_grant *g, const char *line) {
|
||||
unsigned major, minor;
|
||||
uint64_t lo, hi, off, ino;
|
||||
int prefix = 0;
|
||||
char mode[5];
|
||||
if (!g->canonical_file || !*g->canonical_file ||
|
||||
sscanf(line, "%" SCNx64 "-%" SCNx64 " %4s %" SCNx64 " %x:%x %" SCNu64 " %n",
|
||||
&lo,&hi,mode,&off,&major,&minor,&ino,&prefix)!=7 ||
|
||||
prefix <= 0 || hi <= lo || strlen(mode)!=4 || mode[2]!='x' ||
|
||||
major!=g->dev_major || minor!=g->dev_minor || !ino || ino!=g->ino)
|
||||
return false;
|
||||
size_t path_len=strcspn(line+prefix,"\r\n");
|
||||
return strlen(g->canonical_file)==path_len && !memcmp(line+prefix,g->canonical_file,path_len);
|
||||
}
|
||||
|
||||
static inline bool dd_worker_grant_matches(const struct dd_worker_grant *g, uint32_t owner,
|
||||
uint32_t uid, uint32_t pid, uint64_t start, uint64_t now, const char *executable_map) {
|
||||
return g && g->app_launch_verified && g->final_go && owner && owner==g->owner &&
|
||||
uid==g->uid && pid>1 && pid==g->pid && start && start==g->start_ticks &&
|
||||
now<g->expires && executable_map && dd_worker_map_matches(g,executable_map);
|
||||
}
|
||||
#endif
|
||||
@@ -916,3 +916,42 @@ JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
|
||||
return (jint)droiddeck_stream_frames();
|
||||
}
|
||||
|
||||
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
extern int droiddeck_frame_worker_grant(int owner, pid_t pid, uint64_t expires, const char *path,
|
||||
uint64_t dev, uint64_t ino, uint64_t receipt);
|
||||
extern void droiddeck_frame_worker_revoke(int owner, int pid);
|
||||
#endif
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeEnabled(JNIEnv *env, jclass c) {
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
return JNI_TRUE;
|
||||
#else
|
||||
return JNI_FALSE;
|
||||
#endif
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeGrant(JNIEnv *env, jclass c,
|
||||
jint owner, jint pid, jlong expires, jstring path, jlong dev, jlong ino, jlong start_ticks) {
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
if (!path || expires <= 0 || ino <= 0 || start_ticks <= 0) return JNI_FALSE;
|
||||
const char *name = (*env)->GetStringUTFChars(env, path, NULL);
|
||||
if (!name) return JNI_FALSE;
|
||||
int granted = droiddeck_frame_worker_grant(owner, pid, (uint64_t)expires, name, (uint64_t)dev, (uint64_t)ino, (uint64_t)start_ticks);
|
||||
(*env)->ReleaseStringUTFChars(env, path, name);
|
||||
return granted ? JNI_TRUE : JNI_FALSE;
|
||||
#else
|
||||
return JNI_FALSE;
|
||||
#endif
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_frameWorkerProbeRevoke(JNIEnv *env, jclass c,
|
||||
jint owner, jint pid) {
|
||||
#ifdef DROIDDECK_FRAME_ACQUIRE_PROBE
|
||||
droiddeck_frame_worker_revoke(owner, pid);
|
||||
#endif
|
||||
}
|
||||
@@ -625,6 +625,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
|
||||
private var hdrOn by mutableStateOf(false)
|
||||
private var zeroCopyOn by mutableStateOf(true)
|
||||
private var producerAcquireFences by mutableStateOf(false)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
private var upscaleSharpness by mutableStateOf(75)
|
||||
private var hdrReason by mutableStateOf<String?>(null)
|
||||
@@ -2921,6 +2922,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
mode = mode, resolution = resolution, resolutionPortrait = resolutionPortrait,
|
||||
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
|
||||
hdr = hdrOn, hdrReason = hdrReason, hdrDisplay = hdrDisplay, zeroCopy = zeroCopyOn,
|
||||
producerAcquireFences = producerAcquireFences.takeIf {
|
||||
mode == SessionService.MODE_STEAM &&
|
||||
com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe.available(this)
|
||||
},
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
gpuDrivers = drivers.summary(),
|
||||
touchMode = touchMode,
|
||||
@@ -2985,6 +2990,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
SessionPrefs.prefMode(SessionState.mode) == SessionPrefs.prefMode(mode))
|
||||
com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetZeroCopy(on)
|
||||
},
|
||||
onProducerAcquireFences = {
|
||||
SessionPrefs.setProducerAcquireFences(this, it)
|
||||
producerAcquireFences = it
|
||||
},
|
||||
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
|
||||
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
|
||||
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
|
||||
@@ -3346,6 +3355,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
loadBootMovie()
|
||||
hdrOn = SessionPrefs.hdr(this, mode)
|
||||
zeroCopyOn = SessionPrefs.zeroCopy(this, mode)
|
||||
producerAcquireFences = SessionPrefs.producerAcquireFences(this)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
upscaleSharpness = SessionPrefs.upscaleSharpness(this)
|
||||
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.blocked(this)
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import android.system.Os
|
||||
import android.system.OsConstants
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption.NOFOLLOW_LINKS
|
||||
import java.security.MessageDigest
|
||||
|
||||
/** One app-issued Steam session and one attested Gamescope worker. This is not an
|
||||
* isolation boundary against arbitrary code already running as the Android app UID. */
|
||||
internal object FrameAcquireWorkerProbe {
|
||||
private const val SESSION_SCRIPT = "/usr/local/bin/droiddeck-session"
|
||||
private const val PATH = "/usr/local/bin/gamescope"
|
||||
private const val CAPABILITY = "linuxfs/usr/local/share/droiddeck/gamescope-producer-acquire-v1"
|
||||
internal const val GAMESCOPE_ENABLE = "GAMESCOPE_DROIDDECK_PRODUCER_ACQUIRE=1"
|
||||
internal const val GAME_ENABLE = "DROIDDECK_GAME_DROIDDECK_GAME_FRAME_ACQUIRE=1"
|
||||
private const val MAX_BINARY_BYTES = 32L * 1024L * 1024L
|
||||
internal const val RECEIPT_TAG = 0x44445046
|
||||
internal const val RECEIPT_BYTES = Int.SIZE_BYTES + Long.SIZE_BYTES
|
||||
private const val TTL_MS = 90_000L
|
||||
|
||||
internal data class Ticket(val owner: Int, val root: File, val configuredRoot: File, val binary: File, val expected: ByteArray, val expires: Long)
|
||||
internal data class Qualified(val ticket: Ticket, val dev: Long, val ino: Long, val mtime: Long, val ctime: Long)
|
||||
private var intent: Ticket? = null
|
||||
private var nativeOwner = 0
|
||||
private var nativePid = 0
|
||||
|
||||
private enum class Stage { ARM, MATCH, PUBLISH }
|
||||
private enum class Reason {
|
||||
ENABLED, 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
|
||||
}
|
||||
private val reported = mutableSetOf<Stage>()
|
||||
@Synchronized private fun breadcrumb(stage: Stage, reason: Reason) {
|
||||
if (reported.add(stage)) Log.i("FrameAcquireWorkerProbe", "worker_admission=" + reason.name)
|
||||
}
|
||||
|
||||
internal fun validEnvironment(agentEnvironment: List<String>, customEnvironment: List<String>): Boolean {
|
||||
// AgentEnv supplies a replacement PATH whenever any executable override is staged.
|
||||
// Custom env is user-editable, including names not known to this build; it is not a trust root.
|
||||
return agentEnvironment.isEmpty() && customEnvironment.isEmpty()
|
||||
}
|
||||
|
||||
fun available(context: Context): Boolean =
|
||||
android.os.Build.VERSION.SDK_INT >= 30 && com.droiddeck.launcher.core.DeviceSupport.adreno() &&
|
||||
runCatching { context.assets.open(CAPABILITY).use { it.readBytes().decodeToString() } }
|
||||
.getOrNull() == "droiddeck-producer-acquire-v1\n"
|
||||
|
||||
private fun digest(input: InputStream, maxBytes: Long): ByteArray {
|
||||
val out = MessageDigest.getInstance("SHA-256")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var size = 0L
|
||||
while (true) {
|
||||
val n = input.read(buffer)
|
||||
if (n == -1) break
|
||||
require(n > 0)
|
||||
size += n
|
||||
require(size <= maxBytes)
|
||||
out.update(buffer, 0, n)
|
||||
}
|
||||
require(size > 0)
|
||||
return out.digest()
|
||||
}
|
||||
|
||||
// Compute asset identity outside SessionService's stop lock and before a worker
|
||||
// exists. The resulting ticket still has to be assigned to that exact owner.
|
||||
internal fun prepare(context: Context): Ticket? {
|
||||
if (!available(context) || !WaylandCompositor.frameWorkerProbeEnabled()) return null
|
||||
return runCatching {
|
||||
val configuredRoot = LinuxRuntime.rootDir(context).absoluteFile
|
||||
val root = configuredRoot.canonicalFile
|
||||
val file = File(root.path + PATH)
|
||||
require(file.canonicalFile == file && Files.isRegularFile(file.toPath(), NOFOLLOW_LINKS))
|
||||
val script = File(root.path + SESSION_SCRIPT)
|
||||
require(exactSteamScript(SESSION_SCRIPT, root, configuredRoot))
|
||||
val stagedScript = script.inputStream().use { digest(it, 1024L * 1024L) }
|
||||
val signedScript = context.assets.open("linuxfs" + SESSION_SCRIPT).use { digest(it, 1024L * 1024L) }
|
||||
require(MessageDigest.isEqual(stagedScript, signedScript))
|
||||
val expected = context.assets.open("linuxfs" + PATH).use { digest(it, MAX_BINARY_BYTES) }
|
||||
Ticket(0, root, configuredRoot, file, expected, SystemClock.elapsedRealtime() + TTL_MS)
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
@Synchronized fun arm(owner: Int, prepared: Ticket): Boolean {
|
||||
if (owner <= 0 || SystemClock.elapsedRealtime() >= prepared.expires) return false
|
||||
reported.clear()
|
||||
intent = prepared.copy(owner = owner)
|
||||
breadcrumb(Stage.ARM, Reason.ENABLED)
|
||||
return true
|
||||
}
|
||||
|
||||
/** Native shebang handling can give Bash the staged host filename as its $0. */
|
||||
internal fun exactSteamScript(token: String, root: File, configuredRoot: File): Boolean {
|
||||
if (token != SESSION_SCRIPT && token != root.path + SESSION_SCRIPT &&
|
||||
token != configuredRoot.path + SESSION_SCRIPT) return false
|
||||
return runCatching {
|
||||
val expected = File(root.path + SESSION_SCRIPT)
|
||||
val supplied = if (token == SESSION_SCRIPT) expected else File(token)
|
||||
// Reject symlinks within the authorized root, including a symlink replacing the script.
|
||||
// Android's configured root itself may be an alias of its app-issued canonical root.
|
||||
require(configuredRoot.canonicalFile == root && expected.canonicalFile == expected &&
|
||||
supplied.canonicalFile == expected &&
|
||||
Files.isRegularFile(expected.toPath(), NOFOLLOW_LINKS) &&
|
||||
Files.isRegularFile(supplied.toPath(), NOFOLLOW_LINKS))
|
||||
Files.isSameFile(supplied.toPath(), expected.toPath())
|
||||
}.getOrDefault(false)
|
||||
}
|
||||
|
||||
internal fun exactGamescopeArgs(argv: List<String>, script: (String) -> Boolean): Boolean {
|
||||
if (argv.firstOrNull() !in listOf("gamescope", PATH)) return false
|
||||
val delimiter = argv.indexOf("--")
|
||||
if (delimiter < 4 || argv.size != delimiter + 3 || argv[delimiter + 2] != "steam" ||
|
||||
!script(argv[delimiter + 1])) return false
|
||||
val opts = argv.subList(1, delimiter)
|
||||
if (opts.take(4) != listOf("--backend", "wayland", "--expose-wayland", "-f")) return false
|
||||
val dimensions = setOf("-W", "-H", "-w", "-h")
|
||||
val seen = mutableSetOf<String>()
|
||||
var i = 4
|
||||
while (i < opts.size) {
|
||||
val option = opts[i++]
|
||||
if (!seen.add(option)) return false
|
||||
when (option) {
|
||||
"-e", "--hdr-enabled", "--mangoapp" -> Unit
|
||||
"-S" -> if (opts.getOrNull(i++) != "stretch") return false
|
||||
"--default-touch-mode" -> if (opts.getOrNull(i++) != "4") return false
|
||||
"-W", "-H", "-w", "-h", "-r", "--xwayland-count" -> {
|
||||
val value = opts.getOrNull(i++) ?: return false
|
||||
if (value.length !in 1..6 || value.any { it !in '0'..'9' } ||
|
||||
value.toIntOrNull()?.let { it > 0 } != true) return false
|
||||
}
|
||||
else -> return false
|
||||
}
|
||||
}
|
||||
return seen.containsAll(dimensions)
|
||||
}
|
||||
|
||||
fun match(owner: Int, root: File, file: String, argv: List<String>, ack: Boolean): Qualified? {
|
||||
val t = synchronized(this) { intent } ?: return null
|
||||
// Startup's --version worker and unrelated workers must not consume the one diagnostic.
|
||||
val candidate = "--version" !in argv && (file.substringAfterLast('/') == "gamescope" ||
|
||||
argv.firstOrNull()?.substringAfterLast('/') == "gamescope")
|
||||
val rejection = when {
|
||||
!ack -> Reason.MATCH_ACK
|
||||
t.owner != owner -> Reason.MATCH_OWNER
|
||||
SystemClock.elapsedRealtime() >= t.expires -> Reason.MATCH_EXPIRED
|
||||
file != PATH -> Reason.MATCH_PATH
|
||||
runCatching { root.canonicalFile }.getOrNull() != t.root -> Reason.MATCH_ROOT
|
||||
!exactGamescopeArgs(argv) { exactSteamScript(it, t.root, t.configuredRoot) } -> Reason.MATCH_ARGV
|
||||
else -> null
|
||||
}
|
||||
if (rejection != null) {
|
||||
if (candidate) breadcrumb(Stage.MATCH, rejection)
|
||||
return null
|
||||
}
|
||||
// Hash an actual descriptor rather than two pathname opens. Check both the
|
||||
// descriptor and pathname identity; a race or substituted executable denies the grant.
|
||||
val qualified = runCatching {
|
||||
require(t.binary.canonicalFile == t.binary)
|
||||
val before = Os.lstat(t.binary.path)
|
||||
require(OsConstants.S_ISREG(before.st_mode) && before.st_size in 1..MAX_BINARY_BYTES)
|
||||
val fd = Os.open(t.binary.path, OsConstants.O_RDONLY or OsConstants.O_NOFOLLOW or OsConstants.O_CLOEXEC, 0)
|
||||
val sum = try {
|
||||
require(stillSame(before, Os.fstat(fd)))
|
||||
android.os.ParcelFileDescriptor.AutoCloseInputStream(android.os.ParcelFileDescriptor.dup(fd)).use {
|
||||
digest(it, MAX_BINARY_BYTES)
|
||||
}.also { require(stillSame(before, Os.fstat(fd))) }
|
||||
} finally {
|
||||
Os.close(fd)
|
||||
}
|
||||
val after = Os.lstat(t.binary.path)
|
||||
require(stillSame(before, after))
|
||||
if (!MessageDigest.isEqual(sum, t.expected)) {
|
||||
breadcrumb(Stage.MATCH, Reason.MATCH_DIGEST)
|
||||
return null
|
||||
}
|
||||
Qualified(t, after.st_dev, after.st_ino, after.st_mtime, after.st_ctime)
|
||||
}.getOrNull()
|
||||
breadcrumb(Stage.MATCH, if (qualified == null) Reason.MATCH_FILE else Reason.QUALIFIED)
|
||||
return qualified
|
||||
}
|
||||
|
||||
private fun stillSame(a: android.system.StructStat, b: android.system.StructStat): Boolean =
|
||||
a.st_dev == b.st_dev && a.st_ino == b.st_ino && a.st_size == b.st_size &&
|
||||
a.st_mtime == b.st_mtime && a.st_ctime == b.st_ctime &&
|
||||
OsConstants.S_ISREG(b.st_mode)
|
||||
|
||||
internal fun validReceipt(pid: Int, workerPid: Int, ticks: Long, bytes: Int): Long =
|
||||
if (pid > 1 && pid == workerPid && ticks > 0 && bytes == RECEIPT_BYTES) ticks else 0L
|
||||
|
||||
internal fun parseSelfStat(stat: String, pid: Int): Long {
|
||||
if (pid <= 1 || !stat.startsWith("$pid (")) return 0L
|
||||
val comm = stat.lastIndexOf(')')
|
||||
if (comm < 3 || stat.getOrNull(comm + 1) != ' ') return 0L
|
||||
val fields = stat.substring(comm + 2).split(' ').filter { it.isNotEmpty() }
|
||||
if (fields.firstOrNull()?.length != 1 || fields.size < 21) return 0L
|
||||
val value = fields[19] // field 22 from field 3 (the single-character task state).
|
||||
return value.takeIf { it.isNotEmpty() && it.all { ch -> ch in '0'..'9' } }
|
||||
?.toLongOrNull()?.takeIf { it > 0 } ?: 0L
|
||||
}
|
||||
|
||||
internal fun selfStartTicks(pid: Int): Long = runCatching {
|
||||
File("/proc/self/stat").inputStream().use { input ->
|
||||
val bytes = ByteArray(4096)
|
||||
var used = 0
|
||||
while (used < bytes.size) {
|
||||
val n = input.read(bytes, used, bytes.size - used)
|
||||
if (n < 0) break
|
||||
if (n == 0) return@runCatching 0L
|
||||
used += n
|
||||
}
|
||||
if (used == bytes.size || used == 0 || bytes[used-1] != '\n'.code.toByte()) 0L
|
||||
else parseSelfStat(String(bytes, 0, used, Charsets.US_ASCII), pid)
|
||||
}
|
||||
}.getOrDefault(0L)
|
||||
|
||||
/** Runs just before the final GO byte. Failure never changes ordinary launch. */
|
||||
@Synchronized fun publish(q: Qualified, pid: Int, startTicks: Long) {
|
||||
val t = q.ticket
|
||||
if (intent !== t || pid <= 1 || SystemClock.elapsedRealtime() >= t.expires) {
|
||||
if (intent === t) breadcrumb(Stage.PUBLISH, Reason.PUBLISH_TICKET)
|
||||
return
|
||||
}
|
||||
intent = null // At most one candidate per explicitly armed session.
|
||||
if (startTicks <= 0L) {
|
||||
breadcrumb(Stage.PUBLISH, Reason.PUBLISH_RECEIPT)
|
||||
return
|
||||
}
|
||||
val status = runCatching {
|
||||
val st = Os.lstat(t.binary.path)
|
||||
require(OsConstants.S_ISREG(st.st_mode) && st.st_dev == q.dev && st.st_ino == q.ino &&
|
||||
st.st_mtime == q.mtime && st.st_ctime == q.ctime)
|
||||
if (WaylandCompositor.frameWorkerProbeGrant(t.owner, pid, t.expires, t.binary.path, st.st_dev, st.st_ino, startTicks)) {
|
||||
nativeOwner = t.owner
|
||||
nativePid = pid
|
||||
Reason.RESERVED
|
||||
} else Reason.PUBLISH_NATIVE
|
||||
}.getOrDefault(Reason.PUBLISH_RESTAT)
|
||||
breadcrumb(Stage.PUBLISH, status)
|
||||
}
|
||||
|
||||
@Synchronized fun revoke(owner: Int, pid: Int = 0) {
|
||||
if (owner <= 0) return
|
||||
if (pid == 0 && intent?.owner == owner) intent = null
|
||||
if (nativeOwner == owner && (pid == 0 || pid == nativePid)) {
|
||||
WaylandCompositor.frameWorkerProbeRevoke(owner, pid)
|
||||
nativeOwner = 0
|
||||
nativePid = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,16 @@ open class GuestWorker : Service() {
|
||||
val fillBinderFd = data.readInt() != 0
|
||||
val go = data.readFileDescriptor()
|
||||
val nice = data.readInt()
|
||||
reply?.writeInt(Process.myPid())
|
||||
val pid = Process.myPid()
|
||||
reply?.writeInt(pid)
|
||||
// Optional fixed-size receipt, on the exact local, non-exported worker's Binder.
|
||||
// Nothing in the guest socket request populates these fields.
|
||||
if (reply != null &&
|
||||
Binder.getCallingUid() == Process.myUid() &&
|
||||
data.dataAvail() == Int.SIZE_BYTES && data.readInt() == FrameAcquireWorkerProbe.RECEIPT_TAG) {
|
||||
reply.writeInt(pid)
|
||||
reply.writeLong(FrameAcquireWorkerProbe.selfStartTicks(pid))
|
||||
}
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
// The app writes a byte once it has the reply and has taken the launch on: an exec
|
||||
// before then would end this process with the reply undelivered, and with none (the
|
||||
@@ -437,7 +446,8 @@ object GuestWorkers {
|
||||
private fun start(context: Context, argv: List<String>, env: List<String>, fds: List<ParcelFileDescriptor>, targets: IntArray,
|
||||
guest: Boolean, onExit: (Int) -> Unit, commit: (Int) -> Boolean = { true },
|
||||
confirmed: () -> Boolean = { true }, owner: Int = session,
|
||||
nice: Int = Process.getThreadPriority(Process.myTid())): Int {
|
||||
nice: Int = Process.getThreadPriority(Process.myTid()),
|
||||
testWorker: FrameAcquireWorkerProbe.Qualified? = null): Int {
|
||||
val app = context.applicationContext
|
||||
if (guest && owner <= stopped) {
|
||||
Log.w(TAG, (if (owner == 0) "a request naming no session" else "session $owner is stopping") +
|
||||
@@ -473,13 +483,21 @@ object GuestWorkers {
|
||||
data.writeInt(if (guest) 0 else 1)
|
||||
data.writeFileDescriptor(go[0].fileDescriptor)
|
||||
data.writeInt(nice)
|
||||
slot.service!!.transact(GuestWorker.RUN, data, reply, 0)
|
||||
val service = checkNotNull(slot.service)
|
||||
if (testWorker != null) data.writeInt(FrameAcquireWorkerProbe.RECEIPT_TAG)
|
||||
check(service.transact(GuestWorker.RUN, data, reply, 0))
|
||||
// The worker has its own copy: with ours closed (and the request's, which holds one too),
|
||||
// a worker that gave up leaves no reader
|
||||
data.recycle()
|
||||
data = null
|
||||
go[0].close()
|
||||
val pid = reply.readInt()
|
||||
val startTicks = if (testWorker != null) {
|
||||
val size = reply.dataAvail()
|
||||
if (size == FrameAcquireWorkerProbe.RECEIPT_BYTES)
|
||||
FrameAcquireWorkerProbe.validReceipt(pid, reply.readInt(), reply.readLong(), size)
|
||||
else 0L
|
||||
} else 0L
|
||||
// Once a session's teardown has begun (stopGuests), none of its programs may start: it
|
||||
// would not find them.
|
||||
val stopping = { guest && owner <= stopped }
|
||||
@@ -508,7 +526,12 @@ object GuestWorkers {
|
||||
// launching slot), or never.
|
||||
val answered = Os.poll(arrayOf(answer), ANSWER_TIMEOUT_MS) > 0 && Os.read(go[1].fileDescriptor, ByteArray(1), 0, 1) == 1
|
||||
val accepted = answered && synchronized(authorizing) {
|
||||
!stopping() && confirmed() && Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
|
||||
if (stopping() || !confirmed()) false
|
||||
else {
|
||||
if (testWorker != null) FrameAcquireWorkerProbe.publish(testWorker, pid,
|
||||
if (slot.service === service) startTicks else 0L)
|
||||
Os.write(go[1].fileDescriptor, byteArrayOf(1), 0, 1) == 1
|
||||
}
|
||||
}
|
||||
val endedRunning = synchronized(slots) {
|
||||
slot.launching = false
|
||||
@@ -685,6 +708,7 @@ object GuestWorkers {
|
||||
}
|
||||
}
|
||||
context?.let { app -> drained.forEach { release(app, it) } }
|
||||
FrameAcquireWorkerProbe.revoke(of)
|
||||
val pids = guestPids(of)
|
||||
if (pids.isEmpty()) return
|
||||
pids.forEach { Process.sendSignal(it, OsConstants.SIGTERM) }
|
||||
@@ -902,16 +926,19 @@ object GuestWorkers {
|
||||
val owner = request.optInt("session", 0).coerceAtLeast(0)
|
||||
// The sender is the forked child (or droiddeck-spawn): its priority is the one the program would inherit
|
||||
val nice = runCatching { Process.getThreadPriority(client.peerCredentials.pid) }.getOrDefault(Process.THREAD_PRIORITY_DEFAULT)
|
||||
val testWorker = FrameAcquireWorkerProbe.match(owner, root, file, argv, ack)
|
||||
val pid = start(app, command, env.map { (k, v) -> "$k=$v" }, programFds, targets, true, owner = owner, nice = nice, onExit = { code ->
|
||||
if (testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker)
|
||||
status = code
|
||||
if (table != null && slot >= 0) reportExit(table, slot, code, parent, child, worker)
|
||||
exited.countDown()
|
||||
}, confirmed = {
|
||||
!ack || runCatching {
|
||||
val confirmed = !ack || runCatching {
|
||||
out.write("ok\n".toByteArray())
|
||||
out.flush()
|
||||
confirmedToHook = true
|
||||
}.isSuccess
|
||||
confirmed
|
||||
}, commit = { started ->
|
||||
worker = started
|
||||
if (!ack) return@start true
|
||||
@@ -930,7 +957,8 @@ object GuestWorkers {
|
||||
}
|
||||
ended && line.toString() == "go"
|
||||
}.getOrDefault(false)
|
||||
})
|
||||
}, testWorker = testWorker)
|
||||
if (pid <= 0 && testWorker != null && worker > 1) FrameAcquireWorkerProbe.revoke(owner, worker)
|
||||
handedOver = true
|
||||
programFds.filter { it !== table }.forEach { runCatching { it.close() } }
|
||||
if (pid <= 0) table?.let { runCatching { it.close() } }
|
||||
|
||||
@@ -1874,6 +1874,13 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean(hdrKey(mode), on).apply()
|
||||
}
|
||||
|
||||
/** Restart-scoped opt-in; not inferred from Zero-copy (which defaults on). */
|
||||
fun producerAcquireFences(context: Context): Boolean = prefs(context).getBoolean("producerAcquireFences", false)
|
||||
|
||||
fun setProducerAcquireFences(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("producerAcquireFences", on).apply()
|
||||
}
|
||||
|
||||
fun zeroCopy(context: Context, mode: String): Boolean = prefs(context).getBoolean("zeroCopy.${prefMode(mode)}", true)
|
||||
|
||||
fun setZeroCopy(context: Context, mode: String, on: Boolean) {
|
||||
|
||||
@@ -555,9 +555,10 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
}
|
||||
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
|
||||
val nextAgentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
|
||||
.onFailure { Log.w(TAG, "agent environment skipped", it) }
|
||||
.getOrDefault(emptyList())
|
||||
val agentEnvironment = nextAgentEnvironment.getOrDefault(emptyList())
|
||||
val customEnvironment = extraEnv()
|
||||
try {
|
||||
if (systemVulkan) {
|
||||
SystemVulkanDriver.prepare(this)
|
||||
@@ -623,7 +624,7 @@ class SessionService : Service() {
|
||||
.onFailure { Log.w(TAG, "forced components", it) }
|
||||
}
|
||||
try {
|
||||
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment) }
|
||||
SessionEvents.step("client-environment") { addClientEnvironment(guest, steamHere, agentEnvironment, customEnvironment) }
|
||||
} catch (e: IllegalStateException) {
|
||||
Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e)
|
||||
failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1)
|
||||
@@ -708,15 +709,27 @@ class SessionService : Service() {
|
||||
// this session's worker number: the shared field may be a newer session's by the time it is used
|
||||
var ownWorkers = 0
|
||||
if (com.droiddeck.launcher.runtime.GuestWorkers.enabled(this)) {
|
||||
val fenceWorker = com.droiddeck.launcher.runtime.FrameAcquireWorkerProbe
|
||||
val preparedFence = if (steamHere && !systemVulkan && !VenusComponent.wanted(this) &&
|
||||
SessionPrefs.zeroCopy(this, MODE_STEAM) && SessionPrefs.producerAcquireFences(this) &&
|
||||
nextAgentEnvironment.isSuccess && fenceWorker.validEnvironment(agentEnvironment, customEnvironment)) fenceWorker.prepare(this) else null
|
||||
var fenceArmed = false
|
||||
// Under the lock a stop takes its number with: a stop either comes first (and this session
|
||||
// starts no workers) or owns them
|
||||
ownWorkers = synchronized(stopLock) {
|
||||
if (gen != sessionGen || !SessionState.running) 0
|
||||
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also { guestWorkerSession = it }
|
||||
else com.droiddeck.launcher.runtime.GuestWorkers.serve(this).also {
|
||||
guestWorkerSession = it
|
||||
if (preparedFence != null) fenceArmed = fenceWorker.arm(it, preparedFence)
|
||||
}
|
||||
}
|
||||
if (ownWorkers > 0) {
|
||||
guest.add("DD_SPAWN=" + com.droiddeck.launcher.runtime.GuestWorkers.socketName(this))
|
||||
guest.add("DD_SPAWN_SESSION=$ownWorkers")
|
||||
if (fenceArmed) {
|
||||
guest.add(fenceWorker.GAMESCOPE_ENABLE)
|
||||
guest.add(fenceWorker.GAME_ENABLE)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Proton builds up to 11.12 report X11 text fields under this name.
|
||||
@@ -1017,7 +1030,8 @@ class SessionService : Service() {
|
||||
return com.droiddeck.launcher.input.GesturePrefs.read(this, game).relativeMouseMode
|
||||
}
|
||||
|
||||
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) {
|
||||
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean,
|
||||
agentEnvironment: List<String>, customEnvironment: List<String>) {
|
||||
guest.add("/usr/bin/env")
|
||||
guest.add("-i")
|
||||
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
|
||||
@@ -1135,7 +1149,7 @@ class SessionService : Service() {
|
||||
guest.add("DD_ZRAM=1")
|
||||
}
|
||||
guest.add("AUDIO_DIRECT_DECAY=0")
|
||||
val extra = extraEnv() + agentEnvironment
|
||||
val extra = customEnvironment + agentEnvironment
|
||||
guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra))
|
||||
if (extra.none { it.startsWith("MESA_NO_ERROR=") }) guest.add("${GAME_PREFIX}MESA_NO_ERROR=")
|
||||
extra.forEach { guest.add(it) }
|
||||
|
||||
@@ -20,7 +20,7 @@ object SettingsReset {
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "avoidNotch", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "drawerPageOrder", "drawerPageHidden", "drawerSections", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores",
|
||||
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "producerAcquireFences", "paceCores",
|
||||
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite", "mountSharedStorage",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
||||
|
||||
@@ -62,6 +62,7 @@ class ModeSettings(
|
||||
val hdrReason: String?,
|
||||
val hdrDisplay: Boolean = true,
|
||||
val zeroCopy: Boolean = true,
|
||||
val producerAcquireFences: Boolean? = null,
|
||||
val gpuDrivers: String? = null,
|
||||
val upscaler: Int = 0,
|
||||
val upscaleSharpness: Int = 75,
|
||||
@@ -125,6 +126,7 @@ class ModeSettingsActions(
|
||||
val onResolutionPortrait: (String) -> Unit = {},
|
||||
val onHdr: (Boolean) -> Unit,
|
||||
val onZeroCopy: (Boolean) -> Unit = {},
|
||||
val onProducerAcquireFences: (Boolean) -> Unit = {},
|
||||
val onGpuDrivers: () -> Unit = {},
|
||||
val onUpscaler: (Int) -> Unit = {},
|
||||
val onUpscaleSharpness: (Int) -> Unit = {},
|
||||
@@ -284,6 +286,11 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
stringResource(R.string.display_avoid_notch_hint), checked = enabled, onChange = a.onAvoidNotch)
|
||||
}
|
||||
ToggleRow(host, "zero-copy", stringResource(R.string.display_zero_copy), null, checked = s.zeroCopy, onChange = a.onZeroCopy)
|
||||
s.producerAcquireFences?.let { enabled ->
|
||||
ToggleRow(host, "producer-acquire-fences", stringResource(R.string.producer_acquire_fences),
|
||||
stringResource(R.string.producer_acquire_fences_summary), checked = enabled,
|
||||
onChange = a.onProducerAcquireFences)
|
||||
}
|
||||
}
|
||||
SettingsGroup(stringResource(R.string.display_image_scaling)) {
|
||||
s.integerScaling?.let { enabled ->
|
||||
|
||||
@@ -9,6 +9,10 @@ public final class WaylandCompositor {
|
||||
|
||||
private WaylandCompositor() {}
|
||||
|
||||
public static native boolean frameWorkerProbeEnabled();
|
||||
public static native boolean frameWorkerProbeGrant(int owner, int pid, long expires, String path, long dev, long ino, long startTicks);
|
||||
public static native void frameWorkerProbeRevoke(int owner, int pid);
|
||||
|
||||
private static volatile Runnable firstFrameListener;
|
||||
|
||||
public static void setFirstFrameListener(Runnable r) { firstFrameListener = r; }
|
||||
|
||||
@@ -4514,4 +4514,6 @@
|
||||
<string name="steam_store_close_steam">Close Steam first</string>
|
||||
<string name="steam_store_session_wait">Pause the Steam download first</string>
|
||||
<string name="steam_store_linux_build">This game installs its Linux build. Install it from Steam.</string>
|
||||
<string name="producer_acquire_fences">Direct game frames (experimental)</string>
|
||||
<string name="producer_acquire_fences_summary">With Zero-copy enabled, compatible Steam games can avoid a frame copy. Takes effect next session.</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import java.io.File
|
||||
import java.nio.file.Files
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class FrameAcquireWorkerProbeTest {
|
||||
@Test fun requiresExactSteamScriptInTheAppIssuedGuestRoot() {
|
||||
val dir = Files.createTempDirectory("worker-probe-script").toFile().canonicalFile
|
||||
try {
|
||||
val root = File(dir, "root").apply { mkdir() }
|
||||
val configured = File(dir, "configured")
|
||||
Files.createSymbolicLink(configured.toPath(), root.toPath())
|
||||
val untrustedAlias = File(dir, "other-alias")
|
||||
Files.createSymbolicLink(untrustedAlias.toPath(), root.toPath())
|
||||
val script = "/usr/local/bin/droiddeck-session"
|
||||
val expected = File(root.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") }
|
||||
val otherRoot = File(dir, "sibling")
|
||||
File(otherRoot.path + script).apply { parentFile!!.mkdirs(); writeText("#!/bin/bash\n") }
|
||||
val otherScript = File(expected.parentFile, "other-script").apply { writeText("#!/bin/bash\n") }
|
||||
|
||||
val args = listOf("gamescope", "--backend", "wayland", "--expose-wayland", "-f",
|
||||
"-W", "1280", "-H", "720", "-w", "1280", "-h", "720", "-r", "60",
|
||||
"-e", "--xwayland-count", "2", "--default-touch-mode", "4", "--hdr-enabled",
|
||||
"--", script, "steam")
|
||||
fun valid(argv: List<String>) = FrameAcquireWorkerProbe.exactGamescopeArgs(argv) {
|
||||
FrameAcquireWorkerProbe.exactSteamScript(it, root, configured)
|
||||
}
|
||||
fun child(path: String) = args.dropLast(2) + listOf(path, "steam")
|
||||
|
||||
assertTrue(valid(args))
|
||||
assertTrue(valid(args.toMutableList().also { it[0] = "/usr/local/bin/gamescope" }))
|
||||
assertFalse(valid(args.toMutableList().also { it[0] = "/opt/droiddeck-agent/bin/gamescope" }))
|
||||
assertTrue(valid(child(root.path + script)))
|
||||
assertTrue(valid(child(configured.path + script)))
|
||||
for (path in listOf(otherRoot.path + script, untrustedAlias.path + script,
|
||||
root.path + "/usr/local/bin/./droiddeck-session", root.path + "/../sibling" + script,
|
||||
otherScript.path, "droiddeck-session")) {
|
||||
assertFalse(valid(child(path)))
|
||||
}
|
||||
for (bad in listOf(listOf("gamescope", "--version"), args + "",
|
||||
args + "steam://open/library", args.dropLast(1) + "desktop",
|
||||
args.take(5) + "--unknown-flag" + args.drop(5),
|
||||
args.take(5) + listOf("-W", "64") + args.drop(5))) {
|
||||
assertFalse(valid(bad))
|
||||
}
|
||||
|
||||
assertTrue(expected.delete())
|
||||
Files.createSymbolicLink(expected.toPath(), otherScript.toPath())
|
||||
assertFalse(valid(args))
|
||||
assertFalse(valid(child(configured.path + script)))
|
||||
} finally {
|
||||
// Don't follow the intentionally broken/foreign symlinks in this fixture.
|
||||
Files.walk(dir.toPath()).use { paths ->
|
||||
paths.sorted(Comparator.reverseOrder()).forEach { Files.deleteIfExists(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test fun selfStatAndFixedBinderReceiptRejectWrongWorkerAndExtraBytes() {
|
||||
val probe = FrameAcquireWorkerProbe
|
||||
val fields = (1..18).joinToString(" ")
|
||||
fun stat(pid: Int, ticks: String) = "$pid (guest )worker) S $fields $ticks 123\n"
|
||||
assertTrue(probe.parseSelfStat(stat(400, "125"), 400) == 125L)
|
||||
for (bad in listOf(stat(401, "125"), stat(400, "0"), stat(400, "-1"),
|
||||
stat(400, "1x"), stat(400, "9223372036854775808"), "400 (guest)")) {
|
||||
assertTrue(probe.parseSelfStat(bad, 400) == 0L)
|
||||
}
|
||||
val size = probe.RECEIPT_BYTES
|
||||
assertTrue(probe.validReceipt(400, 400, 125L, size) == 125L)
|
||||
assertTrue(probe.validReceipt(400, 401, 125L, size) == 0L)
|
||||
assertTrue(probe.validReceipt(1, 1, 125L, size) == 0L)
|
||||
assertTrue(probe.validReceipt(400, 400, 0L, size) == 0L)
|
||||
assertTrue(probe.validReceipt(400, 400, -1L, size) == 0L)
|
||||
assertTrue(probe.validReceipt(400, 400, 125L, size - 4) == 0L)
|
||||
assertTrue(probe.validReceipt(400, 400, 125L, size + 4) == 0L)
|
||||
}
|
||||
|
||||
@Test fun anyCustomOrAgentEnvironmentDisablesTheProductionTicket() {
|
||||
val probe = FrameAcquireWorkerProbe
|
||||
assertTrue(probe.validEnvironment(emptyList(), emptyList()))
|
||||
assertFalse(probe.validEnvironment(listOf("PATH=/opt/droiddeck-agent/bin"), emptyList()))
|
||||
assertFalse(probe.validEnvironment(emptyList(), listOf("LD_PRELOAD=/tmp/custom.so")))
|
||||
assertFalse(probe.validEnvironment(listOf("DD_THOR_WORKER_ACQUIRE_TEST=1"), emptyList()))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# Opt-in producer acquire fences for Steam
|
||||
|
||||
[Thor investigation and captured benchmark](https://github.com/Droid-Deck/DroidDeck/pull/3636).
|
||||
|
||||
The existing copy path is the default. In Steam display settings, **Direct game frames (experimental)** is a separate opt-in, applied at the next session. It requires zero-copy presentation, an eligible Adreno/native-worker Steam session, and a signed APK containing a capable Gamescope asset. The next normal session without the option, or a session with custom or Agent launch environment overrides, sees no private host global. Non-compatible clients and older components keep their current path. This is not a trust boundary against arbitrary code already executing as the Android app UID.
|
||||
|
||||
## Source and lifetime
|
||||
|
||||
- APK preparation verifies the Gamescope archive digest. At run time, the app compares the staged executable against the signed APK copy. It also checks the staged session script. No Agent executable, user environment, debug property, or test key can arm the host. Only a launch of the exact staged Gamescope path can qualify.
|
||||
- One app-owned session prepares a short-lived worker ticket. Only the matching Steam backend launch can consume it. The dedicated, app-bound non-exported Worker reports its own PID/start time through the existing local Binder exchange, not into a guest message. The broker uses a live pidfd, a matching start time, and an exact executable mapping after exec. If Android hides the pre-exec stat entry, the Worker receipt is provisional only until the same timestamp is observable after exec. A malformed or wrong timestamp, wrong executable, stale worker, or no pidfd denies the private global. The bound grant remains scoped to that worker and is revoked on stop or worker exit.
|
||||
- Gamescope only offers v1 to nested clients after negotiating v1 with that authenticated host. Mesa must export a real native sync_file for that particular attachment. Gamescope ties it to the exact submitted buffer/commit, waits on its duplicate normally, and forwards only a successful, signaled fence for unchanged source content. It cannot use a source fence as proof for composited output. The host consumes only a matching attachment's genuine successful fence and retains existing release and copy behavior. No fence, failed export, unsupported buffer, missing global, or X11-only path is not a license to scan out unsynchronized content.
|
||||
|
||||
## Validation and rollout gates
|
||||
|
||||
The historical controlled build on Thor used the same APK/components in both arms, the same Bright Family House camera with 120/no VSync and Steam limiter off at 60 Hz. Independent Android actual-presentation timestamps measured **21.08 FPS OFF → 37.42 FPS ON**. The compositor separately submitted 42.5–42.6 FPS on the direct path. This validates the technical approach, not the final candidate or physical panel behavior.
|
||||
|
||||
Before default changes or release: after testing the exact signed candidate with the intended Gamescope and Turnip binaries, record OFF/ON same-scene timestamps and direct/layer/full/verified-acquire counters; old producer/host, malformed/missing proof, X11/FIFO and unsupported import should use safe fallback. Exercise cap changes, pause/resume, Home→return, and a cold restart to verify no stale fence/buffer/cap state. Test boot with the option off. Use an external camera on the actual panel for tearing/corruption; Android captures cannot settle it. Keep the feature off by default and hold rollout if these checks do not pass.
|
||||
|
||||
A new immutable Gamescope component and a compatible DD-Turnip build are required for the effective path. The current old component does not advertise the signed capability marker. This PR need not publish or replace any existing component release.
|
||||
@@ -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.
|
||||
@@ -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"
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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, ¬_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)
|
||||
@@ -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"})
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user