This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-13 21:27:42 -04:00
1 parent 5fd47421f9
commit aecd2ebe1d
852 files changed
+4844 -46144

No files matched your search

+12 -108
View File
@@ -1,33 +1,4 @@
#define _GNU_SOURCE
/*
* VK_LAYER_DROIDDECK_vr: lets SteamVR's vrcompositor create its Vulkan instance on Turnip/KGSL.
*
* vrcompositor always asks for VK_KHR_display and the direct-mode extensions around it (it opens a
* direct mode window even when a driver-direct-mode driver - tools/vr/src/driver_droiddeck.cpp -
* will receive the frames). Turnip's KGSL backend has no displays and refuses to enumerate any GPU
* on an instance with VK_KHR_display enabled. This layer takes those extensions out of the instance
* it creates below itself and answers the display queries on its own: there are no displays.
*
* Shared semaphores: SteamVR shares a timeline semaphore with every image it shares between its
* processes, exported as an opaque fd. Turnip/KGSL cannot export one. Such a semaphore is created
* unshared here instead, its "fd" is a placeholder (a memfd named droiddeck-detached-sem), and a
* process importing a placeholder keeps a detached semaphore whose GPU waits are dropped and whose
* host waits return at once. Each process still orders its own work; what is lost is only the GPU
* ordering between processes, which SteamVR's own IPC (one frame at a time) mostly covers.
*
* Where it runs: droiddeck-steamvr enables it explicitly in SteamVR's own processes (VK_INSTANCE_LAYERS
* + VK_LAYER_PATH). It is also an implicit layer for the whole session, because processes SteamVR did
* not start share textures with it too: Steam's web helper draws its in-VR overlay through SteamVR,
* needs the exportable semaphores, and without them crashes until Steam quits. As an implicit layer
* it stays out of the way:
* - the display stand-in (taking display extensions off, the fake display) happens only while
* SteamVR runs (droiddeck-steamvr's marker file) or where the layer was enabled by name, never in
* an ordinary session: gamescope and games see the driver's extensions unchanged;
* - the semaphore bridge is active in those same processes, and in Steam's web helper once SteamVR
* is installed (its GPU process outlives SteamVR runs);
* - everything else - every process of a session without SteamVR installed - gets the next layer's
* functions untouched.
*/
#include <vulkan/vulkan.h>
#include <vulkan/vk_layer.h>
@@ -51,10 +22,7 @@ static void say(const char *fmt, const char *arg) {
fputc('\n', stderr);
}
/* ------------------------------------------------------------------ crash trace (debug) */
/* DROIDDECK_VR_CRASHTRACE=1: print a backtrace on a fatal signal. vrcompositor's launcher drops
* LD_PRELOAD, but this layer is loaded into it, so this is the way to see where it dies. */
#include <dlfcn.h>
#include <execinfo.h>
#include <signal.h>
@@ -86,7 +54,6 @@ static void crash_trace_install(void) {
static int done;
if (done++) return;
if (!getenv("DROIDDECK_VR_CRASHTRACE")) {
/* Or a marker beside droiddeck-steamvr's, for processes whose environment is not ours (Steam). */
const char *rt = getenv("XDG_RUNTIME_DIR");
char path[512];
snprintf(path, sizeof(path), "%s/droiddeck-steamvr/crashtrace", rt && *rt ? rt : "/run/droiddeck");
@@ -100,33 +67,28 @@ static void crash_trace_install(void) {
sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
int sigs[] = {SIGSEGV, SIGABRT, SIGBUS, SIGILL, SIGFPE};
for (unsigned i = 0; i < sizeof(sigs) / sizeof(*sigs); i++) {
/* Only where nothing handles the signal yet: Wine and FEX (Proton games) take SIGSEGV as part
* of their normal work, and replacing their handler crashes the game. */
struct sigaction old;
if (sigaction(sigs[i], NULL, &old) == 0 && !(old.sa_flags & SA_SIGINFO) && old.sa_handler == SIG_DFL)
sigaction(sigs[i], &sa, NULL);
}
}
/* ------------------------------------------------------------------ dispatch */
struct inst {
VkInstance handle;
PFN_vkGetInstanceProcAddr gipa;
PFN_vkDestroyInstance destroy;
int stripped; /* the app asked for display extensions we took out */
int active; /* see the top of the file */
int stripped;
int active;
};
struct dev {
VkDevice handle;
PFN_vkGetDeviceProcAddr gdpa;
PFN_vkDestroyDevice destroy;
int active;
int display; /* its instance has the pretend display */
int display;
};
/* SteamVR is running (droiddeck-steamvr start/stop keeps this file), or the layer was asked for by
* name. Only then does the layer stand in for a display. */
static int steamvr_running(void) {
const char *layers = getenv("VK_INSTANCE_LAYERS");
if (layers && strstr(layers, "VK_LAYER_DROIDDECK_vr")) return 1;
@@ -137,10 +99,6 @@ static int steamvr_running(void) {
return access(path, F_OK) == 0;
}
/* Whether an instance gets the semaphore bridge. Steam's web helper shares its in-VR overlays with
* SteamVR, and its GPU process lives across SteamVR runs: one created before SteamVR started crashes
* once SteamVR shows the overlay, and after a few of those Steam quits. So it is bridged whenever
* SteamVR is installed, not only while it runs. */
static int bridge_wanted(void) {
if (steamvr_running()) return 1;
if (strcmp(program_invocation_short_name, "steamwebhelper")) return 0;
@@ -155,7 +113,6 @@ static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
static struct inst g_inst[MAX_OBJS];
static struct dev g_dev[MAX_OBJS];
/* The dispatch key: the loader's dispatch table pointer at the start of every dispatchable object. */
static void *key(const void *obj) { return *(void **)obj; }
static struct inst *inst_for(const void *obj) {
@@ -178,7 +135,6 @@ static struct dev *dev_for(const void *obj) {
#define NEXT(dev, fn) ((PFN_vk##fn)dev_for(dev)->gdpa(dev, "vk" #fn))
#define HOOK_AS(str, fn) if (!strcmp(name, str)) return (PFN_vkVoidFunction)fn;
/* Extensions this layer takes off the instance and stands in for. */
static const char *const DISPLAY_EXTS[] = {
"VK_KHR_display", "VK_EXT_direct_mode_display", "VK_EXT_display_surface_counter",
"VK_KHR_get_display_properties2", "VK_EXT_acquire_xlib_display", "VK_EXT_acquire_drm_display",
@@ -189,7 +145,6 @@ static int is_display_ext(const char *name) {
return 0;
}
/* ------------------------------------------------------------------ instance */
static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const VkAllocationCallbacks *alloc,
VkInstance *out) {
@@ -203,7 +158,6 @@ static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const
PFN_vkCreateInstance next_create = (PFN_vkCreateInstance)next_gipa(VK_NULL_HANDLE, "vkCreateInstance");
if (!next_create) return VK_ERROR_INITIALIZATION_FAILED;
/* Outside SteamVR the instance is created exactly as asked: display extensions stay on. */
const int vr = steamvr_running();
VkInstanceCreateInfo mine = *ci;
const char **names = calloc(ci->enabledExtensionCount + 1, sizeof(*names));
@@ -216,7 +170,6 @@ static VkResult VKAPI_CALL CreateInstance(const VkInstanceCreateInfo *ci, const
if (stripped) {
int have = 0;
for (uint32_t i = 0; i < n; i++) have |= !strcmp(names[i], "VK_EXT_headless_surface");
/* The pretend display's surface is a headless one; it needs VK_KHR_surface too. */
const char *more[] = {"VK_EXT_headless_surface", "VK_KHR_surface"};
names = realloc(names, (n + 3) * sizeof(*names));
if (!have) names[n++] = more[0];
@@ -253,7 +206,6 @@ static void VKAPI_CALL DestroyInstance(VkInstance instance, const VkAllocationCa
if (d) d(instance, alloc);
}
/* ------------------------------------------------------------------ device */
static VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice pd, const VkDeviceCreateInfo *ci,
const VkAllocationCallbacks *alloc, VkDevice *out) {
@@ -270,7 +222,6 @@ static VkResult VKAPI_CALL CreateDevice(VkPhysicalDevice pd, const VkDeviceCreat
const int active = in && in->active;
const int display = in && in->stripped;
/* VK_EXT_display_control (vblank events on a display) goes too: there is no display. */
VkDeviceCreateInfo mine = *ci;
const char **names = calloc(ci->enabledExtensionCount + 1, sizeof(*names));
uint32_t n = 0;
@@ -307,13 +258,6 @@ static void VKAPI_CALL DestroyDevice(VkDevice device, const VkAllocationCallback
if (f) f(device, alloc);
}
/* ------------------------------------------------------------------ the display stand-in
*
* One pretend display with one mode and one plane. vrcompositor keeps a direct mode window on it even
* when a driver-direct driver takes the frames, and waits on that window's presents, so the display
* needs a working swapchain: its surface is a headless one (VK_EXT_headless_surface, Mesa's WSI).
* The vblank side of VK_EXT_display_control is a 60 Hz clock. Size and rate:
* DROIDDECK_VR_DISPLAY_MODE=WIDTHxHEIGHT@HZ (default 1920x1080@60). */
#include <time.h>
@@ -452,8 +396,6 @@ static VkResult VKAPI_CALL GetRandROutputDisplayEXT(VkPhysicalDevice pd, void *d
*d = FAKE_DISPLAY; return VK_SUCCESS;
}
/* VK_EXT_display_control on the device: a 60 Hz clock. A vblank event's fence comes back signalled
* once the next tick has passed (the caller's vblank thread waits right after registering). */
static VkResult VKAPI_CALL DisplayPowerControlEXT(VkDevice d, VkDisplayKHR disp, const VkDisplayPowerInfoEXT *info) { return VK_SUCCESS; }
static VkResult signalled_fence(VkDevice d, const VkAllocationCallbacks *a, VkFence *fence) {
VkFenceCreateInfo fci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, NULL, VK_FENCE_CREATE_SIGNALED_BIT};
@@ -477,14 +419,10 @@ static VkResult VKAPI_CALL GetSwapchainCounterEXT(VkDevice d, VkSwapchainKHR sc,
return VK_SUCCESS;
}
/* The pretend display's swapchain, on the headless surface: no swapchain counter (that belongs to
* VK_EXT_display_control, which the device does not have), and a request the headless WSI accepts. */
static VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice d, const VkSwapchainCreateInfoKHR *ci, const VkAllocationCallbacks *a,
VkSwapchainKHR *out) {
PFN_vkCreateSwapchainKHR next = NEXT(d, CreateSwapchainKHR);
VkSwapchainCreateInfoKHR sized = *ci;
/* A headless surface has no size of its own (UINT32_MAX), and SteamVR passes that through: the
* pretend display's mode is the size. */
mode_init();
if (sized.imageExtent.width == UINT32_MAX || sized.imageExtent.height == UINT32_MAX)
sized.imageExtent = (VkExtent2D){g_mode_w, g_mode_h};
@@ -498,13 +436,12 @@ static VkResult VKAPI_CALL CreateSwapchainKHR(VkDevice d, const VkSwapchainCreat
for (const VkBaseInStructure *p = ci->pNext; p && n < (int)sizeof(line) - 16; p = p->pNext) n += snprintf(line + n, sizeof(line) - n, " %d", p->sType);
say("vkCreateSwapchainKHR refused (%s); retrying for the headless surface", line);
VkSwapchainCreateInfoKHR mine = *ci;
mine.pNext = NULL; /* drops VkSwapchainCounterCreateInfoEXT and friends */
mine.pNext = NULL;
mine.presentMode = VK_PRESENT_MODE_FIFO_KHR;
mine.imageColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
if (mine.minImageCount < 2) mine.minImageCount = 2;
r = next(d, &mine, a, out);
if (r != VK_SUCCESS) {
/* Last resort: the plainest swapchain the surface can take. */
mine.imageFormat = VK_FORMAT_B8G8R8A8_UNORM;
mine.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
mine.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
@@ -524,16 +461,6 @@ static PFN_vkVoidFunction display_device_hook(const char *name) {
return NULL;
}
/* ------------------------------------------------------------------ bridged shared semaphores
*
* SteamVR shares a timeline semaphore with every image it shares between processes, exported as an
* opaque fd; Turnip/KGSL cannot export one. Here such a semaphore is created unshared, and its "fd" is
* a memfd (named droiddeck-shared-sem) holding a 64-bit counter. Every process that has the semaphore -
* the creator and each importer - keeps its own real timeline semaphore, and a poller thread in each
* process carries values both ways: a value reached locally goes up into the counter, a value the
* counter shows (another process got there) is signalled locally from the host. GPU waits then work
* as written, about a poll period late. A binary semaphore cannot be bridged that way; GPU waits on an
* imported binary one are dropped (each process still orders its own work). */
#include <sched.h>
#include <stdatomic.h>
@@ -547,14 +474,14 @@ struct bridged {
VkSemaphore sem;
VkDevice dev;
_Atomic uint64_t *counter;
int fd; /* the memfd, kept by the creator so every export can dup it; -1 for an importer */
int timeline; /* 0: binary, bridged only by dropping its waits */
unsigned long ino; /* the memfd's inode, which names the semaphore across processes in traces */
uint64_t submitted; /* the highest value this process has queued a signal of */
int fd;
int timeline;
unsigned long ino;
uint64_t submitted;
};
static pthread_mutex_t g_br_lock = PTHREAD_MUTEX_INITIALIZER;
static struct bridged g_br[MAX_SEMS];
static VkSemaphore g_timeline_sems[MAX_TYPED]; /* every timeline semaphore this process made */
static VkSemaphore g_timeline_sems[MAX_TYPED];
static pthread_t g_poller;
static int g_poller_started;
@@ -573,7 +500,6 @@ static void timeline_note(VkSemaphore s, int add) {
pthread_mutex_unlock(&g_br_lock);
}
/* Under g_br_lock. */
static struct bridged *bridged_find(VkSemaphore s) {
for (int i = 0; i < MAX_SEMS; i++) if (g_br[i].sem == s) return &g_br[i];
return NULL;
@@ -585,7 +511,6 @@ static void bridged_drop(struct bridged *b) {
b->fd = -1;
}
/* A `semtrace` file beside droiddeck-steamvr's marker: log every bridged semaphore every 2 s. */
static int sem_trace_on(void) {
static int checked, on;
if (!checked++) {
@@ -673,7 +598,6 @@ static VkResult VKAPI_CALL CreateSemaphore(VkDevice d, const VkSemaphoreCreateIn
return r;
}
if (!export_info) return r;
/* Rebuild the chain without the export request. */
VkSemaphoreTypeCreateInfo type = {0};
VkSemaphoreCreateInfo mine = *ci;
mine.pNext = NULL;
@@ -688,7 +612,7 @@ static VkResult VKAPI_CALL CreateSemaphore(VkDevice d, const VkSemaphoreCreateIn
int fd = memfd_create(SHARED_NAME, MFD_CLOEXEC);
_Atomic uint64_t *counter = NULL;
if (fd >= 0 && ftruncate(fd, 4096) == 0) counter = map_counter(fd);
if (!counter) { if (fd >= 0) close(fd); return r; } /* unshared, unbridged */
if (!counter) { if (fd >= 0) close(fd); return r; }
atomic_store(counter, timeline ? type_info->initialValue : 0);
pthread_mutex_lock(&g_br_lock);
struct bridged *slot = bridged_find(VK_NULL_HANDLE);
@@ -732,7 +656,7 @@ static VkResult VKAPI_CALL ImportSemaphoreFdKHR(VkDevice d, const VkImportSemaph
if (info->fd < 0 || !is_shared_counter(info->fd)) return NEXT(d, ImportSemaphoreFdKHR)(d, info);
_Atomic uint64_t *counter = map_counter(info->fd);
const unsigned long ino = fd_ino(info->fd);
close(info->fd); /* a successful import owns the fd */
close(info->fd);
const int timeline = timeline_known(info->semaphore);
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(info->semaphore);
@@ -748,7 +672,6 @@ static VkResult VKAPI_CALL ImportSemaphoreFdKHR(VkDevice d, const VkImportSemaph
return VK_SUCCESS;
}
/* An imported binary one: nothing here will ever signal it. */
static int drop_wait(VkSemaphore s) {
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(s);
@@ -763,17 +686,8 @@ static uint64_t now_us(void) {
return (uint64_t)ts.tv_sec * 1000000u + (uint64_t)ts.tv_nsec / 1000u;
}
/* How long a submit may wait for another process to reach a shared value before the wait is dropped. */
#define SUBMIT_GRACE_US 3000
/* Whether a submit should drop its GPU wait on s for value.
*
* Turnip on KGSL does not defer a submit that waits on a timeline value nobody has signalled yet ("wait
* before signal"): vkQueueSubmit blocks the calling thread until the value is signalled. SteamVR's
* client waits on a value of the compositor's that the compositor signals only after the client has
* submitted and told it so, which on Turnip deadlocks the client before its first frame (helloxr's
* acquire, DXVK's submit thread in Proton games). For an imported timeline semaphore whose value is
* neither reached nor queued here, the counter gets a short grace period, then the wait goes. */
static int submit_drop_wait(VkSemaphore s, uint64_t value) {
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(s);
@@ -787,7 +701,6 @@ static int submit_drop_wait(VkSemaphore s, uint64_t value) {
if (!imported || !value || value <= queued) return 0;
struct dev *d = dev_for(dev);
if (!d) return 0;
/* A Vulkan 1.0 device (SteamVR's client interop) has only the KHR names. */
PFN_vkGetSemaphoreCounterValue get = (PFN_vkGetSemaphoreCounterValue)d->gdpa(dev, "vkGetSemaphoreCounterValue");
if (!get) get = (PFN_vkGetSemaphoreCounterValue)d->gdpa(dev, "vkGetSemaphoreCounterValueKHR");
PFN_vkSignalSemaphore sig = (PFN_vkSignalSemaphore)d->gdpa(dev, "vkSignalSemaphore");
@@ -812,7 +725,6 @@ static int submit_drop_wait(VkSemaphore s, uint64_t value) {
return 1;
}
/* Notes the values this process queues signals of, so its own later waits on them are kept. */
static void note_signal(VkSemaphore s, uint64_t value) {
pthread_mutex_lock(&g_br_lock);
struct bridged *b = bridged_find(s);
@@ -836,7 +748,6 @@ static void note_submit2_signals(uint32_t count, const VkSubmitInfo2 *submits) {
note_signal(submits[i].pSignalSemaphoreInfos[j].semaphore, submits[i].pSignalSemaphoreInfos[j].value);
}
/* Drops waits on detached semaphores from a list; returns the new count. */
static uint32_t keep_waits(const VkSemaphore *in, const VkPipelineStageFlags *stages, const uint64_t *values, uint32_t n,
VkSemaphore *out, VkPipelineStageFlags *out_stages, uint64_t *out_values) {
uint32_t k = 0;
@@ -850,7 +761,6 @@ static uint32_t keep_waits(const VkSemaphore *in, const VkPipelineStageFlags *st
return k;
}
/* semtrace: the first wait and the first signal of each shared semaphore, and its first few values. */
static void trace_sem(const char *what, VkSemaphore sem, uint64_t value) {
if (!sem_trace_on() || value > 3) return;
pthread_mutex_lock(&g_br_lock);
@@ -876,8 +786,6 @@ static VkResult VKAPI_CALL QueueSubmit(VkQueue q, uint32_t count, const VkSubmit
for (uint32_t j = 0; j < submits[i].signalSemaphoreCount; j++)
trace_sem("signals", submits[i].pSignalSemaphores[j], t && j < t->signalSemaphoreValueCount ? t->pSignalSemaphoreValues[j] : 0);
}
/* Waits are judged before this submit's own signals count as queued: an acquire may wait on one
* value and signal the next on the same semaphore. */
int any = 0;
for (uint32_t i = 0; i < count && !any; i++) {
const VkTimelineSemaphoreSubmitInfo *t = NULL;
@@ -911,7 +819,6 @@ static VkResult VKAPI_CALL QueueSubmit(VkQueue q, uint32_t count, const VkSubmit
copy[i].pWaitSemaphores = sems;
copy[i].pWaitDstStageMask = stages;
if (t) {
/* Only this struct is replaced; the rest of the chain is kept behind it. */
tl[i] = *t;
tl[i].waitSemaphoreValueCount = t->waitSemaphoreValueCount ? k : 0;
tl[i].pWaitSemaphoreValues = vals;
@@ -920,7 +827,7 @@ static VkResult VKAPI_CALL QueueSubmit(VkQueue q, uint32_t count, const VkSubmit
for (const VkBaseInStructure *p = submits[i].pNext; p; prev = p, p = p->pNext) if (p == (const void *)t) { rest = p->pNext; break; }
(void)prev;
tl[i].pNext = rest;
copy[i].pNext = &tl[i]; /* other structs before it are dropped: SteamVR chains only this one */
copy[i].pNext = &tl[i];
}
}
VkResult r = next(q, count, copy, fence);
@@ -989,7 +896,6 @@ static VkResult VKAPI_CALL GetSemaphoreCounterValue(VkDevice d, VkSemaphore s, u
return next(d, s, value);
}
/* semtrace also logs how shared (external memory) images are created, to compare both sides. */
static VkResult VKAPI_CALL CreateImage(VkDevice d, const VkImageCreateInfo *ci, const VkAllocationCallbacks *a, VkImage *out) {
VkResult r = NEXT(d, CreateImage)(d, ci, a, out);
if (!sem_trace_on()) return r;
@@ -1026,7 +932,6 @@ static PFN_vkVoidFunction semaphore_hook(const char *name) {
return NULL;
}
/* ------------------------------------------------------------------ proc addr */
#define HOOK(fn) if (!strcmp(name, "vk" #fn)) return (PFN_vkVoidFunction)fn;
@@ -1085,7 +990,6 @@ EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL DroidDeckVr_GetDeviceProcAddr(Vk
if (f) return f;
}
if (d) {
/* Only where the driver has the function: the hooks call through to it. */
PFN_vkVoidFunction mine = semaphore_hook(name);
if (mine && d->gdpa(device, name)) return mine;
}