Keep recovery for outstanding restores after a loss, keep losses across a rollback, and leave the paused state idle when no attempt is due

This commit is contained in:
Kurt Himebauch committed 2026-12-05 06:22:44 -05:00
1 parent 82f806ad84
commit 8f639a08eb
4 files changed
+132 -16

No files matched your search

@@ -278,7 +278,7 @@ class SessionService : Service() {
}
ACTION_XR_ACTIVITY_VISIBLE -> {
xrActivityVisible = true
resumeSession(panelVisible = false)
resumeSession(panelVisible = false, restartRecovery = false)
return START_NOT_STICKY
}
ACTION_XR_ACTIVITY_HIDDEN -> {
@@ -1955,7 +1955,9 @@ class SessionService : Service() {
SteamGameProcess.running(gameId)
private fun resumeSession(panelVisible: Boolean = true, restartRecovery: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
if (SessionState.suspended && (restartRecovery || resumeRecovery.due(SystemClock.elapsedRealtime()))) {
SessionState.resumeRequested = true
}
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
@@ -2245,7 +2247,8 @@ class SessionService : Service() {
acquireLocks()
SessionState.resuming = true
controller.resume { success ->
val lost = !success && controller.guestLost
// A loss with another spill still reading back is retried for that one; the loss is kept.
val lost = !success && controller.guestLost && !controller.restoreOutstanding
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
suspendOperationPending = false
@@ -2267,7 +2270,7 @@ class SessionService : Service() {
SessionState.resumeFailed = true
resumeRecovery.reset()
mainHandler.removeCallbacks(retryResume)
SessionEvents.record("session.resume_lost_guest")
SessionEvents.transition(SessionEvents.resumePhase(), "session.resume_lost_guest")
Log.w(TAG, "a game ended before its memory was read back from storage")
refreshNotification()
} else {
@@ -66,10 +66,15 @@ internal class SessionSuspendController(
// Released by this attempt on a late answer of 0 or a cancellation: not lost if they end afterwards.
private var answeredLate = emptyList<ProcessRecord>()
// The last restore wait saw a spilled process end without its memory back: retrying cannot bring it back.
// A spilled process ended without its memory back since the last suspend began: retrying cannot bring it
// back, so no later resume of this suspension reports success.
@Volatile var guestLost = false
private set
// Spilled processes still reading back, which a later resume waits for again.
@Volatile var restoreOutstanding = false
private set
// A failed freeze that could not return every process to running: only a resume releases them.
@Volatile var rollbackPending = false
private set
@@ -77,6 +82,7 @@ internal class SessionSuspendController(
fun freeze(pageOut: Boolean = false, spill: Boolean = false, completion: (Boolean) -> Unit) {
cancelled = false
submit({
guestLost = false
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
var complete = false
var interrupted = false
@@ -148,7 +154,6 @@ internal class SessionSuspendController(
submit({
val records = frozen
val advancedTo = advanceClock()
guestLost = false
adopted = emptyList()
answeredLate = emptyList()
val running = startedAlive()
@@ -161,7 +166,9 @@ internal class SessionSuspendController(
// 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(running))
val restoredAll = resumed && awaitRestored(running)
restoreOutstanding = frozen.isNotEmpty() || spilledTargets.isNotEmpty()
completion(restoredAll && !guestLost)
if (resumed) readBack(waitForRestore = false)
}, { completion(false) })
}
@@ -468,22 +475,25 @@ internal class SessionSuspendController(
val start = nowMillis()
val waiting = targets.toMutableList()
val untraced = HashMap<ProcessRecord, Long>()
val releasedWithoutMarker = HashSet<ProcessRecord>()
try {
while (targets.isNotEmpty() && (whileClosing || !closing) && nowMillis() - start < RESTORE_TIMEOUT_MS) {
waiting.removeAll { settled(control, it) || detached(control, it, untraced) }
waiting.removeAll {
settled(control, it) || detached(control, it, untraced).also { done -> if (done) releasedWithoutMarker += it }
}
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
}
val lost = (running + adopted).distinct().filterNot { it in answeredLate }.filter { record ->
val lost = (running + adopted).distinct().filterNot { it in answeredLate || it in releasedWithoutMarker }.filter { record ->
val ack = readAck(ackFile(control, "ack", record))
ended(record) && readAck(ackFile(control, "restored", record)) == null && ack != 0L && ack != SPILL_CANCELLED
}
adopted = emptyList()
answeredLate = emptyList()
guestLost = lost.isNotEmpty()
if (lost.isNotEmpty()) guestLost = true
if (targets.isNotEmpty()) {
release(control, targets.filterNot { it in waiting })
spilledTargets = waiting.toList()
@@ -519,10 +529,11 @@ internal class SessionSuspendController(
}
}
// Started or written spills of processes alive now: one of them that ends without its memory back is lost.
// Asked, started or written spills of processes alive now: one that ends without its memory back (or a 0 or
// cancelled answer) is lost.
private fun startedAlive(): List<ProcessRecord> {
val control = zramControl ?: return emptyList()
return (spilledTargets + spillAsked.filter { ackFile(control, "ack", it).exists() }).distinct().filter {
return (spilledTargets + spillAsked).distinct().filter {
val ack = readAck(ackFile(control, "ack", it))
ack != 0L && ack != SPILL_CANCELLED && !ended(it)
}
@@ -340,6 +340,70 @@ class SessionSuspendControllerTest {
assertTrue(fixture.controller.guestLost)
}
@Test fun aLossWithAnotherSpillStillReadingBackKeepsBothTheRetryAndTheFailure() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.addSecondSpiller()
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.readBackKills = true
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
assertTrue(fixture.controller.restoreOutstanding)
assertTrue(fixture.other.threads.all { it.state == 't' })
fixture.releaseSecondSpiller()
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
assertFalse(fixture.controller.restoreOutstanding)
fixture.controller.freeze { assertTrue(it) }
assertFalse(fixture.controller.guestLost)
}
@Test fun aGuestReleasedWithoutItsMarkerThatEndsLaterIsNotLost() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.addSecondSpiller()
fixture.game.tracer = HELPER
fixture.sync()
fixture.markerFails = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val start = fixture.now
fixture.afterSleep = {
if (fixture.now - start >= 3_000L && fixture.game.threads.first().started == 2000L) {
fixture.game.threads.first().started++
}
if (fixture.now - start >= 4_000L && fixture.otherHeld) fixture.releaseSecondSpiller()
}
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.controller.guestLost)
}
@Test fun anAskedGuestThatStartsAndEndsBeforeItIsTakenIsLost() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.onAudioResume = {
File(fixture.control.parentFile, ".dd-zram.ack.$GAME").writeText("")
fixture.game.threads.first().started++
fixture.sync()
}
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
}
@Test fun aGuestLostInACancelledFreezesRollbackStaysLost() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.readBackKills = true
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
fixture.afterSleep = null
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.controller.guestLost)
assertFalse(fixture.controller.restoreOutstanding)
}
@Test fun aSpillThatStartsDuringTheResumeAndIsLostFailsIt() {
val fixture = fixture(17)
fixture.control.writeText("0")
@@ -873,6 +937,20 @@ class SessionSuspendControllerTest {
val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S')))
val game = Group(GAME, ROOT, ROOT, MutableList(count) { Task(GAME + it, 2000L + it, 'S') })
val groups = mutableListOf(root, game)
val other = Group(OTHER, ROOT, ROOT, mutableListOf(Task(OTHER, 4000, 'S')))
var otherHeld = false
fun addSecondSpiller() {
groups += other
sync()
}
fun releaseSecondSpiller() {
otherHeld = false
other.threads.forEach { it.state = 'S' }
File(control.parentFile, "${control.name}.restored.$OTHER").writeText("50")
sync()
}
val helpers = mutableListOf<Int>()
val signals = mutableListOf<SentSignal>()
val held = mutableListOf<String?>()
@@ -957,6 +1035,13 @@ class SessionSuspendControllerTest {
else group.threads.firstOrNull {
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
}?.state = 't'
} else if (signal == URG && pid == OTHER) {
// a second guest that spills at once and whose helper reads back only when the test lets it
if (request?.startsWith("4") == true) {
File(control.parentFile, "${control.name}.ack.$OTHER").writeText("1000")
otherHeld = true
other.threads.forEach { it.state = 't' }
}
} else if (signal == URG) {
if (request?.startsWith("4") == true) {
if (!handlerReplaced) {
@@ -975,7 +1060,9 @@ class SessionSuspendControllerTest {
if (pid == GAME) gameStopPending = false
if (pid == GAME) gameContinued = true
// a spilled guest stays in its tracing stop until its helper has read the memory back
if (!(pid == GAME && (blockGameContinue || parked))) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
if (!(pid == GAME && (blockGameContinue || parked)) && !(pid == OTHER && otherHeld)) {
group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
}
}
sync()
}
@@ -1103,7 +1190,7 @@ class SessionSuspendControllerTest {
"TracerPid: ${group.tracer}\n" +
if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb 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 (group == game || group == other) 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()
@@ -1156,5 +1243,6 @@ class SessionSuspendControllerTest {
const val URG = 23
const val RESTORE_DELAY_MS = 300L
const val HELPER = 300
const val OTHER = 400
}
}
@@ -39,14 +39,17 @@ class SuspendRecoveryTest {
}
}
// Only a scheduled retry or a poll runs a pass; time with neither runs nothing.
fun runUntil(end: Long, pollMs: Long? = null) {
while (now < end) {
while (true) {
val nextPoll = pollMs?.let { now - now % it + it } ?: Long.MAX_VALUE
val next = minOf(nextPoll, scheduled.firstOrNull() ?: Long.MAX_VALUE, end)
val next = minOf(nextPoll, scheduled.firstOrNull() ?: Long.MAX_VALUE)
if (next > end) break
now = next
scheduled.remove(next)
pass()
}
now = end
}
}
@@ -62,6 +65,7 @@ class SuspendRecoveryTest {
val service = Service()
service.pass()
assertEquals(1, service.resumes)
assertEquals(listOf(5_000L), service.scheduled.toList())
service.counterWritable = true
service.runUntil(4_999L)
assertTrue(service.suspended)
@@ -70,6 +74,16 @@ class SuspendRecoveryTest {
assertEquals(2, service.resumes)
}
@Test fun nothingResumesWithoutAScheduledRetryOrAnEvent() {
val service = Service(SuspendRecovery(maxAttempts = 1))
service.pass()
assertTrue(service.scheduled.isEmpty())
service.counterWritable = true
service.runUntil(600_000L)
assertTrue(service.suspended)
assertEquals(1, service.resumes)
}
@Test fun attemptsAreBoundedUntilAResumeSucceeds() {
val recovery = SuspendRecovery(maxAttempts = 2, firstDelayMs = 1_000L)
recovery.failed(0L)