mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e2043a2405 | ||
|
|
7b7a3bd673 | ||
|
|
f5fdc408aa | ||
|
|
0d7175ea9a | ||
|
|
3dac3ed47c | ||
|
|
a3470dbf6d | ||
|
|
10aafd1079 | ||
|
|
7323183580 | ||
|
|
4cf766afb9 | ||
|
|
6fbca0b6d1 |
No files matched your search
@@ -929,6 +929,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,89 @@ 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) = later(check, ::pageOutIfShort)
|
||||
|
||||
private fun later(check: Int, task: (Int) -> Unit) {
|
||||
schedule(PAGE_OUT_CHECK_MS) { submit({ task(check) }, {}) }
|
||||
}
|
||||
|
||||
private fun pageOutIfShort(check: Int) {
|
||||
if (check != pageOutChecks || closing || cancelled || frozen.isEmpty()) return
|
||||
if (!memoryShort()) return checkPageOut(check)
|
||||
restopUntilStable(++pageOutChecks, pageOut = true)
|
||||
}
|
||||
|
||||
private fun restopUntilStable(check: Int, pageOut: Boolean = false) {
|
||||
if (check != pageOutChecks || closing || cancelled || frozen.isEmpty()) return
|
||||
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
|
||||
val root = records.values.firstOrNull { it.role == Role.SESSION_ROOT }?.takeUnless { isGone(it) } ?: return
|
||||
val helpers = records.values.filter { it.role == Role.HELPER_ROOT }.map { it.pid }
|
||||
if (pageOut) advanceClock()
|
||||
var stable = false
|
||||
try {
|
||||
if (pageOut) {
|
||||
restore(records.values.toList())
|
||||
pageOut(records, root.pid, helpers)
|
||||
}
|
||||
stable = stopUntilStable(records, root, helpers)
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
} catch (_: Exception) {
|
||||
} finally {
|
||||
stop(records.values.toList())
|
||||
frozen = records.values.toList()
|
||||
if (pageOut) frozenSince = nowNanos()
|
||||
}
|
||||
if (!stable) later(check, ::restopUntilStable)
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -330,27 +387,32 @@ internal class SessionSuspendController(
|
||||
pagedOutTargets = emptyList()
|
||||
val control = zramControl?.takeIf { it.isFile } ?: return
|
||||
if (targets.isEmpty() || closing) return
|
||||
val before = memoryKb(targets).second
|
||||
val swapKb = targets.associateWith { memoryKb(listOf(it)).second }
|
||||
val before = swapKb.values.sum()
|
||||
val (total, available) = meminfoKb()
|
||||
if (!canTake(before, total, available)) {
|
||||
val chosen = readBackTargets(swapKb, total, available)
|
||||
if (chosen.isEmpty()) {
|
||||
pagedIn(0, before, before, available, 0)
|
||||
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
|
||||
}
|
||||
val start = nowMillis()
|
||||
for (record in targets) send(record, SIGURG)
|
||||
var swap = before
|
||||
for (record in chosen) send(record, SIGURG)
|
||||
var swap = memoryKb(chosen).second
|
||||
var unchanged = 0
|
||||
try {
|
||||
while (!closing && nowMillis() - start < READ_BACK_TIMEOUT_MS) {
|
||||
sleep(READ_BACK_POLL_MS)
|
||||
val current = memoryKb(targets).second
|
||||
val current = memoryKb(chosen).second
|
||||
unchanged = if (current == swap) unchanged + 1 else 0
|
||||
swap = current
|
||||
if (swap == 0L || unchanged >= READ_BACK_STABLE_POLLS) break
|
||||
@@ -358,14 +420,25 @@ internal class SessionSuspendController(
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
} finally {
|
||||
requests.forEach { it.delete() }
|
||||
hold.delete()
|
||||
}
|
||||
pagedIn(targets.size, swap, before, available, nowMillis() - start)
|
||||
pagedIn(chosen.size, memoryKb(targets).second, before, available, nowMillis() - start)
|
||||
}
|
||||
|
||||
private fun canTake(swapKb: Long, totalKb: Long, availableKb: Long): Boolean =
|
||||
availableKb >= swapKb * READ_BACK_AVAILABLE_FACTOR &&
|
||||
availableKb - swapKb >= maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE)
|
||||
private fun readBackTargets(swapKb: Map<ProcessRecord, Long>, totalKb: Long, availableKb: Long): List<ProcessRecord> {
|
||||
var budget = minOf(
|
||||
availableKb / READ_BACK_AVAILABLE_FACTOR,
|
||||
availableKb - reserveKb(totalKb),
|
||||
)
|
||||
val chosen = ArrayList<ProcessRecord>()
|
||||
for ((record, swap) in swapKb.entries.sortedByDescending { it.value }) {
|
||||
if (swap > budget) continue
|
||||
chosen += record
|
||||
budget -= swap
|
||||
}
|
||||
return chosen
|
||||
}
|
||||
|
||||
private fun meminfoKb(): Pair<Long, Long> = try {
|
||||
val values = HashMap<String, Long>()
|
||||
@@ -477,9 +550,12 @@ 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
|
||||
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
|
||||
|
||||
@@ -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,132 @@ 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<String?>("1", "0"), fixture.held)
|
||||
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 anUnsettledStopAfterADeferredPageOutIsRetriedUntilTheSessionStops() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
val results = mutableListOf<Boolean>()
|
||||
fixture.availableWhileSuspendedKb = 8_000_000L
|
||||
fixture.controller.freeze(pageOut = true) { results += it }
|
||||
fixture.availableWhileSuspendedKb = 3_000_000L
|
||||
fixture.neverStop = true
|
||||
fixture.sync()
|
||||
fixture.runScheduled()
|
||||
assertEquals(listOf(1), fixture.pagedOut.map { it.first })
|
||||
assertEquals('T', fixture.root.threads.single().state)
|
||||
assertEquals('S', fixture.game.threads.last().state)
|
||||
assertEquals(listOf(10_000L), fixture.scheduled.map { it.first })
|
||||
fixture.runScheduled()
|
||||
assertEquals('S', fixture.game.threads.last().state)
|
||||
assertEquals(1, fixture.scheduled.size)
|
||||
fixture.neverStop = false
|
||||
val before = fixture.signals.size
|
||||
fixture.runScheduled()
|
||||
assertFalse(fixture.signals.drop(before).any { it.signal == CONT || it.signal == URG })
|
||||
assertTrue(fixture.game.threads.all { it.state == 't' })
|
||||
assertTrue(fixture.scheduled.isEmpty())
|
||||
assertEquals(listOf(true), results)
|
||||
assertEquals(1, fixture.audioSuspends)
|
||||
assertEquals(0, fixture.audioResumes)
|
||||
assertEquals(listOf(1), fixture.pagedOut.map { it.first })
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf(1), fixture.pagedIn.map { it.first })
|
||||
assertTrue(fixture.game.threads.all { it.state == 'S' })
|
||||
}
|
||||
|
||||
@Test fun aResumeEndsTheRetriedStop() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.availableWhileSuspendedKb = 8_000_000L
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
fixture.availableWhileSuspendedKb = 3_000_000L
|
||||
fixture.neverStop = true
|
||||
fixture.sync()
|
||||
fixture.runScheduled()
|
||||
assertEquals(1, fixture.scheduled.size)
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
val before = fixture.signals.size
|
||||
fixture.runScheduled()
|
||||
assertFalse(fixture.signals.drop(before).any { it.signal == STOP })
|
||||
assertTrue(fixture.scheduled.isEmpty())
|
||||
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() {
|
||||
@@ -191,6 +317,61 @@ class SessionSuspendControllerTest {
|
||||
assertEquals(listOf(Triple(0, 3_000_000L, 3_000_000L)), fixture.pagedIn)
|
||||
}
|
||||
|
||||
@Test fun readBackTakesTheLargestProcessesThatFitTheAvailableMemory() {
|
||||
val fixture = fixture(17)
|
||||
fixture.addService(2_000_000L)
|
||||
fixture.control.writeText("0")
|
||||
fixture.availableKb = 7_000_000L
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
assertEquals(2, fixture.pagedOut.single().first)
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf(GAME), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid })
|
||||
assertEquals(listOf(Triple(1, 1_000_000L, 4_000_000L)), fixture.pagedIn)
|
||||
assertEquals(0L, fixture.swapKb(GAME))
|
||||
assertEquals(1_000_000L, fixture.swapKb(SERVICE))
|
||||
}
|
||||
|
||||
@Test fun aProcessTooLargeForTheBudgetDoesNotBlockTheOthers() {
|
||||
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) }
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(listOf(SERVICE), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid })
|
||||
assertEquals(listOf<String?>("1", "1", "0"), fixture.held)
|
||||
assertEquals(listOf(Triple(1, 3_000_000L, 4_000_000L)), fixture.pagedIn)
|
||||
assertEquals(3_000_000L, fixture.swapKb(GAME))
|
||||
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)
|
||||
fixture.control.writeText("0")
|
||||
fixture.controller.freeze(pageOut = true) { assertTrue(it) }
|
||||
val before = fixture.signals.size
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertEquals(setOf(GAME, SERVICE), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid }.toSet())
|
||||
assertEquals(listOf(Triple(2, 0L, 4_000_000L)), fixture.pagedIn)
|
||||
}
|
||||
|
||||
@Test fun cancelledFreezeReadsBackWhatThePageOutAlreadyMoved() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
@@ -488,6 +669,7 @@ class SessionSuspendControllerTest {
|
||||
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
|
||||
private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList<Task>)
|
||||
private data class SentSignal(val pid: Int, val signal: Int)
|
||||
private class Paging(var resident: Long, var swap: Long = 0L, var out: Boolean = false, var into: Boolean = false)
|
||||
|
||||
private class Fixture(val proc: File, tmp: File, count: Int, executor: QueueExecutor) {
|
||||
val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S')))
|
||||
@@ -496,6 +678,8 @@ class SessionSuspendControllerTest {
|
||||
val helpers = mutableListOf<Int>()
|
||||
val signals = mutableListOf<SentSignal>()
|
||||
val held = mutableListOf<String?>()
|
||||
val shared = mutableListOf<String?>()
|
||||
var lateRequest: Int? = null
|
||||
var rootPid = ROOT
|
||||
var now = 0L
|
||||
var audioSuspends = 0
|
||||
@@ -514,17 +698,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
|
||||
private var gameResidentKb = 4_000_000L
|
||||
private var gameSwapKb = 0L
|
||||
private var pagingOut = false
|
||||
private var pagingIn = false
|
||||
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,
|
||||
@@ -535,14 +718,32 @@ class SessionSuspendControllerTest {
|
||||
this.unacknowledged = unacknowledged
|
||||
},
|
||||
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
|
||||
schedule = { delay, task -> scheduled += delay to task },
|
||||
)
|
||||
|
||||
init { sync() }
|
||||
|
||||
fun addService(residentKb: Long) {
|
||||
groups += Group(SERVICE, ROOT, 0, mutableListOf(Task(SERVICE, 3000, 'S')))
|
||||
paging[SERVICE] = Paging(residentKb)
|
||||
sync()
|
||||
}
|
||||
|
||||
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) 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
|
||||
@@ -551,7 +752,7 @@ 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
|
||||
take(pid, request)
|
||||
} else if (signal == CONT) {
|
||||
if (clockAtContinue == null && clock.isFile) {
|
||||
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
|
||||
@@ -562,6 +763,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 }
|
||||
@@ -573,23 +788,29 @@ class SessionSuspendControllerTest {
|
||||
|
||||
private fun sleep(millis: Long) {
|
||||
now += millis
|
||||
if (pagingOut && !handlerReplaced) {
|
||||
File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") }
|
||||
lateRequest?.takeIf { sharedHold().isFile }?.let { pid ->
|
||||
lateRequest = null
|
||||
take(pid, request(pid))
|
||||
}
|
||||
if (pagingOut && !handlerStalls && !handlerReplaced) {
|
||||
if (gameResidentKb > 1_000_000L) {
|
||||
gameResidentKb -= 1_000_000L
|
||||
gameSwapKb += 1_000_000L
|
||||
} else {
|
||||
File(control.parentFile, "${control.name}.ack.$GAME").writeText("1")
|
||||
pagingOut = false
|
||||
for ((pid, memory) in paging) {
|
||||
if (memory.out && !handlerReplaced) {
|
||||
File(control.parentFile, "${control.name}.ack.$pid").apply { if (!exists()) writeText("") }
|
||||
}
|
||||
if (memory.out && !handlerStalls && !handlerReplaced) {
|
||||
if (memory.resident > 1_000_000L) {
|
||||
memory.resident -= 1_000_000L
|
||||
memory.swap += 1_000_000L
|
||||
} else {
|
||||
File(control.parentFile, "${control.name}.ack.$pid").writeText("1")
|
||||
memory.out = false
|
||||
}
|
||||
}
|
||||
if (memory.into) {
|
||||
val moved = minOf(memory.swap, 1_000_000L)
|
||||
memory.swap -= moved
|
||||
memory.resident += moved
|
||||
if (memory.swap == 0L) memory.into = false
|
||||
}
|
||||
}
|
||||
if (pagingIn) {
|
||||
val moved = minOf(gameSwapKb, 1_000_000L)
|
||||
gameSwapKb -= moved
|
||||
gameResidentKb += moved
|
||||
if (gameSwapKb == 0L) pagingIn = false
|
||||
}
|
||||
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
|
||||
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
|
||||
@@ -598,8 +819,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 }
|
||||
@@ -607,11 +833,12 @@ class SessionSuspendControllerTest {
|
||||
val stat = File(dir, "stat")
|
||||
if (group == game && missingGameStat) stat.delete()
|
||||
else stat.writeText(stat(group, group.threads.first()))
|
||||
val memory = paging[group.pid]
|
||||
File(dir, "status").writeText(
|
||||
"TracerPid: ${group.tracer}\n" +
|
||||
if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb kB\n" else "",
|
||||
if (memory != null) "VmRSS:\t${memory.resident} kB\nVmSwap:\t${memory.swap} kB\n" else "",
|
||||
)
|
||||
if (group == game) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
|
||||
if (memory != null) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
|
||||
val taskDir = File(dir, "task")
|
||||
if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue }
|
||||
taskDir.mkdirs()
|
||||
@@ -658,6 +885,7 @@ class SessionSuspendControllerTest {
|
||||
private companion object {
|
||||
const val ROOT = 100
|
||||
const val GAME = 200
|
||||
const val SERVICE = 300
|
||||
const val STOP = 19
|
||||
const val CONT = 18
|
||||
const val URG = 23
|
||||
|
||||
@@ -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.<pid>` 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.<pid>` and a trim answers its kB in `/tmp/.dd-zram.trim.<pid>`, 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
|
||||
@@ -156,6 +159,26 @@ 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.
|
||||
|
||||
## Page-out and read-back around a suspend
|
||||
|
||||
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. If the session does not settle in that stop, the app stops it again every ten seconds
|
||||
until it does, so it stays suspended as the service reports. A resume ends the checks and the
|
||||
retries 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.
|
||||
|
||||
## CRAM and the bounded pager experiment
|
||||
|
||||
[Meta's CRAM proposal](https://lpc.events/event/20/contributions/2424/) uses memory compression
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
#define ZR_INLINE_CHUNKS 512UL
|
||||
#define ZR_FAILED (~0UL)
|
||||
#define ZR_FUTEX_WAIT 0
|
||||
#define ZR_PATH (sizeof(ZR_CTL) + sizeof(".hold.") + 20)
|
||||
#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)
|
||||
@@ -217,20 +218,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++)
|
||||
@@ -412,16 +425,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);
|
||||
|
||||
@@ -337,6 +337,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);
|
||||
@@ -508,6 +538,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))
|
||||
@@ -645,6 +677,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):
|
||||
if os.geteuid() == 0:
|
||||
|
||||
Reference in new issue
Block a user