Compare commits

..
14 changed files with 582 additions and 328 deletions

No files matched your search

+42
View File
@@ -1,9 +1,13 @@
#include <errno.h>
#include <fcntl.h>
#include <jni.h>
#include <limits.h>
#include <linux/futex.h>
#include <stdatomic.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
@@ -27,3 +31,41 @@ Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass cla
(void)clazz;
return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno;
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(JNIEnv *env, jclass clazz, jstring path) {
(void)clazz;
const char *chars = (*env)->GetStringUTFChars(env, path, NULL);
if (!chars) return ENOMEM;
char *copy = strdup(chars);
(*env)->ReleaseStringUTFChars(env, path, chars);
if (!copy) return ENOMEM;
int rc = EINVAL;
int fd = -1;
if (copy[0] != '/') goto done;
fd = open("/", O_RDONLY | O_CLOEXEC | O_DIRECTORY);
if (fd < 0) { rc = errno; goto done; }
char *part = copy + 1;
while (*part) {
char *slash = strchr(part, '/');
if (slash) *slash = '\0';
if (!*part || !strcmp(part, ".") || !strcmp(part, "..")) goto done;
int next = openat(fd, part, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK |
(slash ? O_DIRECTORY : 0));
if (next < 0) { rc = errno; goto done; }
close(fd);
fd = next;
if (!slash) {
struct stat st;
if (fstat(fd, &st) < 0) { rc = errno; goto done; }
if (!S_ISREG(st.st_mode) || st.st_size < (8LL << 20)) goto done;
rc = posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
break;
}
part = slash + 1;
}
done:
free(copy);
if (fd >= 0) close(fd);
return rc;
}
@@ -2844,10 +2844,9 @@ static void render_scene(void) {
else if (rendered && how == 2) droiddeck_color_frame_shown(hs.color, DROIDDECK_HDR_TONEMAPPED, 0);
else if (rendered) hdr_copy = "the HDR composition pass is unavailable on this driver";
}
if (hdr_route == 0 && vkp_quest_layer_presentation() && !cardboard && !cursor_on &&
if (hdr_route == 0 && vkp_quest_layer_presentation() && !framegen && !cardboard && !cursor_on &&
!ahb_only) {
settle_unwaited();
g_framegen_layer = framegen;
rendered = vkp_render(w, h, dl.d, dl.n) == 0;
} else if (hdr_route == 0 || hdr_route == 3) {
const int pass_on = fx_on || framegen;
+2 -11
View File
@@ -3013,24 +3013,15 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
}
int vkp_render(int scene_w, int scene_h, const struct vkp_draw *draws, int n) {
if (vkp_quest_layer_presentation() && !vkp_cardboard_active()) {
if (vkp_quest_layer_presentation() && !vkp_framegen_active() && !vkp_cardboard_active()) {
vkp_apply_window_request();
sc_layer_hide_overlay();
if (n > 0) {
const int fg = vkp_framegen_active();
const int generated = fg
? sc_layer_present_generated(draws, n, NULL, scene_w, scene_h, 1, NULL) : 0;
const int r = fg ? (generated >= 0 ? 0 : -1)
: sc_layer_present_pass(draws, n, scene_w, scene_h);
if (r != 0) {
if (sc_layer_present_pass(draws, n, scene_w, scene_h) != 0) {
static int said;
if (!said) { said = 1; droiddeck_log("error", "Quest scene layer unavailable; retaining the previous frame rather than using the corrupt Android swapchain"); }
return -1;
}
if (fg && generated > 0) {
static int said;
if (!said) { said = 1; droiddeck_log("framegen", "generated frames go on the Quest display layer"); }
}
} else {
sc_layer_hide();
}
@@ -0,0 +1,126 @@
package com.droiddeck.launcher.session
import android.util.Log
import java.io.File
import java.nio.file.Files
internal object PageCacheTrim {
private const val TAG = "PageCacheTrim"
private const val MIN_FILE_BYTES = 8L shl 20
private const val POLL_MS = 3000L
private const val RESCAN_MS = 120_000L
private const val MIN_TRIM_MS = 30_000L
data class Mem(val freeKb: Long, val fileKb: Long)
data class Trim(val before: Mem, val after: Mem?, val files: Int, val failed: Int, val ms: Long)
fun parse(meminfo: String): Mem? {
fun field(name: String): Long? =
Regex("""(?m)^${Regex.escape(name)}:\s+(\d+) kB""").find(meminfo)?.groupValues?.get(1)?.toLongOrNull()
val free = field("MemFree") ?: return null
val file = field("Active(file)") ?: return null
val inactive = field("Inactive(file)") ?: return null
return Mem(free, file + inactive)
}
fun shouldTrim(mem: Mem, baselineFileKb: Long): Boolean {
val built = mem.fileKb - baselineFileKb
if (built <= 0) return false
return (mem.freeKb < 2560 * 1024 && built >= 768 * 1024) ||
(mem.freeKb < 1024 * 1024 && built >= 128 * 1024)
}
fun describe(trim: Trim): String {
val after = trim.after
return "trim: free ${trim.before.freeKb / 1024} -> ${after?.freeKb?.div(1024)} MB, " +
"file cache ${trim.before.fileKb / 1024} -> ${after?.fileKb?.div(1024)} MB, " +
"${trim.files} file(s), ${trim.failed} failed, ${trim.ms} ms"
}
internal class Worker(
private val roots: () -> List<File>,
private val alive: () -> Boolean,
private val readMem: () -> Mem?,
private val clock: () -> Long,
private val advise: (String) -> Int,
private val report: (String) -> Unit,
) {
private var baseline: Long? = null
private var files = emptyList<File>()
private var scanned: Long? = null
private var trimmed: Long? = null
fun poll() {
if (!alive()) return
val before = readMem() ?: return
val base = baseline
if (base == null) {
baseline = before.fileKb
return
}
val now = clock()
if (!shouldTrim(before, base) || trimmed?.let { now - it < MIN_TRIM_MS } == true) return
val began = now
if (scanned?.let { now - it >= RESCAN_MS } != false) {
val found = mutableListOf<File>()
for (root in roots()) {
if (!alive()) return
if (Files.isSymbolicLink(root.toPath())) continue
val directory = root.canonicalFile
for (file in directory.walkTopDown().onEnter {
alive() && !Files.isSymbolicLink(it.toPath())
}) {
if (!alive()) return
if (!Files.isSymbolicLink(file.toPath()) && file.isFile && file.length() >= MIN_FILE_BYTES) {
found.add(file)
}
}
}
files = found.distinctBy { it.path }
scanned = clock()
}
var failed = 0
for (file in files) {
if (!alive()) return
if (advise(file.path) != 0) failed++
}
if (!alive()) return
val after = readMem()
if (!alive()) return
baseline = after?.fileKb ?: before.fileKb
val completed = clock()
trimmed = completed
report(describe(Trim(before, after, files.size, failed, completed - began)))
}
}
fun start(roots: () -> List<File>, alive: () -> Boolean, report: (String) -> Unit = {}) {
Thread({
val worker = Worker(
roots, alive,
{ parse(File("/proc/meminfo").readText()) },
{ System.nanoTime() / 1_000_000 },
PageCacheNative::fadviseDontNeed,
{ message -> Log.i(TAG, message); report(message) },
)
var failureLogged = false
while (alive()) {
runCatching { worker.poll() }.onFailure {
if (!failureLogged) Log.w(TAG, "file cache trim failed: $it")
failureLogged = true
}
if (!alive()) break
Thread.sleep(POLL_MS)
}
}, "page-cache-trim").apply { isDaemon = true }.start()
}
}
internal object PageCacheNative {
init {
System.loadLibrary("sdnative")
}
@JvmStatic external fun fadviseDontNeed(path: String): Int
}
@@ -430,6 +430,12 @@ class SessionService : Service() {
stopSession(0)
return START_NOT_STICKY
}
val trimGen = gen
PageCacheTrim.start(
roots = { listOfNotNull(File(filesDir, "linuxfs"), GameStorage.effective(applicationContext)?.let { File(it.path) }) },
alive = { SessionState.running && sessionGen == trimGen },
report = { message -> SessionEvents.record("session.page_cache_trim", mapOf("detail" to message)) },
)
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) RivalClients.stopBeforeSession(this)
SessionState.firstFrameSeen = false
SessionState.guestPid = -1
@@ -0,0 +1,199 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import java.io.File
import java.io.RandomAccessFile
import java.nio.file.Files
class PageCacheTrimTest {
private val meminfo = "MemFree: 1048576 kB\nActive(file): 2097152 kB\nInactive(file): 1048576 kB\n"
private fun mem(freeMb: Long, fileMb: Long) = PageCacheTrim.Mem(freeMb * 1024, fileMb * 1024)
@Test fun parsesFreeAndFileLru() = assertEquals(PageCacheTrim.Mem(1048576, 3145728), PageCacheTrim.parse(meminfo))
@Test fun rejectsMissingFields() {
assertNull(PageCacheTrim.parse("MemFree: 1 kB\n"))
assertNull(PageCacheTrim.parse("MemFree: 1 kB\nActive(file): 2 kB\n"))
}
@Test fun trimsWhenCacheBuiltUpAndFreeIsLow() = assertTrue(PageCacheTrim.shouldTrim(mem(2000, 2000), 1000 * 1024))
@Test fun skipsSmallBuildUp() = assertFalse(PageCacheTrim.shouldTrim(mem(2000, 1200), 1000 * 1024))
@Test fun skipsWhenPlentyFree() = assertFalse(PageCacheTrim.shouldTrim(mem(6000, 5000), 1000 * 1024))
@Test fun lowFreeAcceptsSmallerBuildUp() = assertTrue(PageCacheTrim.shouldTrim(mem(500, 1200), 1000 * 1024))
@Test fun noNewFileCacheNeedsNoTrim() = assertFalse(PageCacheTrim.shouldTrim(mem(500, 900), 1000 * 1024))
@Test fun describesWhatWasDropped() = assertEquals(
"trim: free 2000 -> 2600 MB, file cache 2000 -> 1400 MB, 4 file(s), 1 failed, 12 ms",
PageCacheTrim.describe(PageCacheTrim.Trim(mem(2000, 2000), mem(2600, 1400), 4, 1, 12)),
)
@get:Rule val temporary = TemporaryFolder()
private class Harness(val root: File) {
var current = PageCacheTrim.Mem(500 * 1024, 1024 * 1024)
var now = 0L
var active = true
var reads = 0
val advised = mutableListOf<String>()
val reports = mutableListOf<String>()
var onAdvice: () -> Unit = {}
val worker = PageCacheTrim.Worker(
{ listOf(root) }, { active }, { reads++; current }, { now },
{ advised.add(it); onAdvice(); 0 }, { reports.add(it) },
)
fun grow() { current = current.copy(fileKb = current.fileKb + 128 * 1024) }
}
private fun large(root: File, name: String): File = File(root, name).also {
RandomAccessFile(it, "rw").use { handle -> handle.setLength(8L shl 20) }
}
@Test fun startupAndInvalidSamplesDoNotDiscardWarmCache() {
val root = temporary.newFolder()
large(root, "data")
val h = Harness(root)
h.worker.poll()
h.worker.poll()
assertTrue(h.advised.isEmpty())
h.grow()
h.worker.poll()
assertEquals(1, h.advised.size)
var sample: PageCacheTrim.Mem? = null
val worker = PageCacheTrim.Worker({ error("unexpected scan") }, { true }, { sample }, { 0L },
{ error("unexpected advice") }, { error("unexpected report") })
worker.poll()
sample = mem(500, 4096)
worker.poll()
worker.poll()
}
@Test fun cancellationStopsAdviceAndReportingAndRestartGetsFreshBaseline() {
val root = temporary.newFolder()
large(root, "a")
large(root, "b")
val h = Harness(root)
h.worker.poll()
h.grow()
h.onAdvice = { h.active = false }
h.worker.poll()
assertEquals(1, h.advised.size)
assertTrue(h.reports.isEmpty())
val replacement = Harness(root)
replacement.current = h.current
replacement.worker.poll()
assertTrue(replacement.advised.isEmpty())
h.worker.poll()
assertEquals(1, h.advised.size)
}
@Test fun cancellationDuringRootSelectionStopsTraversal() {
val root = temporary.newFolder()
large(root, "a")
var active = true
var sample = mem(500, 1024)
val worker = PageCacheTrim.Worker({ active = false; listOf(root) }, { active },
{ sample }, { 0L }, { error("cancelled advice") }, { error("cancelled report") })
worker.poll()
sample = mem(500, 2048)
worker.poll()
}
@Test fun cooldownStartsAtCompletionAndRescansAreBounded() {
val root = temporary.newFolder()
large(root, "a")
val h = Harness(root)
h.worker.poll()
h.grow()
h.onAdvice = { h.now += 40_000 }
h.worker.poll()
large(root, "b")
h.grow()
h.now += 29_999
h.worker.poll()
assertEquals(1, h.advised.size)
h.now++
h.onAdvice = {}
h.worker.poll()
assertEquals(2, h.advised.size)
h.now = 120_000
h.grow()
h.worker.poll()
assertEquals(4, h.advised.size)
}
@Test fun excludesSmallFilesAndLinksAndOtherStorage() {
val root = temporary.newFolder()
val outside = temporary.newFolder()
val allowed = large(root, "payload")
val other = large(outside, "payload")
File(root, "small").writeText("small")
Files.createSymbolicLink(File(root, "link").toPath(), other.toPath())
Files.createSymbolicLink(File(root, "directory").toPath(), outside.toPath())
val h = Harness(root)
h.worker.poll()
h.grow()
h.worker.poll()
assertEquals(listOf(allowed.canonicalPath), h.advised)
assertTrue(other.exists())
assertEquals("small", File(root, "small").readText())
}
@Test fun highFreeMemoryDoesNotTouchAnyProgramFiles() {
val root = temporary.newFolder()
large(root, "program-one")
large(root, "program-two")
val h = Harness(root)
h.current = mem(6000, 1024)
h.worker.poll()
h.current = mem(6000, 8192)
h.worker.poll()
assertTrue(h.advised.isEmpty())
assertTrue(h.reports.isEmpty())
}
@Test fun emptyScansAreThrottledAndEventuallyDiscoverNewFiles() {
val root = temporary.newFolder()
val h = Harness(root)
h.worker.poll()
h.grow()
h.worker.poll()
assertEquals(1, h.reports.size)
large(root, "new")
h.now = 30_000
h.grow()
h.worker.poll()
assertTrue(h.advised.isEmpty())
h.now = 120_000
h.grow()
h.worker.poll()
assertEquals(1, h.advised.size)
}
@Test fun cancellationDuringFinalSampleSuppressesReporting() {
val root = temporary.newFolder()
large(root, "a")
var active = true
var reads = 0
var advised = 0
val worker = PageCacheTrim.Worker({ listOf(root) }, { active }, {
reads++
if (reads == 3) active = false
mem(500, if (reads == 1) 1024 else 2048)
}, { 0L }, { advised++; 0 }, { error("cancelled report") })
worker.poll()
worker.poll()
assertEquals(1, advised)
assertFalse(active)
}
}
+21
View File
@@ -85,6 +85,27 @@ session log says so once a minute.
With no shortage nothing is compressed. A game that fits in memory is never touched, and Steam
is no longer compressed on a timer.
## File page cache
The session worker samples `MemFree` and `Active(file)` plus `Inactive(file)` every three
seconds. Its first valid sample establishes the growth baseline without discarding startup cache.
When `MemFree` is under 2.5 GiB with 768 MiB of file-LRU growth, or under 1 GiB with 128 MiB of
growth, it requests `posix_fadvise(DONTNEED)` on regular files of at least 8 MiB under the Linux
root and selected game storage. This mechanism originated in Kurt Himebauch's PR #3439; #3465
hardens the same worker and native bridge rather than introducing another reclaim path.
Scans are at least two minutes apart, including empty scans. Passes are at least 30 seconds
apart measured from completion, using a monotonic clock. Traversal and advice stop when session
ownership is lost. Native opens reject symbolic links in every component, use nonblocking mode,
and validate the opened descriptor's file type and size. Each completed pass is logged to the
session log and `events.jsonl`.
Advice is a best-effort request, not evidence that memory was freed or that a low-memory kill
was prevented. It can cause later disk reads. File cache is shared by inode, so another reader of
the same eligible file may also need to reread it. Files outside the selected roots, mapped pages,
anonymous memory, GPU allocations and explicit user settings are not targeted. Reporter testing
is still required to establish whether this prevents the base Thor's idle-session termination.
## Reading the client back
Once the client has been compressed, it is read back in one request when the game has exited,
+60 -59
View File
@@ -6,7 +6,6 @@
#include <dlfcn.h>
#include <errno.h>
#include <limits.h>
#include <link.h>
#include <linux/input.h>
#include <pthread.h>
#include <stdatomic.h>
@@ -16,7 +15,6 @@
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include <unistd.h>
@@ -36,8 +34,7 @@
"NAME=\"Xbox 360 Controller (%d)\"\n" \
"PHYS=\"usb-fakeinput/input%d\"\n"
#define STEAM_VIRTUAL_VENDOR 0x28de
#define STEAM_VIRTUAL_PRODUCT 0x11ff
#define RING_SDL_ID 0x045e028eu
#define PARENT_NAME "droiddeck-input"
#define PARENT_SYSPATH_FORMAT "/sys/devices/droiddeck%d/" PARENT_NAME "%d"
@@ -144,8 +141,66 @@ static int any_virtual_pad(void) {
return 0;
}
static char *sdl_id_list_text(const char *list) {
char *text = NULL;
char *grown;
size_t length = 0;
size_t got;
FILE *file;
if (list[0] != '@') return strdup(list);
file = fopen(list + 1, "re");
if (file == NULL) return NULL;
do {
grown = realloc(text, length + 4097);
if (grown == NULL) {
free(text);
fclose(file);
return NULL;
}
text = grown;
got = fread(text + length, 1, 4096, file);
length += got;
} while (got > 0);
fclose(file);
text[length] = '\0';
return text;
}
static int sdl_id_list_entries(const char *list, int *has_ring) {
char *text = sdl_id_list_text(list);
char *spot = text;
uint32_t entry;
int entries = 0;
*has_ring = 0;
if (text == NULL) return 0;
while ((spot = strstr(spot, "0x")) != NULL) {
entry = (uint32_t)(uint16_t)strtol(spot, &spot, 0) << 16;
spot = strstr(spot, "0x");
if (spot == NULL) break;
entry |= (uint16_t)strtol(spot, &spot, 0);
entries++;
if (entry == RING_SDL_ID) *has_ring = 1;
}
free(text);
return entries;
}
static int sdl_bus_skips_ring_pad(void) {
const char *steam_virtual = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
const char *except = getenv("SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT");
const char *ignore = getenv("SDL_GAMECONTROLLER_IGNORE_DEVICES");
int has_ring;
if (steam_virtual != NULL && atoi(steam_virtual) != 0) return 1;
if (except != NULL && sdl_id_list_entries(except, &has_ring) > 0) return !has_ring;
return ignore != NULL && sdl_id_list_entries(ignore, &has_ring) > 0 && has_ring;
}
static const char *ring_uevent_format(void) {
return uinput_enabled() && any_virtual_pad() ? PAD_PHYSICAL_UEVENT_FORMAT : PAD_UEVENT_FORMAT;
if (uinput_enabled() && any_virtual_pad()) return PAD_PHYSICAL_UEVENT_FORMAT;
return sdl_bus_skips_ring_pad() ? PAD_UEVENT_FORMAT : PAD_PHYSICAL_UEVENT_FORMAT;
}
static void refresh_locked(int node) {
@@ -459,60 +514,6 @@ static int caller_in_library(void *caller, const char *library) {
static int caller_is_winebus(void *caller) { return caller_in_library(caller, "winebus.so"); }
static int note_winebus(struct dl_phdr_info *info, size_t size, void *data) {
(void)size;
if (info->dlpi_name == NULL || strstr(info->dlpi_name, "winebus.so") == NULL) return 0;
*(int *)data = 1;
return 1;
}
static int winebus_reads_udev(void) {
const char *x360 = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
int loaded = 0;
if (x360 != NULL && atoi(x360) != 0) return 0;
dl_iterate_phdr(note_winebus, &loaded);
return loaded;
}
static int ring_pad_fd(int fd) {
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
const char *entry;
struct stat opened;
struct stat ring;
char path[PATH_MAX];
if (spec == NULL || fstat(fd, &opened) != 0) return 0;
for (entry = spec; *entry != '\0';) {
char *end;
long slot = strtol(entry, &end, 10);
const char *next = strchr(entry, ';');
size_t length;
if (end != entry && *end == '=' && slot >= 0 && slot < RING_MAX) {
length = next != NULL ? (size_t)(next - end - 1) : strlen(end + 1);
if (length < sizeof(path)) {
memcpy(path, end + 1, length);
path[length] = '\0';
if (stat(path, &ring) == 0 && ring.st_dev == opened.st_dev && ring.st_ino == opened.st_ino) return 1;
}
}
if (next == NULL) break;
entry = next + 1;
}
return 0;
}
__attribute__((visibility("hidden"))) void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg,
void *caller, int rc) {
struct input_id *id = arg;
if (rc != 0 || request != EVIOCGID || id == NULL) return;
if (!caller_in_library(caller, "libSDL") || !winebus_reads_udev() || !ring_pad_fd(fd)) return;
id->vendor = STEAM_VIRTUAL_VENDOR;
id->product = STEAM_VIRTUAL_PRODUCT;
}
typedef int (*sdl_rumble_fn)(void *, uint16_t, uint16_t, uint32_t);
static _Atomic(sdl_rumble_fn) real_sdl_rumble;
static __thread int winebus_sdl_call;
-3
View File
@@ -424,8 +424,6 @@ int dd_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute
int dd_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
void dd_ring_pad_sdl_id(int fd, unsigned long request, void *arg, void *caller, int rc)
__attribute__((visibility("hidden")));
int dd_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg,
int *rc) __attribute__((visibility("hidden")));
@@ -446,7 +444,6 @@ int ioctl(int fd, unsigned long request, ...) {
if (dd_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
if (dd_writewatch_ioctl(real, fd, request, arg, &rc)) return rc;
if (!dd_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg);
dd_ring_pad_sdl_id(fd, request, arg, __builtin_return_address(0), rc);
dd_kgsl_track(real, fd, request, arg, &rc);
dd_kgsl_chip_id_fixup(request, arg, rc);
if (arg == NULL || !is_link_query(request)) return rc;
+11 -101
View File
@@ -3,12 +3,8 @@
#include <stdio.h>
struct vkp_draw { int unused; };
struct vkp_hdr_frame;
struct droiddeck_color;
static int quest, framegen, cardboard, pass_result, gen_result, base_result, pass_shown, gen_shown;
static int first_frames, pass_calls, gen_calls, base_calls, fallback_calls;
static int settled, g_framegen_layer;
static void settle_unwaited(void) { settled++; }
static int quest, framegen, cardboard, pass_result, base_result, pass_shown;
static int first_frames, pass_calls, base_calls, fallback_calls;
static int vkp_quest_layer_presentation(void) { return quest; }
static int vkp_framegen_active(void) { return framegen; }
static int vkp_cardboard_active(void) { return cardboard; }
@@ -23,46 +19,26 @@ static int sc_layer_present_pass(const struct vkp_draw *draws, int n, int w, int
if (pass_result == 0 && pass_shown) vkp_signal_first_frame();
return pass_result;
}
static int sc_layer_present_generated(const struct vkp_draw *draws, int n_draws,
const struct vkp_hdr_frame *hf, int w, int h,
int composed, const struct droiddeck_color *color) {
(void)w; (void)h;
assert(composed == 1 && hf == NULL && color == NULL);
gen_calls++;
if (gen_result >= 0 && gen_shown) vkp_signal_first_frame();
return gen_result;
}
static int render_impl(int w, int h, const struct vkp_draw *draws, int n,
const void *hdr, int *how) { fallback_calls++; return 17; }
#include "vkp_render_under_test.inc"
static int compositor_route(int hdr_route, int cursor_on, int ahb_only,
const struct vkp_draw *draws) {
const int w = 1280, h = 720;
const struct { const struct vkp_draw *d; int n; } dl = {draws, 1};
int rendered = -2;
#include "quest_route_under_test.inc"
return rendered;
}
static void reset(void) {
quest = 1;
settled = 0;
g_framegen_layer = -1;
framegen = cardboard = pass_result = gen_result = base_result = pass_shown = gen_shown = 0;
first_frames = pass_calls = gen_calls = base_calls = fallback_calls = 0;
framegen = cardboard = pass_result = base_result = pass_shown = 0;
first_frames = pass_calls = base_calls = fallback_calls = 0;
}
int main(void) {
const struct vkp_draw draw = {0};
reset();
for (int i = 0; i < 3; i++) assert(vkp_render(1280, 720, NULL, 0) == 0);
assert(base_calls == 3 && pass_calls == 0 && gen_calls == 0 && first_frames == 0);
assert(base_calls == 3 && pass_calls == 0 && first_frames == 0);
reset();
assert(vkp_render(1280, 720, &draw, 1) == 0);
assert(pass_calls == 1 && gen_calls == 0 && base_calls == 1 && first_frames == 0);
assert(pass_calls == 1 && base_calls == 1 && first_frames == 0);
reset(); pass_shown = 1;
assert(vkp_render(1280, 720, &draw, 1) == 0);
@@ -77,81 +53,15 @@ int main(void) {
assert(vkp_render(1280, 720, NULL, 0) == -1);
assert(first_frames == 0);
for (int mode = 0; mode < 4; mode++) {
for (int mode = 0; mode < 3; mode++) {
reset();
if (mode == 0) quest = 0;
if (mode == 1) cardboard = 1;
if (mode == 2) { quest = 0; framegen = 1; }
if (mode == 3) { framegen = 1; cardboard = 1; }
if (mode == 1) framegen = 1;
if (mode == 2) cardboard = 1;
assert(vkp_render(1280, 720, &draw, 1) == 17);
assert(fallback_calls == 1 && pass_calls == 0 && gen_calls == 0 && base_calls == 0);
assert(fallback_calls == 1 && pass_calls == 0 && base_calls == 0);
assert(first_frames == 0);
}
reset(); framegen = 1;
assert(vkp_render(1280, 720, &draw, 1) == 0);
assert(gen_calls == 1 && pass_calls == 0 && fallback_calls == 0 && base_calls == 1);
reset(); framegen = 1; gen_result = -1;
assert(vkp_render(1280, 720, &draw, 1) == -1);
assert(gen_calls == 1 && fallback_calls == 0 && base_calls == 0 && first_frames == 0);
reset(); framegen = 1; gen_shown = 1;
assert(vkp_render(1280, 720, &draw, 1) == 0);
assert(first_frames == 1);
assert(vkp_render(1280, 720, NULL, 0) == 0);
assert(first_frames == 1);
reset(); framegen = 1;
assert(vkp_render(1280, 720, &draw, 1) == 0);
framegen = 0;
assert(vkp_render(1280, 720, &draw, 1) == 0);
assert(gen_calls == 1 && pass_calls == 1 && fallback_calls == 0 && first_frames == 0);
for (int count = 1; count <= 2; count++) {
for (int shown = 0; shown <= 1; shown++) {
reset(); framegen = 1; gen_result = count; gen_shown = shown;
assert(vkp_render(1280, 720, &draw, 1) == 0);
assert(gen_calls == 1 && pass_calls == 0 && fallback_calls == 0);
assert(base_calls == 1 && first_frames == shown);
assert(vkp_render(1280, 720, NULL, 0) == 0);
assert(gen_calls == 1 && base_calls == 2 && first_frames == shown);
}
reset(); framegen = 1; gen_result = count; gen_shown = 1; base_result = -1;
assert(vkp_render(1280, 720, &draw, 1) == -1);
assert(gen_calls == 1 && base_calls == 1 && first_frames == 1);
assert(pass_calls == 0 && fallback_calls == 0);
}
for (int route = 0; route <= 3; route++) {
for (int flags = 0; flags < 32; flags++) {
reset();
quest = flags & 1;
framegen = (flags >> 1) & 1;
cardboard = (flags >> 2) & 1;
const int cursor = (flags >> 3) & 1;
const int ahb = (flags >> 4) & 1;
const int selected = route == 0 && quest && !cardboard && !cursor && !ahb;
gen_result = 2; gen_shown = pass_shown = 1;
assert(compositor_route(route, cursor, ahb, &draw) == (selected ? 1 : -2));
assert(settled == selected && base_calls == selected);
assert(gen_calls == (selected && framegen));
assert(pass_calls == (selected && !framegen));
assert(first_frames == selected && fallback_calls == 0);
assert(g_framegen_layer == (selected ? framegen : -1));
assert(quest == (flags & 1));
assert(framegen == ((flags >> 1) & 1));
assert(cardboard == ((flags >> 2) & 1));
}
}
reset(); framegen = 1; gen_result = 2;
assert(compositor_route(0, 0, 0, &draw) == 1);
assert(g_framegen_layer == 1);
framegen = 0;
assert(compositor_route(0, 0, 0, &draw) == 1);
assert(g_framegen_layer == 0 && gen_calls == 1 && pass_calls == 1 && base_calls == 2);
reset(); framegen = 1; gen_result = -1;
assert(compositor_route(0, 0, 0, &draw) == 0);
assert(settled == 1 && gen_calls == 1 && base_calls == 0 && fallback_calls == 0);
puts("PASS: Quest first-frame notification and display-layer frame generation");
puts("PASS: Quest first-frame notification waits for client content");
return 0;
}
+29 -8
View File
@@ -707,15 +707,36 @@ class InputUdevPreloadTest(unittest.TestCase):
def identity(self, pads=None, **extra):
return self.run_program("identity", pads=pads, extra=extra)
def test_a_ring_pad_keeps_the_steam_input_identity_whatever_sdl_is_told(self):
steam = ["pad PRODUCT=6/28de/11ff/110", "parent PRODUCT=6/28de/11ff/110"]
for extra in ({}, {"FAKE_EVDEV_UINPUT": "1"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "0"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "1"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142,0x045E/0x028E"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x045e/0x028e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x28de/0x11ff"},
@classmethod
def id_list(cls, name, text):
path = cls.dir / name
path.write_text(text)
return "@" + str(path)
def test_a_pad_wine_also_reads_through_sdl_is_described_as_the_pad_sdl_sees(self):
xbox = ["pad PRODUCT=3/45e/28e/110", "parent PRODUCT=3/45e/28e/110"]
for extra in ({}, {"FAKE_EVDEV_UINPUT": "1"}, {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x045e/0x028e"}, {"FAKE_EVDEV_STEAM_VIRTUAL": "0"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-other.txt", "0x28de/0x1142\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "@" + str(self.dir / "missing.txt")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": self.id_list("except-ring.txt", "0x045E/0x028E\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x45e/0x28e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": ""},
{"FAKE_EVDEV_UINPUT": "1", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}):
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028f"}):
with self.subTest(**extra):
self.assertEqual(self.identity(**extra), xbox)
def test_a_pad_sdl_skips_keeps_the_steam_input_identity(self):
steam = ["pad PRODUCT=6/28de/11ff/110", "parent PRODUCT=6/28de/11ff/110"]
for extra in ({"FAKE_EVDEV_STEAM_VIRTUAL": "1"}, {"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x28de/0x1142,0x045E/0x028E"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "0x28de/0x11ff"},
{"FAKE_EVDEV_UINPUT": "1", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-ring.txt", "0x28de/0x1142\n0x045e/0x028e\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": self.id_list("except-other.txt", "0x28de/0x11ff\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": self.id_list("ignore-long.txt", "0x28de/0x1142\n" * 400 + "0x045e/0x028e\n")},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x45e/0x28e"},
{"SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT": "", "SDL_GAMECONTROLLER_IGNORE_DEVICES": "0x045e/0x028e"}):
with self.subTest(**extra):
self.assertEqual(self.identity(**extra), steam)
+85
View File
@@ -0,0 +1,85 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
class PageCacheNativeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp = tempfile.TemporaryDirectory()
cls.root = Path(cls.temp.name)
javac = shutil.which("javac")
if not javac:
raise unittest.SkipTest("javac headers unavailable")
include = Path(javac).resolve().parents[1] / "include"
source = Path("app/src/main/cpp/sdnative/sdnative.c").resolve()
harness = cls.root / "harness.c"
harness.write_text(
'#include <stdio.h>\n'
f'#include "{source}"\n'
'static const char *get(JNIEnv *e, jstring s, jboolean *b) {\n'
' (void)e; (void)b; return (const char *)s;\n}\n'
'static void release(JNIEnv *e, jstring s, const char *c) {\n'
' (void)e; (void)s; (void)c;\n}\n'
'int main(int argc, char **argv) {\n'
' if (argc != 2) return 2;\n'
' struct JNINativeInterface_ table = {0};\n'
' table.GetStringUTFChars = get;\n'
' table.ReleaseStringUTFChars = release;\n'
' JNIEnv env = &table;\n'
' printf("%d", Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(\n'
' &env, NULL, (jstring)argv[1]));\n'
' return 0;\n}\n'
)
cls.binary = cls.root / "native-check"
subprocess.run([
"cc", "-D_GNU_SOURCE", "-std=c11", "-Wall", "-Wextra", "-Werror",
f"-I{include}", f"-I{include / 'linux'}", str(harness), "-o", str(cls.binary),
], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
cls.temp.cleanup()
def advise(self, path):
return int(subprocess.check_output([str(self.binary), str(path)], timeout=3))
def test_regular_file_preserves_contents(self):
path = self.root / "large"
with path.open("wb") as handle:
handle.write(b"payload")
handle.truncate(8 << 20)
self.assertEqual(0, self.advise(path))
with path.open("rb") as handle:
self.assertEqual(b"payload", handle.read(7))
self.assertEqual(8 << 20, path.stat().st_size)
def test_replacement_fifo_does_not_block(self):
path = self.root / "fifo"
os.mkfifo(path)
self.assertNotEqual(0, self.advise(path))
def test_rejects_small_file_directory_missing_and_relative_path(self):
path = self.root / "small"
path.write_text("small")
for candidate in [path, self.root, self.root / "missing", "relative"]:
with self.subTest(candidate=candidate):
self.assertNotEqual(0, self.advise(candidate))
self.assertEqual("small", path.read_text())
def test_rejects_final_and_parent_symlink_replacements(self):
outside = self.root / "outside"
outside.mkdir()
payload = outside / "payload"
with payload.open("wb") as handle:
handle.truncate(8 << 20)
final = self.root / "final"
final.symlink_to(payload)
parent = self.root / "parent"
parent.symlink_to(outside, target_is_directory=True)
self.assertNotEqual(0, self.advise(final))
self.assertNotEqual(0, self.advise(parent / "payload"))
self.assertNotEqual(0, self.advise(str(outside) + "/../outside/payload"))
-19
View File
@@ -16,11 +16,6 @@ class QuestBackdropTest(unittest.TestCase):
with tempfile.TemporaryDirectory() as folder:
work = Path(folder)
(work / 'vkp_render_under_test.inc').write_text(source[start:end])
compositor = (ROOT / 'app/src/main/cpp/waylandcomp/src/compositor.c').read_text()
route_start = compositor.index(' if (hdr_route == 0 && vkp_quest_layer_presentation()')
route_end = compositor.index(' } else if (hdr_route == 0 || hdr_route == 3)', route_start)
(work / 'quest_route_under_test.inc').write_text(
compositor[route_start:route_end] + ' }\n')
binary = work / 'test-first-frame'
subprocess.run(['cc', '-std=c11', '-Wall', '-Wextra',
'-Wno-unused-parameter', '-Wno-unused-function', f'-I{work}',
@@ -60,20 +55,6 @@ void AHardwareBuffer_describe(const AHardwareBuffer *, AHardwareBuffer_Desc *);
int AHardwareBuffer_lock(AHardwareBuffer *, uint64_t, int32_t, const ARect *, void **);
int AHardwareBuffer_unlock(AHardwareBuffer *, int32_t *);
void AHardwareBuffer_release(AHardwareBuffer *);
''')
vulkan = work / 'vulkan'
vulkan.mkdir()
(vulkan / 'vulkan.h').write_text('''#pragma once
#include <stdint.h>
typedef void *VkInstance;
typedef void *VkPhysicalDevice;
typedef void *VkDevice;
typedef void *VkQueue;
typedef void *VkCommandBuffer;
typedef void *VkImage;
typedef void *VkImageView;
typedef int VkFormat;
typedef void (*PFN_vkGetInstanceProcAddr)(void);
''')
binary = work / 'test-presentation'
subprocess.run(['cc', '-std=c11', '-O1', '-g', '-Wall', '-Wextra',
-125
View File
@@ -1,125 +0,0 @@
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
SHIM = r"""
#include <linux/input.h>
#include <stdarg.h>
#include <string.h>
int ioctl(int fd, unsigned long request, ...) {
va_list ap;
va_start(ap, request);
struct input_id *id = va_arg(ap, struct input_id *);
va_end(ap);
(void)fd;
if (request != EVIOCGID) return -1;
memset(id, 0, sizeof(*id));
id->bustype = 3;
id->vendor = 0x045e;
id->product = 0x028e;
return 0;
}
"""
QUERY = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
void query(const char *path) {
struct input_id id;
int fd = open(path, O_RDONLY | O_CLOEXEC);
int rc = ioctl(fd, EVIOCGID, &id);
printf("%d %04x:%04x\n", rc, id.vendor, id.product);
close(fd);
}
"""
PROGRAM = r"""
#include <dlfcn.h>
#include <stdio.h>
#include <string.h>
void query(const char *path);
int main(int argc, char **argv) {
(void)argc;
if (strcmp(argv[1], "-") != 0) dlopen(argv[1], RTLD_NOW);
if (strcmp(argv[2], "program") == 0) {
query(argv[3]);
} else {
void *sdl = dlopen(argv[2], RTLD_NOW | RTLD_LOCAL);
void (*sdl_query)(const char *) = (void (*)(const char *))dlsym(sdl, "query");
sdl_query(argv[3]);
}
fflush(stdout);
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("cc"), "needs Linux and cc")
class RingPadSdlIdentityTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
build = cls.dir / "build"
build.mkdir()
for name, text in (("shim.c", SHIM), ("query.c", QUERY), ("program.c", PROGRAM), ("empty.c", "int bus;\n")):
(build / name).write_text(text)
cls.lib = cls.dir / "libddsession.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib),
*map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True)
cls.shim = cls.dir / "libshim.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.shim), str(build / "shim.c")], check=True)
cls.winebus = cls.dir / "winebus.so"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.winebus), str(build / "empty.c")], check=True)
cls.sdl_library = cls.dir / "libSDL2-2.0.so.0"
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(cls.sdl_library), str(build / "query.c")], check=True)
cls.program = cls.dir / "program"
subprocess.run(["cc", "-O2", "-o", str(cls.program), str(build / "program.c"), str(build / "query.c"), "-ldl"],
check=True)
cls.ring = cls.dir / "ring0"
cls.ring.write_text("")
cls.virtual = cls.dir / "ring16"
cls.virtual.write_text("")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, True)
def query(self, winebus=True, caller="sdl", path=None, **extra):
env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.lib, self.shim),
FAKE_EVDEV_MEMFD_PATHS="0=%s;16=%s" % (self.ring, self.virtual))
env.pop("FAKE_EVDEV_STEAM_PAD_AS_X360", None)
env.update(extra)
result = subprocess.run([str(self.program), str(self.winebus) if winebus else "-",
str(self.sdl_library) if caller == "sdl" else "program", str(path or self.ring)],
env=env, capture_output=True, text=True, timeout=10, check=True)
return result.stdout.strip()
def test_sdl_in_a_winebus_process_sees_a_ring_pad_as_the_steam_input_pad(self):
self.assertEqual(self.query(), "0 28de:11ff")
def test_sdl_outside_winebus_keeps_the_pad_identity(self):
self.assertEqual(self.query(winebus=False), "0 045e:028e")
def test_other_callers_and_devices_keep_their_identity(self):
self.assertEqual(self.query(caller="program"), "0 045e:028e")
self.assertEqual(self.query(path=self.virtual), "0 045e:028e")
def test_a_winebus_without_a_udev_bus_keeps_the_pad_for_sdl(self):
self.assertEqual(self.query(FAKE_EVDEV_STEAM_PAD_AS_X360="1"), "0 045e:028e")
if __name__ == "__main__":
unittest.main()