Compare commits

...
6 changed files with 479 additions and 0 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;
}
@@ -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,
+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"))