diff --git a/app/src/main/cpp/sdnative/sdnative.c b/app/src/main/cpp/sdnative/sdnative.c index 8482f38d33..ec8cdb0ae3 100644 --- a/app/src/main/cpp/sdnative/sdnative.c +++ b/app/src/main/cpp/sdnative/sdnative.c @@ -5,6 +5,9 @@ #include #include #include +#include +#include +#include #include #include @@ -34,10 +37,35 @@ Java_com_droiddeck_launcher_session_PageCacheNative_fadviseDontNeed(JNIEnv *env, (void)clazz; const char *chars = (*env)->GetStringUTFChars(env, path, NULL); if (!chars) return ENOMEM; - int fd = open(chars, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + char *copy = strdup(chars); (*env)->ReleaseStringUTFChars(env, path, chars); - if (fd < 0) return errno; - int rc = posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED); - close(fd); + 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; } diff --git a/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt b/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt index a3f0b80fae..a7d8f70479 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PageCacheTrim.kt @@ -38,41 +38,79 @@ internal object PageCacheTrim { "${trim.files} file(s), ${trim.failed} failed, ${trim.ms} ms" } + internal class Worker( + private val roots: () -> List, + 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() + 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() + 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, alive: () -> Boolean, report: (String) -> Unit = {}) { Thread({ - var baseline = 0L - var files = emptyList() - var scanned = 0L - var trimmed = 0L + 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 { - val before = parse(File("/proc/meminfo").readText()) ?: return@runCatching - val now = System.currentTimeMillis() - if (!shouldTrim(before, baseline) || now - trimmed < MIN_TRIM_MS) return@runCatching - if (now - scanned >= RESCAN_MS) { - files = roots().asSequence().filter { root -> - root.isDirectory && !Files.isSymbolicLink(root.toPath()) - }.flatMap { root -> - root.walkTopDown().onEnter { !Files.isSymbolicLink(it.toPath()) } - }.filter { file -> - file.isFile && !Files.isSymbolicLink(file.toPath()) && file.length() >= MIN_FILE_BYTES - }.toList() - if (files.isNotEmpty()) scanned = now - } - val began = System.nanoTime() - var failed = 0 - files.forEach { if (PageCacheNative.fadviseDontNeed(it.path) != 0) failed++ } - val after = parse(File("/proc/meminfo").readText()) - baseline = after?.fileKb ?: before.fileKb - trimmed = now - val message = describe(Trim(before, after, files.size, failed, (System.nanoTime() - began) / 1_000_000)) - Log.i(TAG, message) - report(message) - }.onFailure { + 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() diff --git a/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt index 99f152a935..407ed049a4 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PageCacheTrimTest.kt @@ -5,6 +5,11 @@ 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" @@ -32,4 +37,163 @@ class PageCacheTrimTest { "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() + val reports = mutableListOf() + 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) + } } diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index 071aa5f5d0..10c752df98 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -87,15 +87,24 @@ is no longer compressed on a timer. ## File page cache -Android can still kill the app while clean file pages DroidDeck itself read are cached: they are -reclaimable, but not counted as free by `lmkd`. While a session runs, a separate thread reads -`MemFree` and the `Active(file)` plus `Inactive(file)` totals every three seconds. When `MemFree` -is under 2.5 GiB and the file LRU has grown by 768 MiB since the last pass, or under 1 GiB with -128 MiB of growth, it calls `posix_fadvise(DONTNEED)` on regular files of at least 8 MiB under the -session's Linux root and the selected game storage. The file list is rescanned every two minutes, -a pass runs at most once every 30 seconds, and only files DroidDeck owns are dropped. The pass -stops at the same message in the session log and in `events.jsonl`. Other apps' page cache, mapped -pages, anonymous memory and GPU memory are untouched. +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 diff --git a/tools/tests/test_page_cache_native.py b/tools/tests/test_page_cache_native.py new file mode 100644 index 0000000000..243fcda9bc --- /dev/null +++ b/tools/tests/test_page_cache_native.py @@ -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 \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"))