mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Bind a spill to the resume count it was asked under and report a resume only once memory is back
This commit is contained in:
1 parent
ad6bb159d3
commit
f17406effc
5 files changed
+111
-35
No files matched your search
@@ -977,7 +977,7 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.paged_out", mapOf(
|
||||
"processes" to processes, "unacknowledged" to unacknowledged, "residentMb" to residentKb / 1024,
|
||||
"swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024, "ms" to millis,
|
||||
))
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
|
||||
@@ -990,7 +990,7 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.paged_in", mapOf(
|
||||
"processes" to processes, "swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024,
|
||||
"availableMb" to availableKb / 1024, "ms" to millis,
|
||||
))
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
spilled = { processes, spilledKb, residentKb, millis ->
|
||||
@@ -1000,7 +1000,7 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.spilled", mapOf(
|
||||
"processes" to processes, "spilledMb" to spilledKb / 1024, "residentMb" to residentKb / 1024,
|
||||
"ms" to millis,
|
||||
))
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
restored = { processes, unacknowledged, residentKb, millis ->
|
||||
@@ -1010,7 +1010,7 @@ class SessionService : Service() {
|
||||
SessionEvents.record("session.restored", mapOf(
|
||||
"processes" to processes, "unacknowledged" to unacknowledged,
|
||||
"residentMb" to residentKb / 1024, "ms" to millis,
|
||||
))
|
||||
), sessionDir)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -129,7 +129,8 @@ internal class SessionSuspendController(
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restoreSafely(records)
|
||||
if (resumed) frozen = emptyList()
|
||||
completion(resumed)
|
||||
// a spilled process runs again only once its helper has read its memory back
|
||||
completion(resumed && awaitRestored())
|
||||
if (resumed) readBack()
|
||||
}, { completion(false) })
|
||||
}
|
||||
@@ -282,7 +283,9 @@ internal class SessionSuspendController(
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return
|
||||
val hold = holdFile(control)
|
||||
try {
|
||||
hold.writeText(if (spill) SPILL_REQUEST else PAGE_OUT_REQUEST)
|
||||
// A spill names the resume count it was asked under: any later count releases the helper, however
|
||||
// late it starts reading.
|
||||
hold.writeText(if (spill) "$SPILL_REQUEST ${resumeCount(control)}" else PAGE_OUT_REQUEST)
|
||||
sleep(PAGE_OUT_POLL_MS)
|
||||
if (spill) spill(control, records, root, helpers) else pageOut(control, records, root, helpers)
|
||||
} catch (_: IOException) {
|
||||
@@ -338,21 +341,33 @@ internal class SessionSuspendController(
|
||||
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
|
||||
private fun resumeFile(control: File) = File(control.parentFile, "${control.name}.resume")
|
||||
|
||||
private fun resumeCount(control: File): Long = try {
|
||||
resumeFile(control).takeIf { it.isFile }?.readText()?.trim()?.toLongOrNull() ?: 0L
|
||||
} catch (_: IOException) {
|
||||
0L
|
||||
}
|
||||
|
||||
// False when a spilled process's helper may not have seen the new count: it would stay stopped.
|
||||
private fun bumpResume(): Boolean {
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return spilledTargets.isEmpty()
|
||||
val counter = resumeFile(control)
|
||||
return try {
|
||||
val next = resumeCount(control) + 1
|
||||
counter.writeText(next.toString())
|
||||
resumeCount(control) == next
|
||||
} catch (_: IOException) {
|
||||
spilledTargets.isEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
private fun awaitRestored() {
|
||||
// True when every spilled process has its memory back (or is gone).
|
||||
private fun awaitRestored(): Boolean {
|
||||
val targets = spilledTargets
|
||||
spilledTargets = emptyList()
|
||||
val control = zramControl ?: return
|
||||
if (targets.isEmpty()) return
|
||||
val control = zramControl ?: return true
|
||||
if (targets.isEmpty()) return true
|
||||
val start = nowMillis()
|
||||
val waiting = targets.toMutableList()
|
||||
try {
|
||||
@@ -366,6 +381,7 @@ internal class SessionSuspendController(
|
||||
}
|
||||
targets.forEach { ackFile(control, "restored", it).delete() }
|
||||
restored(targets.size, waiting.size, memoryKb(targets).first, nowMillis() - start)
|
||||
return waiting.isEmpty()
|
||||
}
|
||||
|
||||
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
|
||||
@@ -504,7 +520,7 @@ internal class SessionSuspendController(
|
||||
Role.HELPER_CHILD -> 3
|
||||
}
|
||||
}
|
||||
bumpResume()
|
||||
if (!bumpResume()) return false
|
||||
for (record in ordered) send(record, SIGCONT)
|
||||
val waiting = ordered.toMutableList()
|
||||
repeat(RESTORE_CHECKS) { check ->
|
||||
|
||||
@@ -128,7 +128,7 @@ class SessionSuspendControllerTest {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
assertEquals(listOf<String?>("4"), fixture.held)
|
||||
assertEquals(listOf<String?>("4 0"), 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())
|
||||
@@ -142,7 +142,15 @@ class SessionSuspendControllerTest {
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
var called = false
|
||||
fixture.controller.resume {
|
||||
// success is reported once the guest has its memory back and has left its tracing stop
|
||||
assertTrue(it)
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' })
|
||||
called = true
|
||||
}
|
||||
assertTrue(called)
|
||||
assertEquals(listOf<String?>("1"), fixture.resumeAtContinue)
|
||||
assertFalse(fixture.signals.drop(before).any { it.signal == URG })
|
||||
assertEquals(listOf(1 to 0), fixture.restores)
|
||||
@@ -581,6 +589,7 @@ class SessionSuspendControllerTest {
|
||||
private var spilling = false
|
||||
private var spilledBase: String? = null
|
||||
private var restoring = false
|
||||
private var continuedAt = 0L
|
||||
private val resume = File(tmp, ".dd-zram.resume")
|
||||
private var continuing = false
|
||||
val controller = SessionSuspendController(
|
||||
@@ -613,7 +622,10 @@ class SessionSuspendControllerTest {
|
||||
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
|
||||
}?.state = 't'
|
||||
} else if (signal == URG) {
|
||||
if (request == "4") spilling = true
|
||||
if (request?.startsWith("4") == true) {
|
||||
spilling = true
|
||||
spilledBase = request.substringAfter(' ', "0").trim()
|
||||
}
|
||||
else if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
|
||||
} else if (signal == CONT) {
|
||||
if (pid == GAME) resumeAtContinue += resume.takeIf { it.isFile }?.readText()
|
||||
@@ -621,7 +633,9 @@ class SessionSuspendControllerTest {
|
||||
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
|
||||
}
|
||||
continuing = true
|
||||
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
|
||||
if (pid == GAME && restoring) continuedAt = now
|
||||
// a spilled guest stays in its tracing stop until its helper has read the memory back
|
||||
if (!(pid == GAME && (blockGameContinue || restoring))) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
|
||||
}
|
||||
sync()
|
||||
}
|
||||
@@ -645,15 +659,16 @@ class SessionSuspendControllerTest {
|
||||
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) {
|
||||
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
|
||||
if (restoring && continuing && count != spilledBase && now - continuedAt >= RESTORE_DELAY_MS) {
|
||||
restoring = false
|
||||
gameResidentKb = 4_000_000L
|
||||
game.threads.forEach { if (it.state != 'Z') it.state = 'S' }
|
||||
File(control.parentFile, "${control.name}.restored.$GAME").writeText("120")
|
||||
}
|
||||
if (pagingOut && !handlerReplaced) {
|
||||
@@ -744,5 +759,6 @@ class SessionSuspendControllerTest {
|
||||
const val STOP = 19
|
||||
const val CONT = 18
|
||||
const val URG = 23
|
||||
const val RESTORE_DELAY_MS = 300L
|
||||
}
|
||||
}
|
||||
@@ -224,8 +224,8 @@ 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 unsigned long zr_helper_spilled;
|
||||
static unsigned long zr_baseline; // the resume count the spill was asked under
|
||||
|
||||
static int zr_prefix(const char *text, const char *prefix) {
|
||||
while (*prefix)
|
||||
@@ -252,6 +252,9 @@ static int zr_open(const char *path) {
|
||||
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
|
||||
}
|
||||
|
||||
// The number after a request's mode: kB to trim, or for a spill the resume count it was asked under.
|
||||
static unsigned long zr_request_arg;
|
||||
|
||||
static int zr_mode(unsigned long *want) {
|
||||
char text[24];
|
||||
long n = 0;
|
||||
@@ -270,6 +273,7 @@ static int zr_mode(unsigned long *want) {
|
||||
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');
|
||||
zr_request_arg = kb;
|
||||
*want = kb / (zr_page / 1024);
|
||||
if ((text[0] == '2' || text[0] == '3') && *want == 0) return -1;
|
||||
return text[0] - '0';
|
||||
@@ -692,8 +696,9 @@ static unsigned long zr_spill_all(int fd, int *direct) {
|
||||
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;
|
||||
// Tagged memory (mt) stays: dropping its pages drops the tags, which reading the bytes back cannot restore.
|
||||
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'))
|
||||
!zr_flag(flags, 'i', 'o') && !zr_flag(flags, 'p', 'f') && !zr_flag(flags, 'm', 't'))
|
||||
spilled += zr_spill_range(pagemap, fd, s, e, writable, &off, direct, &full);
|
||||
take = 0;
|
||||
}
|
||||
@@ -723,13 +728,14 @@ static int zr_spill_file(void) {
|
||||
return fd;
|
||||
}
|
||||
|
||||
// A count other than the request's; a marker that cannot be read is no resume.
|
||||
static int zr_resumed(void) {
|
||||
char now[sizeof(zr_baseline)];
|
||||
char now[24];
|
||||
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;
|
||||
unsigned long count = 0;
|
||||
int digits = 0;
|
||||
for (int i = 0; i < got && now[i] >= '0' && now[i] <= '9'; i++, digits++) count = count * 10 + (unsigned long)(now[i] - '0');
|
||||
return digits > 0 && count != zr_baseline;
|
||||
}
|
||||
|
||||
// Runs in a process that shares the owner's memory, so it keeps running while every owner thread is stopped.
|
||||
@@ -747,9 +753,11 @@ static void zr_helper(void) {
|
||||
int direct = 1, idle = 0;
|
||||
zr_run_count = 0;
|
||||
unsigned long spilled = zr_spill_all(fd, &direct);
|
||||
zr_helper_spilled = spilled;
|
||||
zr_helper_done = 1;
|
||||
zr_ack((long)(spilled / 1024), ".ack.");
|
||||
// nothing written (a full volume): the owner pages out to zram instead and acknowledges that
|
||||
if (spilled > 0) {
|
||||
zr_ack((long)(spilled / 1024), ".ack.");
|
||||
while (!zr_resumed()) zr_nap(&idle, 0, ZR_RESUME_POLL_MS);
|
||||
long start = zr_now_ms();
|
||||
char path[48] = "/proc/";
|
||||
@@ -757,11 +765,15 @@ static void zr_helper(void) {
|
||||
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);
|
||||
int restored = 1;
|
||||
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 (zr_restore_run(fd, mem, &zr_runs[i], &direct) < 0) {
|
||||
zr_sys(SYS_kill, zr_owner, SIGKILL);
|
||||
restored = 0;
|
||||
}
|
||||
}
|
||||
if (mem >= 0) zr_sys(SYS_close, mem);
|
||||
zr_ack(zr_now_ms() - start, ".restored.");
|
||||
if (restored) zr_ack(zr_now_ms() - start, ".restored.");
|
||||
}
|
||||
zr_sys(SYS_close, fd);
|
||||
zr_detach_all();
|
||||
@@ -779,8 +791,9 @@ static int zr_spill(void) {
|
||||
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_baseline = zr_request_arg;
|
||||
zr_helper_done = 0;
|
||||
zr_helper_spilled = 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);
|
||||
@@ -790,7 +803,7 @@ static int zr_spill(void) {
|
||||
}
|
||||
}
|
||||
__atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE);
|
||||
return child > 0 && zr_helper_done;
|
||||
return child > 0 && zr_helper_done && zr_helper_spilled > 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ PROGRAM = r"""
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/ptrace.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
@@ -108,6 +109,24 @@ static long wait_for(const char *suffix, pid_t pid, long ms) {
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc > 1 && !strcmp(argv[1], "probe")) {
|
||||
// whether a child may seize its parent, as the spill helper does (Yama's ptrace_scope 1 refuses)
|
||||
pid_t parent = getpid(), probe = fork();
|
||||
if (probe == 0) _exit(ptrace(PTRACE_SEIZE, parent, 0, 0) == 0 ? 0 : 1);
|
||||
int status = 0;
|
||||
waitpid(probe, &status, 0);
|
||||
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
|
||||
}
|
||||
if (argc > 1 && !strcmp(argv[1], "pageout")) {
|
||||
// whether this host pages anonymous memory out at all (swap, and a kernel that is not emulated)
|
||||
size_t n = 64u << 20;
|
||||
unsigned char *p = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (p == MAP_FAILED) return 1;
|
||||
fill(p, n, 3);
|
||||
long before = rss_kb(getpid());
|
||||
madvise(p, n, 21 /* MADV_PAGEOUT */);
|
||||
return rss_kb(getpid()) < before - 32 * 1024 ? 0 : 1;
|
||||
}
|
||||
ctl = argv[1];
|
||||
size = (size_t)atol(argv[2]) << 20;
|
||||
block_urg = argc > 3 && !strcmp(argv[3], "block");
|
||||
@@ -133,7 +152,7 @@ int main(int argc, char **argv) {
|
||||
}
|
||||
while (shared->progress < 50) nap(10);
|
||||
long before = rss_kb(child);
|
||||
put(".hold", "4");
|
||||
put(".hold", "4 0");
|
||||
kill(child, SIGURG);
|
||||
long spilled = wait_for(".ack.", child, 20000);
|
||||
long after = rss_kb(child);
|
||||
@@ -173,6 +192,12 @@ class ZramSpillPreloadTest(unittest.TestCase):
|
||||
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
|
||||
cls.can_trace = subprocess.run([str(prog), "probe"]).returncode == 0
|
||||
cls.can_page_out = subprocess.run([str(prog), "pageout"]).returncode == 0
|
||||
|
||||
def need_tracing(self):
|
||||
if not self.can_trace:
|
||||
self.skipTest("this host does not let a child seize its parent (Yama ptrace_scope)")
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
@@ -187,6 +212,7 @@ class ZramSpillPreloadTest(unittest.TestCase):
|
||||
return _fields(out)
|
||||
|
||||
def test_spills_to_disk_holds_every_thread_and_restores_intact(self):
|
||||
self.need_tracing()
|
||||
r = self.run_spill()
|
||||
self.assertEqual(r["exit"], 0)
|
||||
self.assertGreater(r["spilled"], 200 * 1024)
|
||||
@@ -197,6 +223,7 @@ class ZramSpillPreloadTest(unittest.TestCase):
|
||||
self.assertEqual(r["errors"], 0)
|
||||
|
||||
def test_a_thread_that_blocks_every_signal_is_held_too(self):
|
||||
self.need_tracing()
|
||||
r = self.run_spill("block")
|
||||
self.assertEqual(r["exit"], 0)
|
||||
self.assertGreater(r["spilled"], 200 * 1024)
|
||||
@@ -208,6 +235,10 @@ class ZramSpillPreloadTest(unittest.TestCase):
|
||||
r = self.run_spill("undumpable")
|
||||
self.assertEqual(r["exit"], 0)
|
||||
self.assertEqual(r["spilled"], 0)
|
||||
# the fallback pages out to zram before it answers: where the host can page out, the resident set
|
||||
# has shrunk by then
|
||||
if self.can_page_out:
|
||||
self.assertLess(r["after"], r["before"] - 64 * 1024)
|
||||
self.assertGreater(r["resumed"], 0)
|
||||
self.assertEqual(r["errors"], 0)
|
||||
|
||||
|
||||
Reference in new issue
Block a user