mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
fix(session): keep a suspended session resident until memory runs short
This commit is contained in:
1 parent
3dac3ed47c
commit
0d7175ea9a
4 files changed
+176
-30
No files matched your search
@@ -926,6 +926,7 @@ class SessionService : Service() {
|
||||
))
|
||||
}
|
||||
},
|
||||
schedule = { delay, task -> mainHandler.postDelayed({ task() }, delay) },
|
||||
)
|
||||
updateDownloadMonitoring()
|
||||
mainHandler.post { updateSuspendPolicy() }
|
||||
|
||||
@@ -29,6 +29,7 @@ internal class SessionSuspendController(
|
||||
{ _, _, _, _, _, _ -> },
|
||||
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
|
||||
{ _, _, _, _, _ -> },
|
||||
private val schedule: (Long, () -> Unit) -> Unit = { _, _ -> },
|
||||
) {
|
||||
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
|
||||
|
||||
@@ -53,6 +54,7 @@ internal class SessionSuspendController(
|
||||
private var frozen = emptyList<ProcessRecord>()
|
||||
private var frozenSince: Long? = null
|
||||
private var pagedOutTargets = emptyList<ProcessRecord>()
|
||||
private var pageOutChecks = 0
|
||||
|
||||
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
|
||||
cancelled = false
|
||||
@@ -60,6 +62,7 @@ internal class SessionSuspendController(
|
||||
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
|
||||
var complete = false
|
||||
var interrupted = false
|
||||
var deferred = false
|
||||
try {
|
||||
val root = records.values.firstOrNull { it.role == Role.SESSION_ROOT }
|
||||
?: readProcess(sessionRoot())?.takeIf { it.pid > 1 }?.let {
|
||||
@@ -74,29 +77,10 @@ internal class SessionSuspendController(
|
||||
records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT)
|
||||
}
|
||||
}
|
||||
if (pageOut) pageOut(records, root.pid, helpers)
|
||||
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
|
||||
var previous: Map<TaskIdentity, Long>? = null
|
||||
for (pass in 0 until FREEZE_MAX_PASSES) {
|
||||
if (closing || cancelled || nowMillis() >= deadline) break
|
||||
try {
|
||||
if (readProcess(root.pid)?.started != root.started) break
|
||||
addSnapshot(records, root.pid, helpers)
|
||||
if (readProcess(root.pid)?.started != root.started) break
|
||||
stop(records.values.toList())
|
||||
sleep(if (pass == 0) 70L else 35L)
|
||||
if (closing || cancelled || nowMillis() >= deadline) break
|
||||
val current = stoppedSnapshot(records.values.toList(), root)
|
||||
if (current != null && current == previous) {
|
||||
complete = true
|
||||
break
|
||||
}
|
||||
previous = current
|
||||
} catch (_: IOException) {
|
||||
previous = null
|
||||
sleep(35L)
|
||||
}
|
||||
}
|
||||
val pageOutNow = pageOut && memoryShort()
|
||||
if (pageOutNow) pageOut(records, root.pid, helpers)
|
||||
deferred = pageOut && !pageOutNow && zramControl?.isFile == true
|
||||
complete = stopUntilStable(records, root, helpers)
|
||||
} catch (_: InterruptedException) {
|
||||
interrupted = true
|
||||
Thread.interrupted()
|
||||
@@ -111,16 +95,79 @@ internal class SessionSuspendController(
|
||||
if (interrupted) Thread.currentThread().interrupt()
|
||||
}
|
||||
completion(complete)
|
||||
if (complete && deferred) checkPageOut(++pageOutChecks)
|
||||
if (!complete && frozen.isEmpty() && !interrupted) readBack()
|
||||
}, { completion(false) })
|
||||
}
|
||||
|
||||
private fun stopUntilStable(
|
||||
records: MutableMap<Pair<Int, Long>, ProcessRecord>,
|
||||
root: ProcessRecord,
|
||||
helpers: List<Int>,
|
||||
): Boolean {
|
||||
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
|
||||
var previous: Map<TaskIdentity, Long>? = null
|
||||
for (pass in 0 until FREEZE_MAX_PASSES) {
|
||||
if (closing || cancelled || nowMillis() >= deadline) return false
|
||||
try {
|
||||
if (readProcess(root.pid)?.started != root.started) return false
|
||||
addSnapshot(records, root.pid, helpers)
|
||||
if (readProcess(root.pid)?.started != root.started) return false
|
||||
stop(records.values.toList())
|
||||
sleep(if (pass == 0) 70L else 35L)
|
||||
if (closing || cancelled || nowMillis() >= deadline) return false
|
||||
val current = stoppedSnapshot(records.values.toList(), root)
|
||||
if (current != null && current == previous) return true
|
||||
previous = current
|
||||
} catch (_: IOException) {
|
||||
previous = null
|
||||
sleep(35L)
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun checkPageOut(check: Int) {
|
||||
schedule(PAGE_OUT_CHECK_MS) { submit({ pageOutIfShort(check) }, {}) }
|
||||
}
|
||||
|
||||
private fun pageOutIfShort(check: Int) {
|
||||
if (check != pageOutChecks || closing || cancelled || frozen.isEmpty()) return
|
||||
if (!memoryShort()) return checkPageOut(check)
|
||||
pageOutChecks++
|
||||
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
|
||||
val root = records.values.firstOrNull { it.role == Role.SESSION_ROOT } ?: return
|
||||
val helpers = records.values.filter { it.role == Role.HELPER_ROOT }.map { it.pid }
|
||||
advanceClock()
|
||||
try {
|
||||
restore(records.values.toList())
|
||||
pageOut(records, root.pid, helpers)
|
||||
stopUntilStable(records, root, helpers)
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
} catch (_: Exception) {
|
||||
} finally {
|
||||
stop(records.values.toList())
|
||||
frozen = records.values.toList()
|
||||
frozenSince = nowNanos()
|
||||
}
|
||||
}
|
||||
|
||||
private fun memoryShort(): Boolean {
|
||||
val (total, available) = meminfoKb()
|
||||
return available < reserveKb(total) * PAGE_OUT_RESERVES
|
||||
}
|
||||
|
||||
private fun reserveKb(totalKb: Long) = maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE)
|
||||
|
||||
fun cancelFreeze() {
|
||||
cancelled = true
|
||||
}
|
||||
|
||||
fun resume(completion: (Boolean) -> Unit) {
|
||||
cancelled = true
|
||||
submit({
|
||||
pageOutChecks++
|
||||
val records = frozen
|
||||
advanceClock()
|
||||
runAudio(resumeAudio)
|
||||
@@ -372,7 +419,7 @@ internal class SessionSuspendController(
|
||||
private fun readBackTargets(swapKb: Map<ProcessRecord, Long>, totalKb: Long, availableKb: Long): List<ProcessRecord> {
|
||||
var budget = minOf(
|
||||
availableKb / READ_BACK_AVAILABLE_FACTOR,
|
||||
availableKb - maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE),
|
||||
availableKb - reserveKb(totalKb),
|
||||
)
|
||||
val chosen = ArrayList<ProcessRecord>()
|
||||
for ((record, swap) in swapKb.entries.sortedByDescending { it.value }) {
|
||||
@@ -497,6 +544,8 @@ internal class SessionSuspendController(
|
||||
const val PAGE_OUT_POLL_MS = 100L
|
||||
const val PAGE_OUT_START_MS = 2_000L
|
||||
const val PAGE_OUT_TIMEOUT_MS = 12_000L
|
||||
const val PAGE_OUT_CHECK_MS = 10_000L
|
||||
const val PAGE_OUT_RESERVES = 2L
|
||||
const val READ_BACK_POLL_MS = 100L
|
||||
const val READ_BACK_STABLE_POLLS = 5
|
||||
const val READ_BACK_TIMEOUT_MS = 5_000L
|
||||
|
||||
@@ -138,6 +138,79 @@ class SessionSuspendControllerTest {
|
||||
assertEquals(listOf<String?>("1", "2 0"), fixture.shared)
|
||||
}
|
||||
|
||||
@Test fun aSuspendWithMemoryToSpareKeepsTheSessionResident() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.availableWhileSuspendedKb = 8_000_000L
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
assertFalse(fixture.signals.any { it.signal == URG })
|
||||
assertTrue(fixture.pagedOut.isEmpty())
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
assertEquals(listOf(10_000L), fixture.scheduled.map { it.first })
|
||||
fixture.runScheduled()
|
||||
assertFalse(fixture.signals.any { it.signal == URG || it.signal == CONT })
|
||||
assertEquals(1, fixture.scheduled.size)
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.signals.any { it.signal == URG })
|
||||
assertTrue(fixture.pagedIn.isEmpty())
|
||||
fixture.runScheduled()
|
||||
assertTrue(fixture.scheduled.isEmpty())
|
||||
assertTrue(fixture.game.threads.all { it.state == 'S' })
|
||||
}
|
||||
|
||||
@Test fun aSuspendedSessionIsPagedOutOnceMemoryRunsShort() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.clock.writeBytes(shift(0L))
|
||||
fixture.availableWhileSuspendedKb = 8_000_000L
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
fixture.now += 60_000L
|
||||
fixture.availableWhileSuspendedKb = 3_000_000L
|
||||
fixture.sync()
|
||||
val before = fixture.signals.size
|
||||
fixture.runScheduled()
|
||||
val relieved = fixture.signals.drop(before)
|
||||
assertEquals(listOf(GAME), relieved.filter { it.signal == URG }.map { it.pid })
|
||||
assertTrue(relieved.indexOfFirst { it.signal == CONT } < relieved.indexOfFirst { it.signal == URG })
|
||||
assertTrue(relieved.indexOfFirst { it.signal == URG } < relieved.indexOfLast { it.signal == STOP })
|
||||
assertEquals(60_000L * 1_000_000L, fixture.clockAtContinue)
|
||||
assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut)
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
assertEquals(1, fixture.audioSuspends)
|
||||
assertEquals(0, fixture.audioResumes)
|
||||
assertTrue(fixture.scheduled.isEmpty())
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf(Triple(1, 0L, 3_000_000L)), fixture.pagedIn)
|
||||
assertTrue(fixture.game.threads.all { it.state == 'S' })
|
||||
}
|
||||
|
||||
@Test fun aResumeEndsThePageOutChecks() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.availableWhileSuspendedKb = 8_000_000L
|
||||
val executor = QueueExecutor()
|
||||
val queued = fixture(17, executor).apply {
|
||||
control.writeText("0")
|
||||
availableWhileSuspendedKb = 8_000_000L
|
||||
}
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
fixture.availableWhileSuspendedKb = 1_000_000L
|
||||
fixture.availableKb = 1_000_000L
|
||||
fixture.sync()
|
||||
fixture.runScheduled()
|
||||
assertFalse(fixture.signals.any { it.signal == URG })
|
||||
queued.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
executor.drain()
|
||||
queued.availableWhileSuspendedKb = 1_000_000L
|
||||
queued.sync()
|
||||
queued.runScheduled()
|
||||
queued.controller.resume { assertTrue(it) }
|
||||
executor.drain()
|
||||
assertFalse(queued.signals.any { it.signal == URG })
|
||||
assertTrue(queued.game.threads.all { it.state == 'S' })
|
||||
}
|
||||
|
||||
@Test fun noReadBackAfterAFreezeWithoutPageOut() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
@@ -575,14 +648,16 @@ class SessionSuspendControllerTest {
|
||||
val pagedOut = mutableListOf<Triple<Int, Long, Long>>()
|
||||
val pagedIn = mutableListOf<Triple<Int, Long, Long>>()
|
||||
var availableKb = 8_000_000L
|
||||
var availableWhileSuspendedKb = 2_000_000L
|
||||
var totalKb = 16_000_000L
|
||||
val scheduled = mutableListOf<Pair<Long, () -> Unit>>()
|
||||
private val paging = linkedMapOf(GAME to Paging(4_000_000L))
|
||||
var unacknowledged = -1
|
||||
var handlerStalls = false
|
||||
var handlerReplaced = false
|
||||
private var continuing = false
|
||||
val controller = SessionSuspendController(
|
||||
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
|
||||
{ rootPid }, { helpers }, { audioSuspends++; meminfo() }, { audioResumes++; meminfo() },
|
||||
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
|
||||
zramControl = control,
|
||||
clockControl = clock,
|
||||
@@ -593,6 +668,7 @@ class SessionSuspendControllerTest {
|
||||
this.unacknowledged = unacknowledged
|
||||
},
|
||||
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
|
||||
schedule = { delay, task -> scheduled += delay to task },
|
||||
)
|
||||
|
||||
init { sync() }
|
||||
@@ -605,6 +681,12 @@ class SessionSuspendControllerTest {
|
||||
|
||||
fun swapKb(pid: Int) = paging.getValue(pid).swap
|
||||
|
||||
fun runScheduled() {
|
||||
val tasks = scheduled.toList()
|
||||
scheduled.clear()
|
||||
tasks.forEach { it.second() }
|
||||
}
|
||||
|
||||
private fun signal(pid: Int, signal: Int) {
|
||||
signals += SentSignal(pid, signal)
|
||||
val request = if (signal == URG) request(pid) else null
|
||||
@@ -687,8 +769,13 @@ class SessionSuspendControllerTest {
|
||||
sync()
|
||||
}
|
||||
|
||||
private fun meminfo() {
|
||||
val available = if (audioSuspends > audioResumes) availableWhileSuspendedKb else availableKb
|
||||
File(proc, "meminfo").writeText("MemTotal:\t$totalKb kB\nMemFree:\t1000 kB\nMemAvailable:\t$available kB\n")
|
||||
}
|
||||
|
||||
fun sync() {
|
||||
File(proc, "meminfo").writeText("MemTotal:\t$totalKb kB\nMemFree:\t1000 kB\nMemAvailable:\t$availableKb kB\n")
|
||||
meminfo()
|
||||
for (group in groups) {
|
||||
val dir = File(proc, group.pid.toString())
|
||||
if (group == root && rootGone) { dir.deleteRecursively(); continue }
|
||||
|
||||
@@ -153,11 +153,20 @@ Without root an app cannot write its memory cgroup's `memory.reclaim` (owned by
|
||||
and KGSL's per-process GPU reclaim `state` is root-only. Page-out therefore runs inside each
|
||||
process through the preload, and GPU memory itself cannot be compressed from userspace.
|
||||
|
||||
## Read-back after a suspend
|
||||
## Page-out and read-back around a suspend
|
||||
|
||||
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.
|
||||
A hidden or screen-off suspend stops the session at once. It pages the session out first only
|
||||
when `MemAvailable` is below twice the reserve, the larger of 1 GiB and a tenth of RAM. Otherwise
|
||||
the session stays resident while it is stopped, and every ten seconds of uptime the app reads
|
||||
`MemAvailable` again. Once it falls below that level, the app moves the guest clock forward by
|
||||
the stopped time, continues the session with audio still suspended, pages it out and stops it
|
||||
again. A resume ends the checks and cuts a running page-out short. A short screen-off with memory
|
||||
to spare therefore moves nothing into zram, and nothing has to come back when the screen turns on.
|
||||
Getting it back costs much more on some phones than on others: after a 12 s screen-off a Poco F7
|
||||
read 690 MB back in 6.7 s while the phone was waking up.
|
||||
|
||||
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 reserve available.
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user