Keep the frozen clock, a pending rollback and late spills tracked when a resume cannot finish

This commit is contained in:
Kurt Himebauch committed 2026-12-05 05:16:03 -05:00
1 parent 6638a7dac8
commit f68a78c577
3 files changed
+177 -29

No files matched your search

@@ -2197,6 +2197,7 @@ class SessionService : Service() {
val freezeNativeToken = nativeSleepToken
val pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn
controller.freeze(pageOut = pageOut, spill = pageOut && SessionPrefs.diskSpill(this)) { success ->
val rollbackPending = !success && controller.rollbackPending
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
SessionState.suspending = false
@@ -2219,6 +2220,12 @@ class SessionService : Service() {
SessionState.manualPause = false
Log.w(TAG, "could not confirm that the session stopped")
}
// Some processes are still held: only a resume can release them.
if (rollbackPending) {
SessionState.suspended = true
SessionState.resumeFailed = true
Log.w(TAG, "could not return the session to running after the suspend failed")
}
}
updateSuspendPolicy()
}
@@ -58,6 +58,11 @@ internal class SessionSuspendController(
private var spilledTargets = emptyList<ProcessRecord>()
// Asked to spill and not yet released by a resume count they saw: acknowledged or not, each may park its process.
private var spillAsked = emptyList<ProcessRecord>()
private var counterUnpublished = false
// A failed freeze that could not return every process to running: only a resume releases them.
@Volatile var rollbackPending = false
private set
fun freeze(pageOut: Boolean = false, spill: Boolean = false, completion: (Boolean) -> Unit) {
cancelled = false
@@ -113,6 +118,7 @@ internal class SessionSuspendController(
if (restoreSafely(frozen)) frozen = emptyList()
runAudio(resumeAudio)
}
rollbackPending = !complete && frozen.isNotEmpty()
if (interrupted) Thread.currentThread().interrupt()
}
completion(complete)
@@ -127,12 +133,18 @@ internal class SessionSuspendController(
fun resume(completion: (Boolean) -> Unit) {
submit({
val records = frozen
advanceClock()
val advancedTo = advanceClock()
runAudio(resumeAudio)
val running = (spilledTargets + spillAsked).filterNot { isGone(it) }
val resumed = restoreSafely(records)
if (resumed) frozen = emptyList()
if (resumed) {
frozen = emptyList()
rollbackPending = false
}
// nothing was continued: the guest clock owes the time from here to the next attempt
if (!resumed && counterUnpublished && advancedTo != null) frozenSince = advancedTo
// a spilled process runs again only once its helper has read its memory back
completion(resumed && awaitRestored())
completion(resumed && awaitRestored(running))
if (resumed) readBack(waitForRestore = false)
}, { completion(false) })
}
@@ -155,22 +167,25 @@ internal class SessionSuspendController(
}
}
private fun advanceClock() {
val since = frozenSince ?: return
// Returns the moment the guest clock now accounts for, or null when no frozen interval was open.
private fun advanceClock(): Long? {
val since = frozenSince ?: return null
frozenSince = null
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return
val now = nowNanos()
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return now
try {
mapClockControl(control)
RandomAccessFile(control, "rw").use { file ->
val bytes = ByteArray(Long.SIZE_BYTES)
file.readFully(bytes)
val shift = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).long.coerceAtLeast(0L) +
(nowNanos() - since).coerceAtLeast(0L)
(now - since).coerceAtLeast(0L)
file.seek(0L)
file.write(ByteBuffer.allocate(Long.SIZE_BYTES).order(ByteOrder.LITTLE_ENDIAN).putLong(shift).array())
}
} catch (_: IOException) {
}
return now
}
private fun runAudio(action: () -> Unit) {
@@ -349,18 +364,21 @@ internal class SessionSuspendController(
// spilled one, its acknowledgement kept. One with no acknowledgement may have no handler, or one that has
// not got that far: it is not waited for, but stays asked, so a resume count that cannot be written still
// fails (a late spill waits for any count other than the one it was asked with).
val unanswered = targets.filter { (acks[it] ?: -1L) < 0L && ackFile(control, "ack", it).exists() && !isGone(it) }
spillAsked = spillAsked.filterNot { acks[it] == 0L }
val unanswered = targets.filter { acks[it] == null && ackFile(control, "ack", it).exists() && !isGone(it) }
spillAsked = spillAsked.filterNot { acks[it] == 0L || acks[it] == SPILL_CANCELLED }
spilledTargets = (spilledTargets + written + unanswered).distinct()
pagedOutTargets = (pagedOutTargets + targets.filter { acks[it] == 0L }).distinct()
targets.filterNot { it in unanswered }.forEach { ackFile(control, "ack", it).delete() }
spilled(written.size, total, memoryKb(targets).first, nowMillis() - start)
}
// Its memory is back, it paged out to zram after all (an answer of 0 that came late), or it is gone.
private fun settled(control: File, record: ProcessRecord) =
readAck(ackFile(control, "restored", record)) != null || readAck(ackFile(control, "ack", record)) == 0L ||
// Its memory is back, it paged out to zram after all (an answer of 0 that came late), a resume cancelled
// it before it wrote anything, or it is gone.
private fun settled(control: File, record: ProcessRecord): Boolean {
val ack = readAck(ackFile(control, "ack", record))
return readAck(ackFile(control, "restored", record)) != null || ack == 0L || ack == SPILL_CANCELLED ||
isGone(record)
}
// Settled targets stop being tracked; one that fell back to zram late is read back like any paged-out one.
private fun release(control: File, settledTargets: List<ProcessRecord>) {
@@ -400,9 +418,10 @@ internal class SessionSuspendController(
return ok || spillAsked.isEmpty()
}
// True when every spilled process has its memory back (or is gone). Ones still reading stay tracked, so a
// later resume waits for them again.
private fun awaitRestored(): Boolean {
// True when every spilled process has its memory back (or was gone already). Ones still reading stay
// tracked, so a later resume waits for them again. One of [running] that ends without its memory back fails
// this resume.
private fun awaitRestored(running: Collection<ProcessRecord> = emptyList()): Boolean {
val control = zramControl ?: return true
val targets = spilledTargets
if (targets.isEmpty()) return true
@@ -417,10 +436,15 @@ internal class SessionSuspendController(
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
}
val lost = running.filter { record ->
val ack = readAck(ackFile(control, "ack", record))
record in targets && isGone(record) && readAck(ackFile(control, "restored", record)) == null &&
ack != 0L && ack != SPILL_CANCELLED
}
release(control, targets.filterNot { it in waiting })
spilledTargets = waiting.toList()
restored(targets.size, waiting.size, memoryKb(targets).first, nowMillis() - start)
return waiting.isEmpty()
return waiting.isEmpty() && lost.isEmpty()
}
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
@@ -539,10 +563,12 @@ internal class SessionSuspendController(
private fun stopThreads(record: ProcessRecord) {
val current = try { readProcess(record.pid) } catch (_: Exception) { return }
if (current == null || current.started != record.started) return
// A spill helper's tracing stop ends when it detaches after reading back: the pending SIGSTOP holds then.
val helperHeld = record in spilledTargets
for (entry in File(procRoot, "${record.pid}/task").listFiles().orEmpty()) {
val tid = entry.name.toIntOrNull() ?: continue
val state = try { readStat(File(entry, "stat"))[0].first() } catch (_: IOException) { continue }
if (state == 'T' || state == 't' || state == 'Z' || state == 'X') continue
if (state == 'T' || (state == 't' && !helperHeld) || state == 'Z' || state == 'X') continue
try {
threadSignal(record.pid, tid, SIGSTOP)
} catch (_: Throwable) {
@@ -559,7 +585,10 @@ internal class SessionSuspendController(
Role.HELPER_CHILD -> 3
}
}
if (!bumpResume()) return false
val asked = spillAsked
counterUnpublished = !bumpResume()
if (counterUnpublished) return false
adoptStartedSpills(asked)
for (record in ordered) send(record, SIGCONT)
val waiting = ordered.toMutableList()
repeat(RESTORE_CHECKS) { check ->
@@ -571,6 +600,14 @@ internal class SessionSuspendController(
return false
}
// A handler that started after the spill wait ended parks its process until it has read back, like one
// that answered in time.
private fun adoptStartedSpills(asked: List<ProcessRecord>) {
val control = zramControl ?: return
val started = asked.filter { it !in spilledTargets && ackFile(control, "ack", it).exists() && !isGone(it) }
if (started.isNotEmpty()) spilledTargets = spilledTargets + started
}
private fun restoreSafely(records: List<ProcessRecord>): Boolean = try {
restore(records)
} catch (_: InterruptedException) {
@@ -609,6 +646,7 @@ internal class SessionSuspendController(
const val PAGE_OUT_REQUEST = "1"
const val READ_BACK_REQUEST = "0"
const val SPILL_REQUEST = "4"
const val SPILL_CANCELLED = -2L
const val SPILL_TIMEOUT_MS = 30_000L
const val RESTORE_TIMEOUT_MS = 30_000L
const val PAGE_OUT_POLL_MS = 100L
@@ -229,12 +229,92 @@ class SessionSuspendControllerTest {
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.startLateSpill()
var called = false
fixture.controller.resume {
assertTrue(it)
assertEquals(listOf(1 to 0), fixture.restores)
assertEquals(4_000_000L, fixture.gameResident)
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' || thread.state == 'T' })
called = true
}
assertTrue(called)
}
@Test fun aLateSpillThatSeesTheNewCountIsCancelledWithoutAReadBack() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.lateSpillSeesTheCount = true
fixture.startLateSpill()
fixture.controller.resume { assertTrue(it) }
fixture.advance(1_000L)
assertTrue(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").isFile)
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.pagedIn.isEmpty())
assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists())
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aSpilledGuestThatEndsWhileReadingBackFailsTheResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 60_000L
fixture.afterSleep = {
if (fixture.signals.any { it.signal == CONT } && fixture.game.threads.first().started == 2000L) {
fixture.game.threads.first().started++
}
}
fixture.controller.resume { assertFalse(it) }
}
@Test fun aRefreezeStopsAGuestThatOnlyItsHelperStillHolds() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 60_000L
fixture.controller.resume { assertFalse(it) }
val before = fixture.signals.size
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
assertTrue(fixture.signals.drop(before).count { it.pid == GAME && it.signal == STOP } >= 17)
fixture.restoreDelayMs = 0L
fixture.advance(1_000L)
assertTrue(fixture.game.threads.all { it.state == 'T' })
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aResumeThatCannotPublishItsCountKeepsTheFrozenTimeOwed() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.clock.writeBytes(shift(0L))
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val frozenAt = fixture.now
val blocked = File(fixture.control.parentFile, ".dd-zram.resume.new").apply { mkdirs() }
fixture.now += 90_000L
fixture.controller.resume { assertFalse(it) }
blocked.delete()
fixture.now += 10_000L
val resumedAt = fixture.now
fixture.controller.resume { assertTrue(it) }
assertEquals((resumedAt - frozenAt) * 1_000_000L, shift(fixture.clock))
}
@Test fun aRollbackThatCannotPublishItsCountStaysPendingUntilAResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
val blocked = File(fixture.control.parentFile, ".dd-zram.resume.new").apply { mkdirs() }
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertTrue(fixture.controller.rollbackPending)
assertTrue(fixture.resumeAtContinue.isEmpty())
blocked.delete()
fixture.afterSleep = null
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.controller.rollbackPending)
assertEquals(listOf(1 to 0), fixture.restores)
}
@Test fun aLateFallbackToZramIsReadBack() {
val fixture = fixture(17)
fixture.control.writeText("0")
@@ -265,6 +345,7 @@ class SessionSuspendControllerTest {
fixture.controller.resume { assertFalse(it) }
fixture.restoreDelayMs = 0L
fixture.advance(1_000L)
fixture.advance(100L)
assertTrue(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").isFile)
fixture.spillFallsBack = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
@@ -697,10 +778,14 @@ class SessionSuspendControllerTest {
val spills = mutableListOf<Pair<Int, Long>>()
val restores = mutableListOf<Pair<Int, Int>>()
val resumeAtContinue = mutableListOf<String?>()
var lateSpillSeesTheCount = false
val gameResident get() = gameResidentKb
private var spilling = false
private var spilledBase: String? = null
private var restoring = false
private var continuedAt = 0L
private var restoredPending = false
private var gameStopPending = false
private var continuedAt = -1L
private val resume = File(tmp, ".dd-zram.resume")
private var continuing = false
val controller = SessionSuspendController(
@@ -747,9 +832,10 @@ class SessionSuspendControllerTest {
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
}
continuing = true
if (pid == GAME && restoring) continuedAt = now
if (pid == GAME) gameStopPending = false
if (pid == GAME && parked && continuedAt < 0) 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' }
if (!(pid == GAME && (blockGameContinue || parked))) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
}
sync()
}
@@ -757,12 +843,21 @@ class SessionSuspendControllerTest {
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 }
// held by the helper's trace: the stop stays pending until the helper detaches
if (signal == STOP && pid == GAME && parked && task.state == 't') gameStopPending = true
if (signal == STOP && task.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && task == game.threads.last())) {
task.state = 't'
}
sync()
}
private val parked get() = spilling || restoring
private fun releaseGame() {
continuedAt = -1L
game.threads.forEach { if (it.state != 'Z') it.state = if (gameStopPending) 'T' else 'S' }
}
fun advance(millis: Long) = sleep(millis)
// the handler takes the spill request only now, after the controller stopped waiting for it
@@ -774,10 +869,14 @@ class SessionSuspendControllerTest {
private fun sleep(millis: Long) {
now += millis
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
if (spilling && !spillSilent) {
spilling = false
val ack = File(control.parentFile, "${control.name}.ack.$GAME")
if (spillFallsBack) {
if (lateSpillSeesTheCount && count != spilledBase) {
ack.writeText("-2")
releaseGame()
} else if (spillFallsBack) {
gameSwapKb += gameResidentKb
gameResidentKb = 0L
ack.writeText("0")
@@ -787,12 +886,16 @@ class SessionSuspendControllerTest {
restoring = true
}
}
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
if (restoring && continuing && count != spilledBase && now - continuedAt >= restoreDelayMs) {
// the helper detaches first and publishes its marker after
if (restoredPending) {
restoredPending = false
File(control.parentFile, "${control.name}.restored.$GAME").writeText("120")
}
if (restoring && count != spilledBase && continuedAt >= 0 && now - continuedAt >= restoreDelayMs) {
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")
releaseGame()
restoredPending = true
}
if (pagingOut && !handlerReplaced) {
File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") }
@@ -812,7 +915,7 @@ class SessionSuspendControllerTest {
gameResidentKb += moved
if (gameSwapKb == 0L) pagingIn = false
}
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
if (root.threads.first().state != 'T' && !continuing && !parked) game.threads.forEach {
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
}
afterSleep?.invoke()