diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt index 0a934dd214..d9136eaca1 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt @@ -339,9 +339,12 @@ internal class SessionSuspendController( return } val hold = holdFile(control) + val requests = chosen.map { File(control.parentFile, "${hold.name}.${it.pid}") } try { - hold.writeText(READ_BACK_REQUEST) + hold.writeText(NO_REQUEST) + requests.forEach { it.writeText(READ_BACK_REQUEST) } } catch (_: IOException) { + requests.forEach { it.delete() } hold.delete() return } @@ -360,6 +363,7 @@ internal class SessionSuspendController( } catch (_: InterruptedException) { Thread.currentThread().interrupt() } finally { + requests.forEach { it.delete() } hold.delete() } pagedIn(chosen.size, memoryKb(targets).second, before, available, nowMillis() - start) @@ -489,6 +493,7 @@ internal class SessionSuspendController( const val PAGE_OUT_ACK = "1" const val PAGE_OUT_REQUEST = "1" const val READ_BACK_REQUEST = "0" + const val NO_REQUEST = "2 0" const val PAGE_OUT_POLL_MS = 100L const val PAGE_OUT_START_MS = 2_000L const val PAGE_OUT_TIMEOUT_MS = 12_000L diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt index 66fe1d8655..a0c6e492a6 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt @@ -8,6 +8,7 @@ import java.util.concurrent.RejectedExecutionException import java.util.concurrent.TimeUnit import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test @@ -132,7 +133,9 @@ class SessionSuspendControllerTest { assertFalse(hold.exists()) fixture.controller.resume { assertTrue(it) } assertFalse(hold.exists()) + assertFalse(File(fixture.control.parentFile, ".dd-zram.hold.$GAME").exists()) assertEquals(listOf("1", "0"), fixture.held) + assertEquals(listOf("1", "2 0"), fixture.shared) } @Test fun noReadBackAfterAFreezeWithoutPageOut() { @@ -221,6 +224,20 @@ class SessionSuspendControllerTest { assertEquals(0L, fixture.swapKb(SERVICE)) } + @Test fun aPendingPageOutRequestOfAProcessLeftOutDoesNotReadItBack() { + val fixture = fixture(17) + fixture.addService(2_000_000L) + fixture.control.writeText("0") + fixture.availableKb = 5_000_000L + fixture.controller.freeze(pageOut = true) { assertTrue(it) } + fixture.lateRequest = GAME + fixture.controller.resume { assertTrue(it) } + assertNull(fixture.lateRequest) + assertEquals(3_000_000L, fixture.swapKb(GAME)) + assertEquals(0L, fixture.swapKb(SERVICE)) + assertEquals(listOf(Triple(1, 3_000_000L, 4_000_000L)), fixture.pagedIn) + } + @Test fun everyPagedOutProcessIsReadBackWhenMemoryAllows() { val fixture = fixture(17) fixture.addService(2_000_000L) @@ -538,6 +555,8 @@ class SessionSuspendControllerTest { val helpers = mutableListOf() val signals = mutableListOf() val held = mutableListOf() + val shared = mutableListOf() + var lateRequest: Int? = null var rootPid = ROOT var now = 0L var audioSuspends = 0 @@ -588,8 +607,11 @@ class SessionSuspendControllerTest { private fun signal(pid: Int, signal: Int) { signals += SentSignal(pid, signal) - val request = if (signal == URG) File(control.parentFile, "${control.name}.hold").takeIf { it.isFile }?.readText() else null - if (signal == URG) held += request + val request = if (signal == URG) request(pid) else null + if (signal == URG) { + held += request + shared += sharedHold().takeIf { it.isFile }?.readText() + } val group = groups.first { it.pid == pid } if (signal == STOP) { continuing = false @@ -598,8 +620,7 @@ class SessionSuspendControllerTest { it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last()) }?.state = 't' } else if (signal == URG) { - val memory = paging.getValue(pid) - if (request == "0") { memory.out = false; memory.into = true } else memory.out = true + take(pid, request) } else if (signal == CONT) { if (clockAtContinue == null && clock.isFile) { clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long @@ -610,6 +631,20 @@ class SessionSuspendControllerTest { sync() } + private fun sharedHold() = File(control.parentFile, "${control.name}.hold") + + private fun request(pid: Int): String? = + File(control.parentFile, "${control.name}.hold.$pid").takeIf { it.isFile }?.readText() + ?: sharedHold().takeIf { it.isFile }?.readText() + + private fun take(pid: Int, request: String?) { + val memory = paging.getValue(pid) + when (request) { + "0" -> { memory.out = false; memory.into = true } + "1", null -> memory.out = true + } + } + private fun threadSignal(pid: Int, tid: Int, signal: Int) { signals += SentSignal(pid, signal) val task = groups.first { it.pid == pid }.threads.first { it.tid == tid } @@ -621,6 +656,10 @@ class SessionSuspendControllerTest { private fun sleep(millis: Long) { now += millis + lateRequest?.takeIf { sharedHold().isFile }?.let { pid -> + lateRequest = null + take(pid, request(pid)) + } for ((pid, memory) in paging) { if (memory.out && !handlerReplaced) { File(control.parentFile, "${control.name}.ack.$pid").apply { if (!exists()) writeText("") } diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index eb714f802c..e734dc9f9d 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -72,10 +72,13 @@ has waited five seconds in total or six seconds have gone by since it began, is minute, and a late answer from it is discarded. A process is known by its number and start time, so a new process that got the number of a skipped one is asked. Processes with less than 8 MiB of anonymous memory are skipped. While the app pages the session out for suspend, or -reads it back on resume, it holds the monitor off with `/tmp/.dd-zram.hold` and writes its own -request (`1` to page out, `0` to read back) into that file. A signalled process reads the hold -file first and the control file only when the hold file is missing or empty, so a trim request -the monitor wrote at the same moment cannot replace the app's. The suspend page-out answers `1` +reads it back on resume, it holds the monitor off with `/tmp/.dd-zram.hold`. A page-out writes +`1` into that file. A read-back writes `2 0`, which asks for nothing, and puts `0` into +`/tmp/.dd-zram.hold.` for each process it chose. A signalled process reads its own hold file +first, then the shared one, and the control file only when both are missing or empty. A trim +request the monitor wrote at the same moment cannot replace the app's, and a process that was +not chosen does not read back, even if it only now starts the page-out request it was sent +before the suspend. The suspend page-out answers `1` in `/tmp/.dd-zram.ack.` and a trim answers its kB in `/tmp/.dd-zram.trim.`, so the monitor never removes or reads an answer the app is waiting for, and the app never takes a trim's answer for its own. A trim budget smaller than a chunk covers the stretch of the chunk @@ -155,8 +158,9 @@ process through the preload, and GPU memory itself cannot be compressed from use A hidden or screen-off suspend pages the session out before it stops it. After the resume, the processes that were paged out are read back largest first, as long as their swap fits the budget: half of `MemAvailable`, while leaving the larger of 1 GiB and a tenth of RAM available. -Processes that do not fit keep their memory in zram and fault it back on demand, so one large -process no longer stops the read-back of every other one. +Only the chosen processes get a read-back request. Processes that do not fit keep their memory +in zram and fault it back on demand, so one large process no longer stops the read-back of every +other one. ## CRAM and the bounded pager experiment diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index ee13167e38..a2e5c60f52 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -132,7 +132,7 @@ clear_stale_tmp() { [ -z "${DD_INSIDE:-}" ] && clear_stale_tmp if [ -z "${DD_INSIDE:-}" ]; then if [ "${DD_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.dd-zram; else rm -f /tmp/.dd-zram; fi - rm -f /tmp/.dd-zram.hold + rm -f /tmp/.dd-zram.hold /tmp/.dd-zram.hold.* dd if=/dev/zero of=/tmp/.dd-clock bs=8 count=1 conv=notrunc status=none fi diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 551a6e148c..c732ee7e34 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -32,6 +32,7 @@ #define ZR_FAILED (~0UL) #define ZR_FUTEX_WAIT 0 #define ZR_FUTEX_WAKE 1 +#define ZR_PATH (sizeof(ZR_CTL) + sizeof(".hold.") + 20) static long (*zr_sys)(long, ...); static unsigned long zr_page; @@ -58,20 +59,32 @@ static int zr_open(const char *path) { return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0); } +static void zr_path(char *path, const char *suffix) { + char digits[20]; + size_t n = 0, d = 0; + for (const char *p = ZR_CTL; *p; p++) path[n++] = *p; + for (const char *p = suffix; *p; p++) path[n++] = *p; + long pid = zr_sys(SYS_getpid); + do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0); + while (d > 0) path[n++] = digits[--d]; + path[n] = 0; +} + +static long zr_read_text(const char *path, char *text, size_t size) { + int fd = zr_open(path); + if (fd < 0) return 0; + long n = zr_sys(SYS_read, fd, text, size); + zr_sys(SYS_close, fd); + return n; +} + static int zr_mode(unsigned long *want) { char text[24]; - long n = 0; - int fd = zr_open(ZR_CTL ".hold"); - if (fd >= 0) { - n = zr_sys(SYS_read, fd, text, sizeof(text)); - zr_sys(SYS_close, fd); - } - if (n < 1) { - fd = zr_open(ZR_CTL); - if (fd < 0) return -1; - n = zr_sys(SYS_read, fd, text, sizeof(text)); - zr_sys(SYS_close, fd); - } + char own[ZR_PATH]; + zr_path(own, ".hold."); + long n = zr_read_text(own, text, sizeof(text)); + if (n < 1) n = zr_read_text(ZR_CTL ".hold", text, sizeof(text)); + if (n < 1) n = zr_read_text(ZR_CTL, text, sizeof(text)); if (n < 1 || text[0] < '0' || text[0] > '3') return -1; unsigned long kb = 0; for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++) @@ -254,16 +267,10 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns } static void zr_ack(long value, int trim) { - const char *suffix = trim ? ".trim." : ".ack."; - char path[sizeof(ZR_CTL) + sizeof(".trim.") + 20]; + char path[ZR_PATH]; char digits[20]; - size_t n = 0, d = 0; - for (const char *p = ZR_CTL; *p; p++) path[n++] = *p; - for (const char *p = suffix; *p; p++) path[n++] = *p; - long pid = zr_sys(SYS_getpid); - do digits[d++] = (char)('0' + pid % 10); while ((pid /= 10) > 0); - while (d > 0) path[n++] = digits[--d]; - path[n] = 0; + size_t n, d; + zr_path(path, trim ? ".trim." : ".ack."); int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd < 0) return; for (d = 0; value >= 0 && (d == 0 || value > 0); value /= 10) digits[d++] = (char)('0' + value % 10); diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py index bf1e8391cd..6ee4aa0b76 100644 --- a/tools/tests/test_zram_preload.py +++ b/tools/tests/test_zram_preload.py @@ -258,6 +258,36 @@ int main(int argc, char **argv) { printf("held %ld\n", status("VmSwap:")); unlink(hold); return 0; + } else if (!strcmp(argv[4], "scoped")) { + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + request('1'); + printf("out %ld\n", status("VmSwap:")); + char hold[256], own[256]; + snprintf(hold, sizeof(hold), "%s.hold", ctl); + snprintf(own, sizeof(own), "%s.hold.%d", ctl, getpid()); + FILE *f = fopen(ctl, "w"); + if (!f) exit(3); + fputs("0", f); + fclose(f); + f = fopen(hold, "w"); + if (!f) exit(3); + fputs("2 0", f); + fclose(f); + kill(getpid(), SIGURG); + usleep(1000000); + printf("shared %ld\n", status("VmSwap:")); + f = fopen(own, "w"); + if (!f) exit(3); + fputs("0", f); + fclose(f); + kill(getpid(), SIGURG); + usleep(1000000); + printf("own %ld\n", status("VmSwap:")); + unlink(own); + unlink(hold); + printf("intact %d\n", sum(data, size) == before); + return 0; } else if (!strcmp(argv[4], "trim-fork")) { stop = 1; for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); @@ -389,6 +419,8 @@ class ZramPreloadTest(unittest.TestCase): for ack in [*self.dir.glob("ctl.ack.*"), *self.dir.glob("ctl.trim.*")]: ack.unlink() (self.dir / "ctl.hold").unlink(missing_ok=True) + for hold in self.dir.glob("ctl.hold.*"): + hold.unlink() def run_program(self, program=None, mb=48, cycles=1, *extra): environment = dict(os.environ, LD_PRELOAD=str(self.lib)) @@ -535,6 +567,14 @@ class ZramPreloadTest(unittest.TestCase): self.assertTrue(0 < out["empty"][0] <= 512, out) self.assertGreater(out["held"][0], 40 * 1024, out) + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_a_read_back_reaches_only_the_process_it_names(self): + out = self.run_program(None, 48, 0, "scoped") + self.assertGreater(out["out"][0], 32 * 1024, out) + self.assertGreater(out["shared"][0], out["out"][0] * 3 // 4, out) + self.assertLess(out["own"][0], out["out"][0] // 4, out) + self.assertEqual([1], out["intact"]) + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") def test_process_without_a_worker_trims_in_small_steps(self): out = self.run_program(None, 48, 0, "trim-fork")