mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 20:45:43 +00:00
Keep lost guests failed, count zombies and adopted spills as lost, check every thread's tracer, and pace automatic resumes
This commit is contained in:
1 parent
3419391940
commit
7771a87695
5 files changed
+203
-14
No files matched your search
@@ -1785,7 +1785,7 @@ class SessionService : Service() {
|
||||
return
|
||||
}
|
||||
if (SessionState.suspended) {
|
||||
resumeSession()
|
||||
resumeSession(restartRecovery = false)
|
||||
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
|
||||
return
|
||||
}
|
||||
@@ -1954,7 +1954,7 @@ class SessionService : Service() {
|
||||
private fun steamGameRunning(gameId: String): Boolean =
|
||||
SteamGameProcess.running(gameId)
|
||||
|
||||
private fun resumeSession(panelVisible: Boolean = true) {
|
||||
private fun resumeSession(panelVisible: Boolean = true, restartRecovery: Boolean = true) {
|
||||
if (SessionState.suspended) SessionState.resumeRequested = true
|
||||
if (panelVisible) activityVisible = true
|
||||
screenOn = readScreenOn()
|
||||
@@ -1966,6 +1966,7 @@ class SessionService : Service() {
|
||||
completeNativeSleep()
|
||||
completeSteamSleep()
|
||||
suspendAttemptFailed = false
|
||||
if (restartRecovery) resumeRecovery.reset()
|
||||
updateSuspendPolicy()
|
||||
}
|
||||
|
||||
@@ -2184,9 +2185,11 @@ class SessionService : Service() {
|
||||
controller.cancelFreeze()
|
||||
}
|
||||
if (shouldSuspend && SessionState.suspended && !suspendOperationPending) SessionState.resumeRequested = false
|
||||
// A session still held after a failed suspend or resume is released by paced resumes, whatever the latch.
|
||||
val recovering = suspendAttemptFailed && SessionState.suspended && !shouldSuspend &&
|
||||
resumeRecovery.due(SystemClock.elapsedRealtime())
|
||||
// A session still held after a failed suspend or resume is released by paced resumes, whatever clears or
|
||||
// sets the latch; only an explicit resume (resumeSession) restarts the pacing.
|
||||
val held = SessionState.suspended && SessionState.resumeFailed && !shouldSuspend
|
||||
if (!suspendOperationPending && resumeRecovery.holds(held, SystemClock.elapsedRealtime())) return
|
||||
val recovering = suspendAttemptFailed && held
|
||||
if (suspendOperationPending || (suspendAttemptFailed && !recovering) || shouldSuspend == SessionState.suspended) return
|
||||
val gen = sessionGen
|
||||
suspendOperationPending = true
|
||||
@@ -2242,6 +2245,7 @@ class SessionService : Service() {
|
||||
acquireLocks()
|
||||
SessionState.resuming = true
|
||||
controller.resume { success ->
|
||||
val lost = !success && controller.guestLost
|
||||
mainHandler.post {
|
||||
if (gen != sessionGen || !SessionState.running) return@post
|
||||
suspendOperationPending = false
|
||||
@@ -2255,6 +2259,17 @@ class SessionService : Service() {
|
||||
mainHandler.removeCallbacks(retryResume)
|
||||
SessionEvents.transition(SessionEvents.resumePhase(), "session.resumed")
|
||||
refreshNotification()
|
||||
} else if (lost) {
|
||||
// Everything was continued, but a game ended without its memory back: no retry restores
|
||||
// it, and the failure stays reported.
|
||||
SessionState.suspended = false
|
||||
SessionState.resumeFailures++
|
||||
SessionState.resumeFailed = true
|
||||
resumeRecovery.reset()
|
||||
mainHandler.removeCallbacks(retryResume)
|
||||
SessionEvents.record("session.resume_lost_guest")
|
||||
Log.w(TAG, "a game ended before its memory was read back from storage")
|
||||
refreshNotification()
|
||||
} else {
|
||||
suspendAttemptFailed = true
|
||||
SessionState.resumeFailures++
|
||||
|
||||
@@ -61,6 +61,14 @@ internal class SessionSuspendController(
|
||||
private var counterUnpublished = false
|
||||
// Spilled targets whose positive answer was taken (and its acknowledgement removed).
|
||||
private var spillWritten = emptyList<ProcessRecord>()
|
||||
// Taken into the restore wait by this resume: alive then, so one that ends without its memory back is lost.
|
||||
private var adopted = emptyList<ProcessRecord>()
|
||||
// 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.
|
||||
@Volatile var guestLost = false
|
||||
private set
|
||||
|
||||
// A failed freeze that could not return every process to running: only a resume releases them.
|
||||
@Volatile var rollbackPending = false
|
||||
@@ -118,6 +126,8 @@ internal class SessionSuspendController(
|
||||
if (complete && frozenSince == null) frozenSince = nowNanos()
|
||||
if (!complete) {
|
||||
// A spilled process is back only once its helper has read it back: until then a resume retries.
|
||||
adopted = emptyList()
|
||||
answeredLate = emptyList()
|
||||
val running = startedAlive()
|
||||
if (restoreSafely(frozen) && awaitRestored(running)) frozen = emptyList()
|
||||
runAudio(resumeAudio)
|
||||
@@ -138,8 +148,11 @@ internal class SessionSuspendController(
|
||||
submit({
|
||||
val records = frozen
|
||||
val advancedTo = advanceClock()
|
||||
runAudio(resumeAudio)
|
||||
guestLost = false
|
||||
adopted = emptyList()
|
||||
answeredLate = emptyList()
|
||||
val running = startedAlive()
|
||||
runAudio(resumeAudio)
|
||||
val resumed = restoreSafely(records)
|
||||
if (resumed) {
|
||||
frozen = emptyList()
|
||||
@@ -385,7 +398,16 @@ internal class SessionSuspendController(
|
||||
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)
|
||||
ended(record)
|
||||
}
|
||||
|
||||
// Gone, or every thread has exited and only an unreaped zombie is left.
|
||||
private fun ended(record: ProcessRecord): Boolean {
|
||||
if (isGone(record)) return true
|
||||
val tasks = File(procRoot, "${record.pid}/task").listFiles()?.filter { it.name.toIntOrNull() != null } ?: return false
|
||||
return tasks.all { entry ->
|
||||
try { readStat(File(entry, "stat"))[0].first().let { it == 'Z' || it == 'X' } } catch (_: IOException) { false }
|
||||
}
|
||||
}
|
||||
|
||||
// Settled targets stop being tracked; one that fell back to zram late is read back like any paged-out one.
|
||||
@@ -418,6 +440,7 @@ internal class SessionSuspendController(
|
||||
ack == 0L || ack == SPILL_CANCELLED
|
||||
}
|
||||
if (answered.isNotEmpty()) {
|
||||
answeredLate = (answeredLate + answered).distinct()
|
||||
spilledTargets = spilledTargets.filterNot { it in answered }
|
||||
release(control, answered)
|
||||
}
|
||||
@@ -454,10 +477,13 @@ internal class SessionSuspendController(
|
||||
} catch (_: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
}
|
||||
val lost = running.filter { record ->
|
||||
val lost = (running + adopted).distinct().filterNot { it in answeredLate }.filter { record ->
|
||||
val ack = readAck(ackFile(control, "ack", record))
|
||||
isGone(record) && readAck(ackFile(control, "restored", record)) == null && ack != 0L && ack != SPILL_CANCELLED
|
||||
ended(record) && readAck(ackFile(control, "restored", record)) == null && ack != 0L && ack != SPILL_CANCELLED
|
||||
}
|
||||
adopted = emptyList()
|
||||
answeredLate = emptyList()
|
||||
guestLost = lost.isNotEmpty()
|
||||
if (targets.isNotEmpty()) {
|
||||
release(control, targets.filterNot { it in waiting })
|
||||
spilledTargets = waiting.toList()
|
||||
@@ -471,20 +497,34 @@ internal class SessionSuspendController(
|
||||
// dies first has its owner killed).
|
||||
private fun detached(control: File, record: ProcessRecord, untraced: MutableMap<ProcessRecord, Long>): Boolean {
|
||||
if (record !in spillWritten && (readAck(ackFile(control, "ack", record)) ?: 0L) <= 0L) return false
|
||||
// The helper detaches thread by thread, so every live thread must be out of its trace.
|
||||
val current = try { readProcess(record.pid) } catch (_: IOException) { null }
|
||||
if (current == null || current.started != record.started || current.tracer != 0) {
|
||||
if (current == null || current.started != record.started || ended(record) || anyThreadTraced(record)) {
|
||||
untraced.remove(record)
|
||||
return false
|
||||
}
|
||||
return nowMillis() - untraced.getOrPut(record) { nowMillis() } >= MARKER_GRACE_MS
|
||||
}
|
||||
|
||||
private fun anyThreadTraced(record: ProcessRecord): Boolean {
|
||||
val tasks = File(procRoot, "${record.pid}/task").listFiles() ?: return true
|
||||
return tasks.any { entry ->
|
||||
entry.name.toIntOrNull() != null && try {
|
||||
File(entry, "status").useLines { lines ->
|
||||
lines.firstOrNull { it.startsWith("TracerPid:") }?.substringAfter(':')?.trim()?.toIntOrNull() != 0
|
||||
}
|
||||
} catch (_: IOException) {
|
||||
File(entry, "stat").exists()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Started or written spills of processes alive now: one of them that ends without its memory back is lost.
|
||||
private fun startedAlive(): List<ProcessRecord> {
|
||||
val control = zramControl ?: return emptyList()
|
||||
return (spilledTargets + spillAsked.filter { ackFile(control, "ack", it).exists() }).distinct().filter {
|
||||
val ack = readAck(ackFile(control, "ack", it))
|
||||
ack != 0L && ack != SPILL_CANCELLED && !isGone(it)
|
||||
ack != 0L && ack != SPILL_CANCELLED && !ended(it)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,8 +685,9 @@ internal class SessionSuspendController(
|
||||
// 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) }
|
||||
val started = asked.filter { it !in spilledTargets && ackFile(control, "ack", it).exists() && !ended(it) }
|
||||
if (started.isNotEmpty()) spilledTargets = spilledTargets + started
|
||||
adopted = started
|
||||
}
|
||||
|
||||
private fun restoreSafely(records: List<ProcessRecord>): Boolean = try {
|
||||
|
||||
@@ -10,6 +10,9 @@ internal class SuspendRecovery(
|
||||
|
||||
fun due(now: Long): Boolean = attempts < maxAttempts && now >= nextAt
|
||||
|
||||
// Whether a session that is still held must wait instead of starting another resume now.
|
||||
fun holds(held: Boolean, now: Long): Boolean = held && !due(now)
|
||||
|
||||
// The delay before the next attempt is due, or null when no attempt is left.
|
||||
fun failed(now: Long): Long? {
|
||||
attempts++
|
||||
|
||||
@@ -337,6 +337,64 @@ class SessionSuspendControllerTest {
|
||||
}
|
||||
}
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aSpillThatStartsDuringTheResumeAndIsLostFailsIt() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.handlerReplaced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
// after the resume took its snapshot, before it publishes the count
|
||||
fixture.onAudioResume = {
|
||||
fixture.startLateSpill()
|
||||
fixture.readBackKills = true
|
||||
}
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aGuestThatFellBackLateAndEndedIsNotLost() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.spillSilent = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { }
|
||||
fixture.onAudioResume = {
|
||||
File(fixture.control.parentFile, ".dd-zram.ack.$GAME").writeText("0")
|
||||
fixture.game.threads.forEach { it.state = 'Z' }
|
||||
fixture.sync()
|
||||
}
|
||||
fixture.controller.resume { assertTrue(it) }
|
||||
assertFalse(fixture.controller.guestLost)
|
||||
}
|
||||
|
||||
@Test fun aSpilledGuestKilledByAFailedReadBackIsLostWhileStillAZombie() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.game.tracer = HELPER
|
||||
fixture.sync()
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
fixture.readBackKills = true
|
||||
fixture.controller.resume { assertFalse(it) }
|
||||
assertTrue(fixture.controller.guestLost)
|
||||
assertTrue(fixture.game.threads.all { it.state == 'Z' })
|
||||
}
|
||||
|
||||
@Test fun theMarkerlessFallbackWaitsForEveryThreadToLeaveTheTrace() {
|
||||
val fixture = fixture(17)
|
||||
fixture.control.writeText("0")
|
||||
fixture.game.tracer = HELPER
|
||||
fixture.sync()
|
||||
fixture.markerFails = true
|
||||
fixture.workerStaysTraced = true
|
||||
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
|
||||
var called = false
|
||||
fixture.controller.resume {
|
||||
assertTrue(it)
|
||||
assertTrue(fixture.workerReleaseAt < 0)
|
||||
called = true
|
||||
}
|
||||
assertTrue(called)
|
||||
}
|
||||
|
||||
@Test fun aRefreezeStopsAGuestThatOnlyItsHelperStillHolds() {
|
||||
@@ -807,7 +865,7 @@ class SessionSuspendControllerTest {
|
||||
private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) =
|
||||
Fixture(temporary.newFolder(), temporary.newFolder(), count, executor)
|
||||
|
||||
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
|
||||
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0, var tracer: Int? = null)
|
||||
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)
|
||||
|
||||
@@ -829,6 +887,7 @@ class SessionSuspendControllerTest {
|
||||
var emptyGameTasks = false
|
||||
var rootGone = false
|
||||
var afterSleep: (() -> Unit)? = null
|
||||
var onAudioResume: (() -> Unit)? = null
|
||||
val control = File(tmp, ".dd-zram")
|
||||
val clock = File(tmp, ".dd-clock")
|
||||
var clockAtContinue: Long? = null
|
||||
@@ -852,6 +911,9 @@ class SessionSuspendControllerTest {
|
||||
val resumeAtContinue = mutableListOf<String?>()
|
||||
var lateSpillSeesTheCount = false
|
||||
var markerFails = false
|
||||
var workerStaysTraced = false
|
||||
var workerReleaseAt = -1L
|
||||
var readBackKills = false
|
||||
var readBacks = 0
|
||||
val gameResident get() = gameResidentKb
|
||||
private var spilling = false
|
||||
@@ -866,7 +928,7 @@ class SessionSuspendControllerTest {
|
||||
private val resume = File(tmp, ".dd-zram.resume")
|
||||
private var continuing = false
|
||||
val controller = SessionSuspendController(
|
||||
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
|
||||
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++; onAudioResume?.invoke() },
|
||||
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
|
||||
zramControl = control,
|
||||
clockControl = clock,
|
||||
@@ -953,6 +1015,10 @@ class SessionSuspendControllerTest {
|
||||
restoredPending = false
|
||||
if (!markerFails) File(control.parentFile, "${control.name}.restored.$GAME").writeText("120")
|
||||
}
|
||||
if (workerReleaseAt in 0..now) {
|
||||
game.threads.last().tracer = null
|
||||
workerReleaseAt = -1L
|
||||
}
|
||||
if (!restoring || count == spilledBase) return
|
||||
if (countSeenAt < 0) {
|
||||
countSeenAt = now
|
||||
@@ -960,9 +1026,20 @@ class SessionSuspendControllerTest {
|
||||
}
|
||||
if (now - countSeenAt < restoreDelayMs) return
|
||||
restoring = false
|
||||
if (readBackKills) {
|
||||
// the helper kills its owner on a failed read-back; nobody has reaped it yet
|
||||
game.tracer = 0
|
||||
game.threads.forEach { it.state = 'Z' }
|
||||
countSeenAt = -1L
|
||||
return
|
||||
}
|
||||
readBacks++
|
||||
gameResidentKb = 4_000_000L
|
||||
if (markerFails) game.tracer = 0
|
||||
if (markerFails && workerStaysTraced) {
|
||||
game.threads.last().tracer = HELPER
|
||||
workerReleaseAt = now + 3_000L
|
||||
}
|
||||
if (!gameContinued) releasedBeforeContinue = true
|
||||
releaseGame()
|
||||
restoredPending = true
|
||||
@@ -1034,6 +1111,7 @@ class SessionSuspendControllerTest {
|
||||
for (task in group.threads) {
|
||||
val entry = File(taskDir, task.tid.toString()).apply { mkdirs() }
|
||||
File(entry, "stat").writeText(stat(group, task))
|
||||
File(entry, "status").writeText("TracerPid: ${task.tracer ?: group.tracer}\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,58 @@ class SuspendRecoveryTest {
|
||||
assertTrue(recovery.due(3_000L))
|
||||
}
|
||||
|
||||
// The service's loop: every policy pass (a 250 ms queued-launch poll, a display event or a scheduled retry)
|
||||
// starts a resume unless the recovery holds it; a failed resume schedules the next pass.
|
||||
private class Service(val recovery: SuspendRecovery = SuspendRecovery()) {
|
||||
var now = 0L
|
||||
var suspended = true
|
||||
var counterWritable = false
|
||||
var resumes = 0
|
||||
val scheduled = sortedSetOf<Long>()
|
||||
|
||||
fun pass() {
|
||||
if (!suspended || recovery.holds(true, now)) return
|
||||
resumes++
|
||||
if (counterWritable) {
|
||||
suspended = false
|
||||
recovery.reset()
|
||||
scheduled.clear()
|
||||
} else {
|
||||
recovery.failed(now)?.let { scheduled += now + it }
|
||||
}
|
||||
}
|
||||
|
||||
fun runUntil(end: Long, pollMs: Long? = null) {
|
||||
while (now < end) {
|
||||
val nextPoll = pollMs?.let { now - now % it + it } ?: Long.MAX_VALUE
|
||||
val next = minOf(nextPoll, scheduled.firstOrNull() ?: Long.MAX_VALUE, end)
|
||||
now = next
|
||||
scheduled.remove(next)
|
||||
pass()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun queuedLaunchPollsCannotExceedTheRetryBudget() {
|
||||
val service = Service()
|
||||
service.pass()
|
||||
service.runUntil(600_000L, pollMs = 250L)
|
||||
assertEquals(5, service.resumes)
|
||||
assertTrue(service.suspended)
|
||||
}
|
||||
|
||||
@Test fun aScheduledRetryResumesOnceTheCountCanBeWrittenWithoutAnotherEvent() {
|
||||
val service = Service()
|
||||
service.pass()
|
||||
assertEquals(1, service.resumes)
|
||||
service.counterWritable = true
|
||||
service.runUntil(4_999L)
|
||||
assertTrue(service.suspended)
|
||||
service.runUntil(5_000L)
|
||||
assertFalse(service.suspended)
|
||||
assertEquals(2, service.resumes)
|
||||
}
|
||||
|
||||
@Test fun attemptsAreBoundedUntilAResumeSucceeds() {
|
||||
val recovery = SuspendRecovery(maxAttempts = 2, firstDelayMs = 1_000L)
|
||||
recovery.failed(0L)
|
||||
|
||||
Reference in new issue
Block a user