Compare commits

..
9 changed files with 41 additions and 479 deletions

No files matched your search

-42
View File
@@ -1,13 +1,9 @@
#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>
@@ -31,41 +27,3 @@ 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;
}
@@ -190,6 +190,7 @@ object BwrapSpawner {
val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
withoutRootfsSettings(env, rootfs)
sdlAudioOnPulse(env)
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
if (envTool == null && binds.any { it.guest == "/dev" }) {
val glIcd = coveringBind(GL_ICD_DIR) != null && File(hostPath(binds, root.path, GL_ICD_DIR)).isDirectory
@@ -220,6 +221,17 @@ object BwrapSpawner {
}
}
private val SDL_AUDIO_DRIVER_KEYS = listOf("SDL_AUDIODRIVER", "SDL_AUDIO_DRIVER")
internal fun sdlAudioOnPulse(env: MutableMap<String, String>) {
if (env["PULSE_SERVER"].isNullOrEmpty()) return
for (key in SDL_AUDIO_DRIVER_KEYS) {
val drivers = env[key]?.split(',')?.map { it.trim() } ?: continue
if (drivers.none { it.equals("pipewire", true) } || drivers.any { it.equals("pulseaudio", true) }) continue
env[key] = drivers.map { if (it.equals("pipewire", true)) "pulseaudio" else it }.joinToString(",")
}
}
private const val GPU_DIR = "/run/droiddeck-gpu"
private const val GL_ICD_DIR = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d"
@@ -1,126 +0,0 @@
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,12 +430,6 @@ 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
@@ -77,6 +77,31 @@ class BwrapSpawnerTest {
assertEquals("x11", x11["SDL_VIDEODRIVER"])
}
@Test fun sdlPinnedToPipewireUsesTheSessionsPulseServer() {
val pulse = "unix:/run/flatpak/pulse/native"
val pinned = mutableMapOf("SDL_AUDIODRIVER" to "pipewire", "PULSE_SERVER" to pulse)
BwrapSpawner.sdlAudioOnPulse(pinned)
assertEquals("pulseaudio", pinned["SDL_AUDIODRIVER"])
val sdl3 = mutableMapOf("SDL_AUDIO_DRIVER" to "PipeWire, alsa", "PULSE_SERVER" to pulse)
BwrapSpawner.sdlAudioOnPulse(sdl3)
assertEquals("pulseaudio,alsa", sdl3["SDL_AUDIO_DRIVER"])
}
@Test fun otherSdlAudioChoicesAreKept() {
val noPulse = mutableMapOf("SDL_AUDIODRIVER" to "pipewire")
BwrapSpawner.sdlAudioOnPulse(noPulse)
assertEquals(mapOf("SDL_AUDIODRIVER" to "pipewire"), noPulse)
val pulse = "unix:/run/flatpak/pulse/native"
for (choice in listOf("pipewire,pulseaudio", "alsa", "dummy")) {
val env = mutableMapOf("SDL_AUDIODRIVER" to choice, "PULSE_SERVER" to pulse)
BwrapSpawner.sdlAudioOnPulse(env)
assertEquals(choice, env["SDL_AUDIODRIVER"])
}
val unset = mutableMapOf("PULSE_SERVER" to pulse)
BwrapSpawner.sdlAudioOnPulse(unset)
assertEquals(mapOf("PULSE_SERVER" to pulse), unset)
}
@Test fun sourcesNamedByTheirKernelPathReachTheSessionsMounts() {
val files = "/data/user/0/com.droiddeck.launcher/files"
val kernel = "/data/data/com.droiddeck.launcher/files"
@@ -1,199 +0,0 @@
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)
}
}
+4
View File
@@ -59,6 +59,10 @@ The spawner also adds what the rootfs gives its own programs:
Chromium and Electron apps use zypak's mimic strategy (`ZYPAK_ZYGOTE_STRATEGY_SPAWN=0`). The
Flatpak portal's Spawn refuses a caller whose `/proc/<pid>/root` holds no `.flatpak-info`,
and a proot sandbox's root is the host's.
- **Audio.** The session's sound server is PulseAudio, and Flatpak binds its socket in for apps that ask
for it. An app that pins SDL to PipeWire (`SDL_AUDIODRIVER=pipewire`, as Chiaki-ng's does) gets
`pulseaudio` in its place when that socket is there. Otherwise SDL finds no PipeWire server and the
app quits at start.
- **CPU.** `/proc/cpuinfo` without the cores' part numbers. Snapdragon's ARMv9 cores imply SVE2
to LLVM, Qualcomm leaves SVE off, and llvmpipe's first shader died with SIGILL.
-21
View File
@@ -85,27 +85,6 @@ 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,
-85
View File
@@ -1,85 +0,0 @@
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"))