diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index b2cc52bcee..5f48f05683 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -972,6 +972,9 @@ object SessionPrefs { fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true) + /** A sleeping session writes its memory to storage instead of zram. */ + fun diskSpill(context: Context): Boolean = prefs(context).getBoolean("diskSpill", false) + fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true) fun setValveProtonOnDemand(context: Context, on: Boolean) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 67992024db..8a0a7e228f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -993,6 +993,26 @@ class SessionService : Service() { )) } }, + spilled = { processes, spilledKb, residentKb, millis -> + Log.i(TAG, "wrote $processes processes to storage in $millis ms: ${spilledKb / 1024} MB, " + + "resident ${residentKb / 1024} MB") + mainHandler.post { + SessionEvents.record("session.spilled", mapOf( + "processes" to processes, "spilledMb" to spilledKb / 1024, "residentMb" to residentKb / 1024, + "ms" to millis, + )) + } + }, + restored = { processes, unacknowledged, residentKb, millis -> + Log.i(TAG, "restored $processes processes ($unacknowledged unacknowledged) from storage in $millis ms: " + + "resident ${residentKb / 1024} MB") + mainHandler.post { + SessionEvents.record("session.restored", mapOf( + "processes" to processes, "unacknowledged" to unacknowledged, + "residentMb" to residentKb / 1024, "ms" to millis, + )) + } + }, ) updateDownloadMonitoring() mainHandler.post { updateSuspendPolicy() } @@ -2175,9 +2195,8 @@ class SessionService : Service() { freezeCancelled = false val freezeSteamToken = steamSleepToken val freezeNativeToken = nativeSleepToken - controller.freeze( - pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn, - ) { success -> + val pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn + controller.freeze(pageOut = pageOut, spill = pageOut && SessionPrefs.diskSpill(this)) { success -> mainHandler.post { if (gen != sessionGen || !SessionState.running) return@post SessionState.suspending = false 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 74f7d5ace9..bc07f29207 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt @@ -29,6 +29,8 @@ internal class SessionSuspendController( { _, _, _, _, _, _ -> }, private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit = { _, _, _, _, _ -> }, + private val spilled: (processes: Int, spilledKb: Long, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> }, + private val restored: (processes: Int, unacknowledged: Int, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> }, ) { private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD } @@ -53,8 +55,9 @@ internal class SessionSuspendController( private var frozen = emptyList() private var frozenSince: Long? = null private var pagedOutTargets = emptyList() + private var spilledTargets = emptyList() - fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) { + fun freeze(pageOut: Boolean = false, spill: Boolean = false, completion: (Boolean) -> Unit) { cancelled = false submit({ val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started } @@ -74,7 +77,7 @@ internal class SessionSuspendController( records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) } } - if (pageOut) pageOut(records, root.pid, helpers) + if (pageOut) pageOut(records, root.pid, helpers, spill) val deadline = nowMillis() + FREEZE_TIMEOUT_MS var previous: Map? = null for (pass in 0 until FREEZE_MAX_PASSES) { @@ -275,13 +278,13 @@ internal class SessionSuspendController( return tasks.takeIf { stopped && it.isNotEmpty() } } - private fun pageOut(records: MutableMap, ProcessRecord>, root: Int, helpers: List) { + private fun pageOut(records: MutableMap, ProcessRecord>, root: Int, helpers: List, spill: Boolean) { val control = zramControl?.takeIf { it.isFile } ?: return val hold = holdFile(control) try { - hold.writeText(PAGE_OUT_REQUEST) + hold.writeText(if (spill) SPILL_REQUEST else PAGE_OUT_REQUEST) sleep(PAGE_OUT_POLL_MS) - pageOut(control, records, root, helpers) + if (spill) spill(control, records, root, helpers) else pageOut(control, records, root, helpers) } catch (_: IOException) { } finally { hold.delete() @@ -290,15 +293,84 @@ internal class SessionSuspendController( private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold") + private fun ackFile(control: File, kind: String, record: ProcessRecord) = + File(control.parentFile, "${control.name}.$kind.${record.pid}") + + private fun preloaded(records: Collection) = records.filter { record -> + try { + File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } } + } catch (_: IOException) { + false + } + } + + private fun readAck(ack: File): Long? = try { + ack.readText().trim().toLongOrNull() + } catch (_: IOException) { + null + } + + // Each process parks its threads, writes its private memory to an unlinked file and stays parked until + // the resume counter changes; its acknowledgement is the kB it wrote, 0 when it paged out to zram instead. + private fun spill(control: File, records: MutableMap, ProcessRecord>, root: Int, helpers: List) { + addSnapshot(records, root, helpers) + val targets = preloaded(records.values) + if (targets.isEmpty()) return + targets.forEach { ackFile(control, "ack", it).delete(); ackFile(control, "restored", it).delete() } + val start = nowMillis() + for (record in targets) send(record, SIGURG) + val waiting = targets.toMutableList() + while (!closing && !cancelled && nowMillis() - start < SPILL_TIMEOUT_MS) { + val started = nowMillis() - start >= PAGE_OUT_START_MS + waiting.removeAll { val ack = ackFile(control, "ack", it); readAck(ack) != null || (started && !ack.exists()) || isGone(it) } + if (waiting.isEmpty()) break + sleep(PAGE_OUT_POLL_MS) + } + var total = 0L + val written = targets.filter { record -> + val kb = readAck(ackFile(control, "ack", record)) ?: 0L + total += kb + kb > 0L + } + spilledTargets = (spilledTargets + written).distinct() + pagedOutTargets = (pagedOutTargets + targets.filterNot { it in written }).distinct() + targets.forEach { ackFile(control, "ack", it).delete() } + spilled(written.size, total, memoryKb(targets).first, nowMillis() - start) + } + + private fun bumpResume() { + val control = zramControl?.takeIf { it.isFile } ?: return + val counter = File(control.parentFile, "${control.name}.resume") + try { + val next = (counter.takeIf { it.isFile }?.readText()?.trim()?.toLongOrNull() ?: 0L) + 1 + counter.writeText(next.toString()) + } catch (_: IOException) { + } + } + + private fun awaitRestored() { + val targets = spilledTargets + spilledTargets = emptyList() + val control = zramControl ?: return + if (targets.isEmpty()) return + val start = nowMillis() + val waiting = targets.toMutableList() + try { + while (!closing && nowMillis() - start < RESTORE_TIMEOUT_MS) { + waiting.removeAll { readAck(ackFile(control, "restored", it)) != null || isGone(it) } + if (waiting.isEmpty()) break + sleep(PAGE_OUT_POLL_MS) + } + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + } + targets.forEach { ackFile(control, "restored", it).delete() } + restored(targets.size, waiting.size, memoryKb(targets).first, nowMillis() - start) + } + private fun pageOut(control: File, records: MutableMap, ProcessRecord>, root: Int, helpers: List) { addSnapshot(records, root, helpers) - val targets = records.values.filter { record -> - try { - File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } } - } catch (_: IOException) { - false - } - } + val targets = preloaded(records.values) if (targets.isEmpty()) return pagedOutTargets = (pagedOutTargets + targets).distinct() val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") } @@ -326,6 +398,7 @@ internal class SessionSuspendController( } private fun readBack() { + awaitRestored() val targets = pagedOutTargets.filterNot { isGone(it) } pagedOutTargets = emptyList() val control = zramControl?.takeIf { it.isFile } ?: return @@ -431,6 +504,7 @@ internal class SessionSuspendController( Role.HELPER_CHILD -> 3 } } + bumpResume() for (record in ordered) send(record, SIGCONT) val waiting = ordered.toMutableList() repeat(RESTORE_CHECKS) { check -> @@ -460,10 +534,12 @@ internal class SessionSuspendController( } } + // A spilled process's threads stay in a tracing stop until its helper has read its memory back. private fun isRunningOrGone(record: ProcessRecord): Boolean { val current = try { readProcess(record.pid) } catch (_: Exception) { return false } if (current == null || current.started != record.started) return true - if (current.state == 'T' || current.state == 't') return false + val spilled = record in spilledTargets + if (current.state == 'T' || (current.state == 't' && !spilled)) return false return File(procRoot, "${record.pid}/task").listFiles().orEmpty().none { entry -> entry.name.toIntOrNull() != null && try { readStat(File(entry, "stat"))[0].first() == 'T' } catch (_: IOException) { false } @@ -477,6 +553,9 @@ internal class SessionSuspendController( const val PAGE_OUT_ACK = "1" const val PAGE_OUT_REQUEST = "1" const val READ_BACK_REQUEST = "0" + const val SPILL_REQUEST = "4" + const val SPILL_TIMEOUT_MS = 30_000L + const val RESTORE_TIMEOUT_MS = 30_000L 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 66b68631f4..0c89e65725 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt @@ -124,6 +124,58 @@ class SessionSuspendControllerTest { assertEquals(1, fixture.pagedIn.size) } + @Test fun aSpillWritesThePreloadedGuestsToStorageBeforeTheyStop() { + val fixture = fixture(17) + fixture.control.writeText("0") + fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) } + assertEquals(listOf("4"), fixture.held) + assertTrue(fixture.signals.indexOfFirst { it.signal == URG } < fixture.signals.indexOfFirst { it.signal == STOP }) + assertEquals(listOf(1 to 4_000_000L), fixture.spills) + assertTrue(fixture.pagedOut.isEmpty()) + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists()) + assertFalse(File(fixture.control.parentFile, ".dd-zram.hold").exists()) + } + + @Test fun resumeMovesTheCounterBeforeContinuingAndWaitsForTheRestore() { + val fixture = fixture(17) + fixture.control.writeText("0") + fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) } + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertEquals(listOf("1"), fixture.resumeAtContinue) + assertFalse(fixture.signals.drop(before).any { it.signal == URG }) + assertEquals(listOf(1 to 0), fixture.restores) + assertTrue(fixture.pagedIn.isEmpty()) + assertFalse(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").exists()) + fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) } + fixture.controller.resume { assertTrue(it) } + assertEquals(listOf("1", "2"), fixture.resumeAtContinue) + assertEquals(2, fixture.restores.size) + } + + @Test fun aGuestThatCouldNotSpillIsReadBackFromZram() { + val fixture = fixture(17) + fixture.control.writeText("0") + fixture.spillFallsBack = true + fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) } + assertEquals(listOf(0 to 0L), fixture.spills) + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertEquals(listOf(GAME), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid }) + assertTrue(fixture.restores.isEmpty()) + assertEquals(1, fixture.pagedIn.size) + } + + @Test fun aSpillCutShortByACancelledFreezeIsStillRestored() { + val fixture = fixture(17) + fixture.control.writeText("0") + fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() } + fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) } + assertEquals(listOf("1"), fixture.resumeAtContinue) + assertEquals(listOf(1 to 0), fixture.restores) + } + @Test fun theMonitorIsHeldOffWhilePagingOutAndReadingBack() { val fixture = fixture(17) fixture.control.writeText("0") @@ -522,6 +574,14 @@ class SessionSuspendControllerTest { var unacknowledged = -1 var handlerStalls = false var handlerReplaced = false + var spillFallsBack = false + val spills = mutableListOf>() + val restores = mutableListOf>() + val resumeAtContinue = mutableListOf() + private var spilling = false + private var spilledBase: String? = null + private var restoring = false + private val resume = File(tmp, ".dd-zram.resume") private var continuing = false val controller = SessionSuspendController( { rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ }, @@ -535,6 +595,8 @@ class SessionSuspendControllerTest { this.unacknowledged = unacknowledged }, pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) }, + spilled = { processes, spilledKb, _, _ -> spills += processes to spilledKb }, + restored = { processes, unacknowledged, _, _ -> restores += processes to unacknowledged }, ) init { sync() } @@ -551,8 +613,10 @@ class SessionSuspendControllerTest { it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last()) }?.state = 't' } else if (signal == URG) { - if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true + if (request == "4") spilling = true + else if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true } else if (signal == CONT) { + if (pid == GAME) resumeAtContinue += resume.takeIf { it.isFile }?.readText() if (clockAtContinue == null && clock.isFile) { clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long } @@ -573,6 +637,25 @@ class SessionSuspendControllerTest { private fun sleep(millis: Long) { now += millis + if (spilling) { + spilling = false + val ack = File(control.parentFile, "${control.name}.ack.$GAME") + if (spillFallsBack) { + gameSwapKb += gameResidentKb + gameResidentKb = 0L + ack.writeText("0") + } else { + spilledBase = resume.takeIf { it.isFile }?.readText() + ack.writeText(gameResidentKb.toString()) + gameResidentKb = 0L + restoring = true + } + } + if (restoring && continuing && resume.takeIf { it.isFile }?.readText() != spilledBase) { + restoring = false + gameResidentKb = 4_000_000L + File(control.parentFile, "${control.name}.restored.$GAME").writeText("120") + } if (pagingOut && !handlerReplaced) { File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") } } diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index a0fbb9f274..abf42619bb 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -97,6 +97,22 @@ out, and resuming reads it back when available memory is at least twice what tho have in swap at that moment and, after it, 1 GiB or a tenth of RAM, whichever is larger, stays available. +## Writing a sleeping session to storage + +With the `diskSpill` session pref on, the suspend for sleep writes each preloaded process's +private memory to storage instead of zram (request `4`). The preload's worker starts a helper +process that shares the process's memory, stops every other thread with ptrace (which also holds +threads that block every signal, as Mesa's queue threads do, and which `SIGCONT` does not undo), +writes readable private anonymous memory to an unlinked file next to the control file, drops it, +and answers the kB it wrote in `/tmp/.dd-zram.ack.`. Regions registered with userfaultfd, +locked or I/O memory and the preload's own memory stay. The app adds one to +`/tmp/.dd-zram.resume` before it continues any process; the helper then reads everything back +(through `/proc//mem` where the pages are not writable), answers `/tmp/.dd-zram.restored.` +and lets the threads go. A process that cannot be traced answers `0` and pages out to zram instead. + +On an AYN Thor with Bully at its menu, 30 processes wrote 1,227 MB in 2.1 seconds and read it +back in 1.3 seconds; system anonymous memory fell from 2.53 to 1.21 GB while asleep. + ## Threads When a worker can be started, page-out runs outside the game's threads. The preload's signal diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index 7fc21d0cab..1498e30d88 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -12,6 +12,8 @@ #include #include #include +#include +#include #if defined(__i386__) #include #endif @@ -37,6 +39,14 @@ #define ZR_INLINE_CHUNKS 512UL #define ZR_FAILED (~0UL) #define ZR_FUTEX_WAIT 0 +#define ZR_PTRACE_DETACH 17 +#define ZR_PTRACE_SEIZE 0x4206 +#define ZR_PTRACE_INTERRUPT 0x4207 +#define ZR_SPILL_CHUNK (8UL << 20) +#define ZR_SPILL_RUNS ((16UL << 20) / sizeof(struct zr_run)) +#define ZR_SPILL_TIDS 8192 +#define ZR_PARK_MS 3000 +#define ZR_RESUME_POLL_MS 50 #define ZR_STACK (128UL << 10) #define ZR_THREAD (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM | \ CLONE_SETTLS | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID) @@ -202,6 +212,20 @@ static struct zr_slot { static uint16_t zr_gen = 1; static unsigned long zr_cursor; static unsigned long zr_visits; +static struct zr_run { + unsigned long addr, len, off, writable; +} *zr_runs; +static char *zr_bounce; +static unsigned long zr_run_count; +static long zr_owner; +static long zr_reaper; +static int zr_seized; +static int zr_tids[ZR_SPILL_TIDS]; +static signed char zr_stopped[ZR_SPILL_TIDS]; +static char *zr_helper_stack; +static int zr_helper_done; +static char zr_baseline[24]; +static int zr_base_len; static int zr_prefix(const char *text, const char *prefix) { while (*prefix) @@ -209,6 +233,11 @@ static int zr_prefix(const char *text, const char *prefix) { return 1; } +// A named mapping never merges with the game's anonymous memory, so excluding it from a spill excludes only it. +static void zr_name(long addr, unsigned long len) { + zr_sys(SYS_prctl, 0x53564d41, 0, addr, len, "dd-zram"); +} + static char *zr_find(char *text, char c, size_t n) { for (; n > 0; n--, text++) if (*text == c) return text; @@ -217,6 +246,7 @@ static char *zr_find(char *text, char c, size_t n) { static char zr_ctl[ZR_PATH] = ZR_CTL; static char zr_hold[ZR_PATH + sizeof(".hold")]; +static char zr_resume[ZR_PATH + sizeof(".resume")]; static int zr_open(const char *path) { return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0); @@ -236,12 +266,12 @@ static int zr_mode(unsigned long *want) { n = zr_sys(SYS_read, fd, text, sizeof(text)); zr_sys(SYS_close, fd); } - if (n < 1 || text[0] < '0' || text[0] > '3') return -1; + if (n < 1 || text[0] < '0' || text[0] > '4') return -1; unsigned long kb = 0; for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++) kb = kb * 10 + (unsigned long)(text[i] - '0'); *want = kb / (zr_page / 1024); - if (text[0] >= '2' && *want == 0) return -1; + if ((text[0] == '2' || text[0] == '3') && *want == 0) return -1; return text[0] - '0'; } @@ -416,14 +446,14 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns return done; } -static void zr_ack(long value, int trim) { - const char *suffix = trim ? ".trim." : ".ack."; - char path[sizeof(zr_ctl) + sizeof(".trim.") + 20]; +static void zr_ack(long value, const char *suffix) { + char path[sizeof(zr_ctl) + sizeof(".restored.") + 20]; 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); + long pid = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE); + if (pid == 0) 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; @@ -435,23 +465,363 @@ static void zr_ack(long value, int trim) { zr_sys(SYS_close, fd); } +#if defined(__aarch64__) +static int zr_read_small(const char *path, char *text, long size) { + int fd = zr_open(path); + if (fd < 0) return 0; + long n; + do n = zr_sys(SYS_read, fd, text, size); while (n == -EINTR); + zr_sys(SYS_close, fd); + return n > 0 ? (int)n : 0; +} + +static void zr_nap(int *word, int value, long ms) { + struct { long sec, nsec; } wait = {ms / 1000, ms % 1000 * 1000000}; + zr_sys(SYS_futex, word, ZR_FUTEX_WAIT, value, &wait, NULL, 0); +} + +static long zr_now_ms(void) { + struct { long sec, nsec; } now = {0, 0}; + zr_sys(SYS_clock_gettime, CLOCK_MONOTONIC, &now); + return now.sec * 1000 + now.nsec / 1000000; +} + +static size_t zr_digits(char *out, long value) { + char digits[20]; + size_t d = 0, n = 0; + do digits[d++] = (char)('0' + value % 10); while ((value /= 10) > 0); + while (d > 0) out[n++] = digits[--d]; + return n; +} + +static int zr_seized_index(long tid) { + for (int i = 0; i < zr_seized; i++) + if (zr_tids[i] == tid) return i; + return -1; +} + +// Seizes and interrupts the owner's threads it has not seized yet; returns how many it added, or -1. +static long zr_seize_new(void) { + char path[48] = "/proc/"; + size_t n = 6 + zr_digits(path + 6, zr_owner); + for (const char *p = "/task"; *p; p++) path[n++] = *p; + path[n] = 0; + int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0); + if (fd < 0) return -1; + long added = 0, got; + while ((got = zr_sys(SYS_getdents64, fd, zr_maps, sizeof(zr_maps))) > 0) { + for (long at = 0; at < got;) { + unsigned short reclen = *(unsigned short *)(zr_maps + at + 16); + const char *name = zr_maps + at + 19; + at += reclen; + long tid = 0; + for (const char *p = name; *p >= '0' && *p <= '9'; p++) tid = tid * 10 + (*p - '0'); + if (tid <= 0 || tid == zr_reaper || zr_seized_index(tid) >= 0) continue; + if (zr_seized == ZR_SPILL_TIDS) { + added = -1; + break; + } + long r = zr_sys(SYS_ptrace, ZR_PTRACE_SEIZE, tid, 0, 0); + if (r == -ESRCH) continue; + if (r < 0) { + added = -1; + break; + } + zr_tids[zr_seized] = (int)tid; + zr_stopped[zr_seized++] = 0; + zr_sys(SYS_ptrace, ZR_PTRACE_INTERRUPT, tid, 0, 0); + added++; + } + if (added < 0) break; + } + zr_sys(SYS_close, fd); + return got < 0 ? -1 : added; +} + +static void zr_detach_all(void) { + for (int i = 0; i < zr_seized; i++) + if (zr_stopped[i] >= 0) zr_sys(SYS_ptrace, ZR_PTRACE_DETACH, zr_tids[i], 0, 0); + zr_seized = 0; +} + +// A thread stopped by ptrace stays stopped whatever its signal mask, and SIGCONT does not start it again: +// only the detach after the restore does. +static int zr_seize_all(void) { + zr_seized = 0; + long start = zr_now_ms(), added; + int idle = 0; + do { + added = zr_seize_new(); + if (added < 0) return 0; + for (;;) { + int status, waiting = 0; + long tid; + while ((tid = zr_sys(SYS_wait4, -1, &status, __WALL | WNOHANG, NULL)) > 0) { + int i = zr_seized_index(tid); + if (i >= 0) zr_stopped[i] = WIFSTOPPED(status) ? 1 : -1; + } + for (int i = 0; i < zr_seized; i++) waiting += zr_stopped[i] == 0; + if (waiting == 0) break; + if (zr_now_ms() - start >= ZR_PARK_MS) return 0; + zr_nap(&idle, 0, 2); + } + } while (added > 0); + return 1; +} + +// The spill must not drop the memory it runs on: the stacks, this file's state and the run index. +static int zr_own(unsigned long start, unsigned long end) { + const unsigned long marks[] = { + (unsigned long)zr_slots, (unsigned long)&zr_owner, (unsigned long)zr_maps, (unsigned long)zr_entries, + (unsigned long)zr_tids, (unsigned long)zr_stack, (unsigned long)zr_runs, (unsigned long)zr_helper_stack, + (unsigned long)zr_bounce, + }; + for (unsigned long i = 0; i < sizeof(marks) / sizeof(marks[0]); i++) + if (marks[i] >= start && marks[i] < end) return 1; + return 0; +} + +static int zr_flag(const char *flags, char a, char b) { + for (const char *p = flags; p[0] && p[1]; p++) + if (p[0] == a && p[1] == b && (p == flags || p[-1] == ' ') && (p[2] == ' ' || p[2] == 0 || p[2] == '\n')) + return 1; + return 0; +} + +// Private anonymous memory that can be read, whatever else its protection allows now. +static int zr_spillable(const char *line, unsigned long *start, unsigned long *end, int *writable) { + const char *p = line; + *start = zr_hex(&p); + if (*p++ != '-') return 0; + *end = zr_hex(&p); + if (*p++ != ' ' || p[0] != 'r' || p[3] != 'p') return 0; + *writable = p[1] == 'w'; + for (int field = 0; field < 4; field++) { + while (*p && *p != ' ') p++; + while (*p == ' ') p++; + } + return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[stack]") || zr_prefix(p, "[anon:"); +} + +static long zr_io(long call, int fd, unsigned long addr, unsigned long len, unsigned long off, int *direct) { + unsigned long done = 0; + while (done < len) { + unsigned long step = len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : len - done; + long n = zr_sys(call, fd, addr + done, step, off + done); + if (n == -EINTR) continue; + if (n == -EINVAL && *direct) { + long flags = zr_sys(SYS_fcntl, fd, F_GETFL); + if (flags < 0 || zr_sys(SYS_fcntl, fd, F_SETFL, flags & ~O_DIRECT) < 0) return -1; + *direct = 0; + continue; + } + if (n <= 0) return -1; + // f2fs on an encrypted volume may serve O_DIRECT through the page cache without saying so. + if (call == SYS_pwrite64) zr_sys(SYS_sync_file_range, fd, off + done, n, 7); + zr_sys(SYS_fadvise64, fd, off + done, n, 4); + done += (unsigned long)n; + } + return 0; +} + +// Pages that cannot be written in place go back through /proc//mem, which the tracer may write. +static int zr_restore_run(int fd, int mem, const struct zr_run *run, int *direct) { + if (run->writable) return (int)zr_io(SYS_pread64, fd, run->addr, run->len, run->off, direct); + for (unsigned long done = 0; done < run->len; done += ZR_SPILL_CHUNK) { + unsigned long step = run->len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : run->len - done; + if (mem < 0 || zr_io(SYS_pread64, fd, (unsigned long)zr_bounce, step, run->off + done, direct) < 0) return -1; + for (unsigned long put = 0; put < step;) { + long n = zr_sys(SYS_pwrite64, mem, zr_bounce + put, step - put, run->addr + done + put); + if (n == -EINTR) continue; + if (n <= 0) return -1; + put += (unsigned long)n; + } + } + return 0; +} + +static unsigned long zr_spill_range(int pagemap, int fd, unsigned long start, unsigned long end, int writable, + unsigned long *off, int *direct, int *full) { + unsigned long spilled = 0; + for (unsigned long addr = start; addr < end && !*full;) { + unsigned long count = (end - addr) / zr_page; + if (count > ZR_BATCH) count = ZR_BATCH; + if (zr_sys(SYS_lseek, pagemap, (long)(addr / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return spilled; + long got = zr_sys(SYS_read, pagemap, zr_entries, count * sizeof(uint64_t)); + if (got < (long)sizeof(uint64_t)) return spilled; + unsigned long pages = (unsigned long)got / sizeof(uint64_t); + for (unsigned long i = 0; i < pages && !*full;) { + if (!(zr_entries[i] & (ZR_PRESENT | ZR_SWAPPED))) { + i++; + continue; + } + unsigned long j = i; + while (j < pages && (zr_entries[j] & (ZR_PRESENT | ZR_SWAPPED))) j++; + unsigned long from = addr + i * zr_page, len = (j - i) * zr_page; + if (zr_run_count == ZR_SPILL_RUNS || zr_io(SYS_pwrite64, fd, from, len, *off, direct) < 0) { + *full = 1; + break; + } + zr_sys(SYS_madvise, from, len, MADV_DONTNEED); + zr_runs[zr_run_count++] = (struct zr_run){from, len, *off, (unsigned long)writable}; + *off += len; + spilled += len; + i = j; + } + addr += pages * zr_page; + } + return spilled; +} + +static unsigned long zr_spill_all(int fd, int *direct) { + int smaps = zr_open("/proc/self/smaps"); + int pagemap = zr_open("/proc/self/pagemap"); + unsigned long spilled = 0, off = 0, s = 0, e = 0; + int take = 0, full = 0, writable = 0; + size_t have = 0; + while (smaps >= 0 && pagemap >= 0 && !full) { + long n = zr_sys(SYS_read, smaps, zr_maps + have, sizeof(zr_maps) - 1 - have); + if (n == -EINTR) continue; + if (n <= 0) break; + have += (size_t)n; + zr_maps[have] = 0; + char *line = zr_maps, *nl; + while (!full && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) { + *nl = 0; + if ((line[0] >= '0' && line[0] <= '9') || (line[0] >= 'a' && line[0] <= 'f')) { + take = zr_spillable(line, &s, &e, &writable) && e > s && !zr_own(s, e); + } else if (take && zr_prefix(line, "VmFlags:")) { + const char *flags = line + 8; + if (!zr_flag(flags, 'u', 'm') && !zr_flag(flags, 'u', 'w') && !zr_flag(flags, 'l', 'o') && + !zr_flag(flags, 'i', 'o') && !zr_flag(flags, 'p', 'f')) + spilled += zr_spill_range(pagemap, fd, s, e, writable, &off, direct, &full); + take = 0; + } + line = nl + 1; + } + have -= (size_t)(line - zr_maps); + for (size_t i = 0; i < have; i++) zr_maps[i] = line[i]; + if (have == sizeof(zr_maps) - 1) have = 0; + } + if (pagemap >= 0) zr_sys(SYS_close, pagemap); + if (smaps >= 0) zr_sys(SYS_close, smaps); + return spilled; +} + +static int zr_spill_file(void) { + char path[sizeof(zr_ctl) + sizeof(".spill.") + 20]; + char digits[20]; + size_t n = 0, d = 0; + for (const char *p = zr_ctl; *p; p++) path[n++] = *p; + for (const char *p = ".spill."; *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; + int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_DIRECT, 0600); + if (fd >= 0) zr_sys(SYS_unlinkat, AT_FDCWD, path, 0); + return fd; +} + +static int zr_resumed(void) { + char now[sizeof(zr_baseline)]; + int got = zr_read_small(zr_resume, now, sizeof(now)); + if (got != zr_base_len) return 1; + for (int i = 0; i < got; i++) + if (now[i] != zr_baseline[i]) return 1; + return 0; +} + +// Runs in a process that shares the owner's memory, so it keeps running while every owner thread is stopped. +static void zr_helper(void) { + zr_sys(SYS_prctl, PR_SET_NAME, "zr-spill"); + if (!zr_seize_all()) { + zr_detach_all(); + return; + } + int fd = zr_spill_file(); + if (fd < 0) { + zr_detach_all(); + return; + } + int direct = 1, idle = 0; + zr_run_count = 0; + unsigned long spilled = zr_spill_all(fd, &direct); + zr_helper_done = 1; + zr_ack((long)(spilled / 1024), ".ack."); + if (spilled > 0) { + while (!zr_resumed()) zr_nap(&idle, 0, ZR_RESUME_POLL_MS); + long start = zr_now_ms(); + char path[48] = "/proc/"; + size_t n = 6 + zr_digits(path + 6, zr_owner); + for (const char *p = "/mem"; *p; p++) path[n++] = *p; + path[n] = 0; + int mem = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CLOEXEC, 0); + for (unsigned long i = 0; i < zr_run_count; i++) { + if (zr_restore_run(fd, mem, &zr_runs[i], &direct) < 0) zr_sys(SYS_kill, zr_owner, SIGKILL); + } + if (mem >= 0) zr_sys(SYS_close, mem); + zr_ack(zr_now_ms() - start, ".restored."); + } + zr_sys(SYS_close, fd); + zr_detach_all(); +} + +static void *zr_area(unsigned long len) { + long area = zr_sys(ZR_MMAP, 0, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); + if ((unsigned long)area > -4096UL) return NULL; + zr_name(area, len); + return (void *)area; +} + +static int zr_spill(void) { + if (zr_runs == NULL) zr_runs = zr_area(ZR_SPILL_RUNS * sizeof(struct zr_run)); + if (zr_helper_stack == NULL) zr_helper_stack = zr_area(ZR_STACK); + if (zr_bounce == NULL) zr_bounce = zr_area(ZR_SPILL_CHUNK); + if (zr_runs == NULL || zr_helper_stack == NULL || zr_bounce == NULL) return 0; + zr_base_len = zr_read_small(zr_resume, zr_baseline, sizeof(zr_baseline)); + zr_helper_done = 0; + zr_reaper = zr_sys(SYS_gettid); + __atomic_store_n(&zr_owner, zr_sys(SYS_getpid), __ATOMIC_RELEASE); + long child = zr_clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM, zr_helper_stack + ZR_STACK, NULL, NULL, NULL); + if (child > 0) { + int status; + while (zr_sys(SYS_wait4, child, &status, __WALL, NULL) == -EINTR) { + } + } + __atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE); + return child > 0 && zr_helper_done; +} +#endif + static void zr_request(int worker) { unsigned long want = 0; int mode = zr_mode(&want); if (mode < 0) return; + if (mode == 4) { + zr_ack(-1, ".ack."); +#if defined(__aarch64__) + if (worker && zr_spill()) return; +#endif + zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS; + zr_walk(1, 1, 0, 0); + zr_gen++; + zr_ack(0, ".ack."); + return; + } if (!worker && want > ZR_INLINE_KB / (zr_page / 1024)) want = ZR_INLINE_KB / (zr_page / 1024); zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS; - if (mode > 0) zr_ack(-1, mode > 1); + if (mode > 0) zr_ack(-1, mode > 1 ? ".trim." : ".ack."); if (mode < 2) { zr_walk(mode, 1, 0, 0); zr_gen++; - if (mode == 1) zr_ack(1, 0); + if (mode == 1) zr_ack(1, ".ack."); return; } unsigned long from = zr_cursor; unsigned long done = zr_walk(mode, want, from, ~0UL); if (done < want && from > 0) done += zr_walk(mode, want - done, 0, from); - zr_ack((long)(done * (zr_page / 1024)), 1); + zr_ack((long)(done * (zr_page / 1024)), ".trim."); } static void zr_drain(int worker) { @@ -463,6 +833,13 @@ static void zr_drain(int worker) { } void zr_thread(void) { +#if defined(__aarch64__) + long owner = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE); + if (owner != 0 && zr_sys(SYS_getpid) != owner) { + zr_helper(); + return; + } +#endif zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker"); zr_drain(1); } @@ -520,6 +897,7 @@ static int zr_start(void) { MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0); if ((unsigned long)base > -4096UL) return 0; zr_stack = (char *)base; + zr_name(base, ZR_STACK); } struct { long sec, nsec; } wait = {0, 5000000}; for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++) @@ -548,6 +926,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) { } static void zr_child(void) { + __atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE); __atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE); __atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE); } @@ -564,6 +943,8 @@ static void zr_paths(void) { size_t n = strlen(zr_ctl); memcpy(zr_hold, zr_ctl, n); memcpy(zr_hold + n, ".hold", sizeof(".hold")); + memcpy(zr_resume, zr_ctl, n); + memcpy(zr_resume + n, ".resume", sizeof(".resume")); } __attribute__((constructor)) static void zr_init(void) { diff --git a/tools/tests/test_zram_spill_preload.py b/tools/tests/test_zram_spill_preload.py new file mode 100644 index 0000000000..e7fdd48893 --- /dev/null +++ b/tools/tests/test_zram_spill_preload.py @@ -0,0 +1,216 @@ +import os +from pathlib import Path +import platform +import shutil +import subprocess +import tempfile +import unittest + +PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" + +PROGRAM = r""" +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define THREADS 4 + +struct shared { + volatile long progress; + volatile long errors; + volatile int stop; +}; + +static const char *ctl; +static size_t size; +static int block_urg; +static struct shared *shared; +static unsigned char *blocks[THREADS]; + +static void fill(unsigned char *p, size_t n, unsigned seed) { + for (size_t i = 0; i < n; i++) p[i] = (unsigned char)((i * 2654435761u + seed) >> 7); +} + +static int same(const unsigned char *p, size_t n, unsigned seed) { + for (size_t i = 0; i < n; i += 61) + if (p[i] != (unsigned char)((i * 2654435761u + seed) >> 7)) return 0; + return 1; +} + +static void *work(void *arg) { + long id = (long)arg; + if (block_urg && id == 0) { + sigset_t set; + sigfillset(&set); + pthread_sigmask(SIG_BLOCK, &set, NULL); + } + unsigned seed = (unsigned)id * 77u + 1u; + while (!shared->stop) { + if (!same(blocks[id], size, seed)) __atomic_add_fetch(&shared->errors, 1, __ATOMIC_RELAXED); + __atomic_add_fetch(&shared->progress, 1, __ATOMIC_RELAXED); + } + return NULL; +} + +static void put(const char *suffix, const char *text) { + char path[512]; + snprintf(path, sizeof(path), "%s%s", ctl, suffix); + FILE *f = fopen(path, "w"); + if (!f) exit(20); + fputs(text, f); + fclose(f); +} + +static long get(const char *suffix, pid_t pid) { + char path[512], text[32] = {0}; + snprintf(path, sizeof(path), "%s%s%d", ctl, suffix, pid); + FILE *f = fopen(path, "r"); + if (!f) return -2; + size_t n = fread(text, 1, sizeof(text) - 1, f); + fclose(f); + return n == 0 ? -1 : atol(text); +} + +static long rss_kb(pid_t pid) { + char path[64], line[256]; + long kb = -1; + snprintf(path, sizeof(path), "/proc/%d/status", pid); + FILE *f = fopen(path, "r"); + while (f && fgets(line, sizeof(line), f)) + if (!strncmp(line, "VmRSS:", 6)) kb = atol(line + 6); + if (f) fclose(f); + return kb; +} + +static void nap(long ms) { + struct timespec t = {ms / 1000, ms % 1000 * 1000000}; + nanosleep(&t, NULL); +} + +static long wait_for(const char *suffix, pid_t pid, long ms) { + for (long waited = 0; waited < ms; waited += 20) { + long v = get(suffix, pid); + if (v >= 0) return v; + nap(20); + } + return -3; +} + +int main(int argc, char **argv) { + ctl = argv[1]; + size = (size_t)atol(argv[2]) << 20; + block_urg = argc > 3 && !strcmp(argv[3], "block"); + if (argc > 3 && !strcmp(argv[3], "undumpable")) prctl(PR_SET_DUMPABLE, 0); + shared = mmap(NULL, sizeof(*shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); + if (shared == MAP_FAILED) return 2; + char resume[512]; + snprintf(resume, sizeof(resume), "%s.resume", ctl); + unlink(resume); + put(".hold", ""); + for (int i = 0; i < THREADS; i++) { + blocks[i] = i % 2 ? malloc(size) : mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (!blocks[i] || blocks[i] == MAP_FAILED) return 3; + fill(blocks[i], size, (unsigned)i * 77u + 1u); + } + if (mprotect(blocks[2], size, PROT_READ) != 0) return 4; + pid_t child = fork(); + if (child == 0) { + pthread_t t[THREADS]; + for (long i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, work, (void *)i); + for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL); + _exit(0); + } + while (shared->progress < 50) nap(10); + long before = rss_kb(child); + put(".hold", "4"); + kill(child, SIGURG); + long spilled = wait_for(".ack.", child, 20000); + long after = rss_kb(child); + long frozen_at = shared->progress; + nap(500); + long frozen_now = shared->progress; + put(".resume", "1"); + long restored = spilled > 0 ? wait_for(".restored.", child, 20000) : 0; + nap(300); + long resumed = shared->progress; + long back = rss_kb(child); + shared->stop = 1; + int status = 0; + waitpid(child, &status, 0); + printf("before=%ld after=%ld back=%ld spilled=%ld restored=%ld frozen=%ld resumed=%ld errors=%ld exit=%d\n", + before, after, back, spilled, restored, frozen_now - frozen_at, resumed - frozen_now, shared->errors, + WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status)); + return 0; +} +""" + + +def _fields(text): + return {k: int(v) for k, v in (part.split("=") for part in text.split())} + + +@unittest.skipUnless(platform.machine() == "aarch64" and shutil.which("cc"), "the spill runs only on arm64") +class ZramSpillPreloadTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dir = Path(tempfile.mkdtemp()) + cls.ctl = cls.dir / "ctl" + lib = cls.dir / "libzram.so" + prog = cls.dir / "spill" + (cls.dir / "spill.c").write_text(PROGRAM) + subprocess.run(["cc", "-O2", "-shared", "-fPIC", f'-DZR_CTL="{cls.ctl}"', "-o", str(lib), + str(PRELOAD / "zram.c")], check=True) + subprocess.run(["cc", "-O2", "-pthread", "-o", str(prog), str(cls.dir / "spill.c")], check=True) + cls.lib, cls.prog = lib, prog + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.dir, ignore_errors=True) + + def run_spill(self, *extra): + self.ctl.write_text("0") + env = dict(os.environ, LD_PRELOAD=str(self.lib)) + env.pop("DDNATV_ROOT", None) + out = subprocess.run([str(self.prog), str(self.ctl), "64", *extra], env=env, check=True, + capture_output=True, text=True, timeout=90).stdout + return _fields(out) + + def test_spills_to_disk_holds_every_thread_and_restores_intact(self): + r = self.run_spill() + self.assertEqual(r["exit"], 0) + self.assertGreater(r["spilled"], 200 * 1024) + self.assertLess(r["after"], r["before"] - 200 * 1024) + self.assertEqual(r["frozen"], 0) + self.assertGreaterEqual(r["restored"], 0) + self.assertGreater(r["resumed"], 0) + self.assertEqual(r["errors"], 0) + + def test_a_thread_that_blocks_every_signal_is_held_too(self): + r = self.run_spill("block") + self.assertEqual(r["exit"], 0) + self.assertGreater(r["spilled"], 200 * 1024) + self.assertEqual(r["frozen"], 0) + self.assertGreater(r["resumed"], 0) + self.assertEqual(r["errors"], 0) + + def test_a_process_that_cannot_be_traced_falls_back_to_zram(self): + r = self.run_spill("undumpable") + self.assertEqual(r["exit"], 0) + self.assertEqual(r["spilled"], 0) + self.assertGreater(r["resumed"], 0) + self.assertEqual(r["errors"], 0) + + +if __name__ == "__main__": + unittest.main()