Compare commits

...
Author SHA1 Message Date
Kurt Himebauch 8f639a08eb Keep recovery for outstanding restores after a loss, keep losses across a rollback, and leave the paused state idle when no attempt is due 2026-12-05 06:22:44 -05:00
Kurt Himebauch 82f806ad84 Stop the owner's worker and hold the helper inside its phase before the mid-I/O kill tests kill it 2026-12-05 06:22:43 -05:00
Kurt Himebauch 7771a87695 Keep lost guests failed, count zombies and adopted spills as lost, check every thread's tracer, and pace automatic resumes 2026-12-05 06:03:00 -05:00
Kurt Himebauch 3419391940 Test that only the kernel's exit kill ends a spilled owner, and that no owner thread runs after its helper dies mid-spill or mid-read-back 2026-12-05 06:03:00 -05:00
Kurt Himebauch c46bb72631 Retry held sessions with paced resumes, settle rollbacks and late answers, and end read-backs without a marker 2026-12-05 05:38:02 -05:00
Kurt Himebauch 0cd42b7217 Kill a spilled owner whose helper exits still tracing it, and check stale spill requests leave no acknowledgement 2026-12-05 05:38:01 -05:00
Kurt Himebauch f68a78c577 Keep the frozen clock, a pending rollback and late spills tracked when a resume cannot finish 2026-12-05 05:16:03 -05:00
Kurt Himebauch 6638a7dac8 Keep intercepted signals, discard checks and owner exit in the spill helper, and answer a cancelled spill 2026-12-05 05:16:03 -05:00
Kurt Himebauch c6333350ae Drop a spill request that reaches the handler after the resume it was asked before 2026-12-05 04:34:25 -05:00
Kurt Himebauch fbf1788647 Keep a spill without an acknowledgement asked, so a failed resume count still fails 2026-12-05 04:21:28 -05:00
Kurt Himebauch 48f587bb41 Wait only on spills whose handler started, and read back a late zram fallback 2026-12-05 04:15:28 -05:00
Kurt Himebauch 088e9994a0 Merge remote-tracking branch 'origin/main' into frozen-session-disk-spill 2026-12-05 04:08:34 -05:00
Kurt Himebauch 29350f1bd5 Fail the spill test when its readers do not go quiet before the measurement 2026-12-05 03:53:09 -05:00
Kurt Himebauch 498a3a653a Wait on resume for a spill that had not answered when the spill wait ended 2026-12-05 03:52:32 -05:00
Kurt Himebauch 644f8e655f Release zram fallbacks on resume and count late restores before another spill 2026-12-05 03:33:08 -05:00
Kurt Himebauch 7ad52166a2 Keep unanswered spills and unfinished restores tracked until a resume can release them 2026-12-05 03:02:57 -05:00
Kurt Himebauch f17406effc Bind a spill to the resume count it was asked under and report a resume only once memory is back 2026-12-04 22:49:06 -05:00
Kurt Himebauch ad6bb159d3 Write a sleeping session's memory to storage instead of zram 2026-12-04 12:53:14 -05:00
9 changed files with 2012 additions and 48 deletions

No files matched your search

@@ -972,6 +972,9 @@ object SessionPrefs {
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
/** A sleeping session writes its memory to storage instead of zram. */
fun diskSpill(context: Context): Boolean = prefs(context).getBoolean("diskSpill", false)
fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true)
fun setValveProtonOnDemand(context: Context, on: Boolean) {
@@ -111,6 +111,8 @@ class SessionService : Service() {
private var suspendOperationPending = false
private var pipTask = false
private var suspendAttemptFailed = false
private val resumeRecovery = SuspendRecovery()
private val retryResume = Runnable { updateSuspendPolicy() }
private var freezePending = false
private var freezeCancelled = false
private var pendingSteamGameId: String? = null
@@ -276,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 -> {
@@ -380,6 +382,8 @@ class SessionService : Service() {
suspendOperationPending = false
freezePending = false
suspendAttemptFailed = false
resumeRecovery.reset()
mainHandler.removeCallbacks(retryResume)
suspendController = null
SessionState.micAvailable = false
SessionState.micEnabled = false
@@ -977,7 +981,7 @@ class SessionService : Service() {
SessionEvents.record("session.paged_out", mapOf(
"processes" to processes, "unacknowledged" to unacknowledged, "residentMb" to residentKb / 1024,
"swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024, "ms" to millis,
))
), sessionDir)
}
},
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
@@ -990,7 +994,27 @@ class SessionService : Service() {
SessionEvents.record("session.paged_in", mapOf(
"processes" to processes, "swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024,
"availableMb" to availableKb / 1024, "ms" to millis,
))
), sessionDir)
}
},
spilled = { processes, spilledKb, residentKb, millis ->
Log.i(TAG, "wrote $processes processes to storage in $millis ms: ${spilledKb / 1024} MB, " +
"resident ${residentKb / 1024} MB")
mainHandler.post {
SessionEvents.record("session.spilled", mapOf(
"processes" to processes, "spilledMb" to spilledKb / 1024, "residentMb" to residentKb / 1024,
"ms" to millis,
), sessionDir)
}
},
restored = { processes, unacknowledged, residentKb, millis ->
Log.i(TAG, "restored $processes processes ($unacknowledged unacknowledged) from storage in $millis ms: " +
"resident ${residentKb / 1024} MB")
mainHandler.post {
SessionEvents.record("session.restored", mapOf(
"processes" to processes, "unacknowledged" to unacknowledged,
"residentMb" to residentKb / 1024, "ms" to millis,
), sessionDir)
}
},
)
@@ -1761,7 +1785,7 @@ class SessionService : Service() {
return
}
if (SessionState.suspended) {
resumeSession()
resumeSession(restartRecovery = false)
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
return
}
@@ -1930,8 +1954,10 @@ class SessionService : Service() {
private fun steamGameRunning(gameId: String): Boolean =
SteamGameProcess.running(gameId)
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
private fun resumeSession(panelVisible: Boolean = true, restartRecovery: Boolean = true) {
if (SessionState.suspended && (restartRecovery || resumeRecovery.due(SystemClock.elapsedRealtime()))) {
SessionState.resumeRequested = true
}
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
@@ -1942,6 +1968,7 @@ class SessionService : Service() {
completeNativeSleep()
completeSteamSleep()
suspendAttemptFailed = false
if (restartRecovery) resumeRecovery.reset()
updateSuspendPolicy()
}
@@ -2160,7 +2187,12 @@ class SessionService : Service() {
controller.cancelFreeze()
}
if (shouldSuspend && SessionState.suspended && !suspendOperationPending) SessionState.resumeRequested = false
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
// 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
SessionEvents.record(if (shouldSuspend) "session.suspend_requested" else "session.resume_requested", mapOf(
@@ -2175,9 +2207,9 @@ class SessionService : Service() {
freezeCancelled = false
val freezeSteamToken = steamSleepToken
val freezeNativeToken = nativeSleepToken
controller.freeze(
pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn,
) { success ->
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
@@ -2186,6 +2218,7 @@ class SessionService : Service() {
if (success) {
SessionState.suspended = true
SessionState.resumeFailed = false
resumeRecovery.reset()
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
releaseLocks()
refreshNotification()
@@ -2200,6 +2233,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()
}
@@ -2208,6 +2247,8 @@ class SessionService : Service() {
acquireLocks()
SessionState.resuming = true
controller.resume { success ->
// 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
@@ -2216,13 +2257,28 @@ class SessionService : Service() {
if (success) {
SessionState.suspended = false
SessionState.resumeFailed = false
suspendAttemptFailed = false
resumeRecovery.reset()
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.transition(SessionEvents.resumePhase(), "session.resume_lost_guest")
Log.w(TAG, "a game ended before its memory was read back from storage")
refreshNotification()
} else {
suspendAttemptFailed = true
SessionState.resumeFailures++
SessionState.resumeFailed = true
Log.w(TAG, "could not confirm that the session resumed")
resumeRecovery.failed(SystemClock.elapsedRealtime())?.let { mainHandler.postDelayed(retryResume, it) }
}
updateSuspendPolicy()
}
@@ -29,6 +29,8 @@ internal class SessionSuspendController(
{ _, _, _, _, _, _ -> },
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
private val spilled: (processes: Int, spilledKb: Long, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> },
private val restored: (processes: Int, unacknowledged: Int, residentKb: Long, millis: Long) -> Unit = { _, _, _, _ -> },
) {
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
@@ -53,10 +55,34 @@ internal class SessionSuspendController(
private var frozen = emptyList<ProcessRecord>()
private var frozenSince: Long? = null
private var pagedOutTargets = emptyList<ProcessRecord>()
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
// 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>()
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
// 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
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
@@ -74,7 +100,7 @@ internal class SessionSuspendController(
records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT)
}
}
if (pageOut) pageOut(records, root.pid, helpers)
if (pageOut) pageOut(records, root.pid, helpers, spill)
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
var previous: Map<TaskIdentity, Long>? = null
for (pass in 0 until FREEZE_MAX_PASSES) {
@@ -105,9 +131,14 @@ internal class SessionSuspendController(
frozen = records.values.toList()
if (complete && frozenSince == null) frozenSince = nowNanos()
if (!complete) {
if (restoreSafely(frozen)) frozen = emptyList()
// 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)
}
rollbackPending = !complete && frozen.isNotEmpty()
if (interrupted) Thread.currentThread().interrupt()
}
completion(complete)
@@ -122,12 +153,23 @@ internal class SessionSuspendController(
fun resume(completion: (Boolean) -> Unit) {
submit({
val records = frozen
advanceClock()
val advancedTo = advanceClock()
adopted = emptyList()
answeredLate = emptyList()
val running = startedAlive()
runAudio(resumeAudio)
val resumed = restoreSafely(records)
if (resumed) frozen = emptyList()
completion(resumed)
if (resumed) readBack()
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
val restoredAll = resumed && awaitRestored(running)
restoreOutstanding = frozen.isNotEmpty() || spilledTargets.isNotEmpty()
completion(restoredAll && !guestLost)
if (resumed) readBack(waitForRestore = false)
}, { completion(false) })
}
@@ -135,7 +177,10 @@ internal class SessionSuspendController(
closing = true
submit({
advanceClock()
val running = startedAlive()
if (restoreSafely(frozen)) frozen = emptyList()
// the teardown asks the guests to exit, which a process still reading back cannot answer
if (frozen.isEmpty()) awaitRestored(running, whileClosing = true)
completion()
executor.shutdown()
}, completion)
@@ -149,22 +194,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) {
@@ -275,13 +323,15 @@ internal class SessionSuspendController(
return tasks.takeIf { stopped && it.isNotEmpty() }
}
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>, spill: Boolean) {
val control = zramControl?.takeIf { it.isFile } ?: return
val hold = holdFile(control)
try {
hold.writeText(PAGE_OUT_REQUEST)
// A spill names the resume count it was asked under: any later count releases the helper, however
// late it starts reading.
hold.writeText(if (spill) "$SPILL_REQUEST ${resumeCount(control)}" else PAGE_OUT_REQUEST)
sleep(PAGE_OUT_POLL_MS)
pageOut(control, records, root, helpers)
if (spill) spill(control, records, root, helpers) else pageOut(control, records, root, helpers)
} catch (_: IOException) {
} finally {
hold.delete()
@@ -290,15 +340,208 @@ internal class SessionSuspendController(
private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold")
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
private fun ackFile(control: File, kind: String, record: ProcessRecord) =
File(control.parentFile, "${control.name}.$kind.${record.pid}")
private fun preloaded(records: Collection<ProcessRecord>) = records.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
} catch (_: IOException) {
false
}
}
private fun readAck(ack: File): Long? = try {
ack.readText().trim().toLongOrNull()
} catch (_: IOException) {
null
}
// Each process parks its threads, writes its private memory to an unlinked file and stays parked until
// the resume counter changes; its acknowledgement is the kB it wrote, 0 when it paged out to zram instead.
private fun spill(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
addSnapshot(records, root, helpers)
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
// A restore that finished after the last resume stopped waiting is counted before its marker goes; one
// still reading is not asked to spill again.
val (done, still) = spilledTargets.partition { settled(control, it) }
release(control, done)
spilledTargets = still
val targets = preloaded(records.values).filterNot { it in spilledTargets }
if (targets.isEmpty()) return
targets.forEach { ackFile(control, "ack", it).delete(); ackFile(control, "restored", it).delete() }
val start = nowMillis()
spillAsked = (spillAsked + targets).distinct()
for (record in targets) send(record, SIGURG)
val waiting = targets.toMutableList()
while (!closing && !cancelled && nowMillis() - start < SPILL_TIMEOUT_MS) {
val started = nowMillis() - start >= PAGE_OUT_START_MS
waiting.removeAll { val ack = ackFile(control, "ack", it); readAck(ack) != null || (started && !ack.exists()) || isGone(it) }
if (waiting.isEmpty()) break
sleep(PAGE_OUT_POLL_MS)
}
var total = 0L
val acks = targets.associateWith { readAck(ackFile(control, "ack", it)) }
val written = targets.filter { record ->
val kb = acks[record]?.coerceAtLeast(0L) ?: 0L
total += kb
kb > 0L
}
// A process that answered 0 paged out to zram instead and has no spill to release. One whose handler
// started (its acknowledgement is there, still empty) may still be writing: it is waited for like a
// 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] == null && ackFile(control, "ack", it).exists() && !isGone(it) }
spillAsked = spillAsked.filterNot { acks[it] == 0L || acks[it] == SPILL_CANCELLED }
spilledTargets = (spilledTargets + written + unanswered).distinct()
spillWritten = (spillWritten + written).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), 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 ||
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.
private fun release(control: File, settledTargets: List<ProcessRecord>) {
val lateZram = settledTargets.filter { readAck(ackFile(control, "ack", it)) == 0L && !isGone(it) }
pagedOutTargets = (pagedOutTargets + lateZram).distinct()
spillAsked = spillAsked.filterNot { it in settledTargets }
spillWritten = spillWritten.filterNot { it in settledTargets }
settledTargets.forEach {
ackFile(control, "restored", it).delete()
ackFile(control, "ack", it).delete()
}
}
private fun resumeFile(control: File) = File(control.parentFile, "${control.name}.resume")
private fun resumeCount(control: File): Long = try {
resumeFile(control).takeIf { it.isFile }?.readText()?.trim()?.toLongOrNull() ?: 0L
} catch (_: IOException) {
0L
}
// False when a process asked to spill may not have seen the new count: it would stay stopped. The count is
// put in place whole, so a failed write leaves the one before.
private fun bumpResume(): Boolean {
val control = zramControl?.takeIf { it.isFile } ?: return spillAsked.isEmpty()
// A late answer of 0 or a cancellation already let its process go: it needs no count.
val answered = spillAsked.filter {
val ack = readAck(ackFile(control, "ack", it))
ack == 0L || ack == SPILL_CANCELLED
}
if (answered.isNotEmpty()) {
answeredLate = (answeredLate + answered).distinct()
spilledTargets = spilledTargets.filterNot { it in answered }
release(control, answered)
}
val counter = resumeFile(control)
val ok = try {
val next = resumeCount(control) + 1
val fresh = File(counter.parentFile, "${counter.name}.new")
fresh.writeText(next.toString())
java.nio.file.Files.move(fresh.toPath(), counter.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING,
java.nio.file.StandardCopyOption.ATOMIC_MOVE)
resumeCount(control) == next
} catch (_: IOException) {
false
}
if (ok) spillAsked = emptyList()
return ok || spillAsked.isEmpty()
}
// 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(), whileClosing: Boolean = false): Boolean {
val control = zramControl ?: return true
val targets = spilledTargets
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).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 || 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()
if (lost.isNotEmpty()) guestLost = true
if (targets.isNotEmpty()) {
release(control, targets.filterNot { it in waiting })
spilledTargets = waiting.toList()
restored(targets.size, waiting.size, memoryKb(targets).first, nowMillis() - start)
}
return waiting.isEmpty() && lost.isEmpty()
}
// A process that wrote its spill is traced by its helper until the read-back ends; one that stays untraced
// and alive for a while has its memory back even if the helper could not write its marker (a helper that
// 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 || 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) {
false
File(entry, "stat").exists()
}
}
}
// 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).distinct().filter {
val ack = readAck(ackFile(control, "ack", it))
ack != 0L && ack != SPILL_CANCELLED && !ended(it)
}
}
private fun pageOut(control: File, records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
addSnapshot(records, root, helpers)
val targets = preloaded(records.values)
if (targets.isEmpty()) return
pagedOutTargets = (pagedOutTargets + targets).distinct()
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
@@ -325,7 +568,8 @@ internal class SessionSuspendController(
false
}
private fun readBack() {
private fun readBack(waitForRestore: Boolean = true) {
if (waitForRestore) awaitRestored()
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
val control = zramControl?.takeIf { it.isFile } ?: return
@@ -411,10 +655,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) {
@@ -431,6 +677,10 @@ internal class SessionSuspendController(
Role.HELPER_CHILD -> 3
}
}
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 ->
@@ -442,6 +692,15 @@ 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() && !ended(it) }
if (started.isNotEmpty()) spilledTargets = spilledTargets + started
adopted = started
}
private fun restoreSafely(records: List<ProcessRecord>): Boolean = try {
restore(records)
} catch (_: InterruptedException) {
@@ -460,10 +719,12 @@ internal class SessionSuspendController(
}
}
// A spilled process's threads stay in a tracing stop until its helper has read its memory back.
private fun isRunningOrGone(record: ProcessRecord): Boolean {
val current = try { readProcess(record.pid) } catch (_: Exception) { return false }
if (current == null || current.started != record.started) return true
if (current.state == 'T' || current.state == 't') return false
val spilled = record in spilledTargets
if (current.state == 'T' || (current.state == 't' && !spilled)) return false
return File(procRoot, "${record.pid}/task").listFiles().orEmpty().none { entry ->
entry.name.toIntOrNull() != null &&
try { readStat(File(entry, "stat"))[0].first() == 'T' } catch (_: IOException) { false }
@@ -477,6 +738,11 @@ internal class SessionSuspendController(
const val PAGE_OUT_ACK = "1"
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 MARKER_GRACE_MS = 1_000L
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
@@ -0,0 +1,29 @@
package com.droiddeck.launcher.session
// Paced resume retries for a session that is still held after a failed suspend or resume.
internal class SuspendRecovery(
private val maxAttempts: Int = 5,
private val firstDelayMs: Long = 5_000L,
) {
private var attempts = 0
private var nextAt = 0L
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++
if (attempts >= maxAttempts) return null
val delay = firstDelayMs shl (attempts - 1)
nextAt = now + delay
return delay
}
fun reset() {
attempts = 0
nextAt = 0L
}
}
@@ -124,6 +124,450 @@ class SessionSuspendControllerTest {
assertEquals(1, fixture.pagedIn.size)
}
@Test fun aSpillWritesThePreloadedGuestsToStorageBeforeTheyStop() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
assertEquals(listOf<String?>("4 0"), fixture.held)
assertTrue(fixture.signals.indexOfFirst { it.signal == URG } < fixture.signals.indexOfFirst { it.signal == STOP })
assertEquals(listOf(1 to 4_000_000L), fixture.spills)
assertTrue(fixture.pagedOut.isEmpty())
assertTrue(fixture.game.threads.all { it.state == 't' })
assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists())
assertFalse(File(fixture.control.parentFile, ".dd-zram.hold").exists())
}
@Test fun resumeMovesTheCounterBeforeContinuingAndWaitsForTheRestore() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val before = fixture.signals.size
var called = false
fixture.controller.resume {
// success is reported once the guest has its memory back and has left its tracing stop
assertTrue(it)
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' })
called = true
}
assertTrue(called)
assertEquals(listOf<String?>("1"), fixture.resumeAtContinue)
assertFalse(fixture.signals.drop(before).any { it.signal == URG })
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.pagedIn.isEmpty())
assertFalse(File(fixture.control.parentFile, ".dd-zram.restored.$GAME").exists())
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf<String?>("1", "2"), fixture.resumeAtContinue)
assertEquals(2, fixture.restores.size)
}
@Test fun aRestoreThatOutlastsTheWaitIsWaitedForAgainByTheNextResume() {
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) }
assertEquals(listOf(1 to 1), fixture.restores)
assertTrue(fixture.game.threads.all { it.state == 't' })
fixture.restoreDelayMs = 0L
var called = false
fixture.controller.resume {
assertTrue(it)
assertTrue(fixture.game.threads.none { thread -> thread.state == 't' })
called = true
}
assertTrue(called)
assertEquals(listOf(1 to 1, 1 to 0), fixture.restores)
}
@Test fun aResumeCountThatCannotBeWrittenFailsWhileASpillHasNotAnswered() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertFalse(it) }
assertFalse(File(fixture.control.parentFile, ".dd-zram.resume").isFile)
}
@Test fun aSpillThatAnswersAfterTheWaitIsStillRestoredOnResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.spillSilent = false
fixture.advance(1_000L)
assertTrue(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").isFile)
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.pagedIn.isEmpty())
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aGuestWithoutTheSpillHandlerIsNotWaitedForOnResume() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.restores.isEmpty())
}
@Test fun aSpillThatStartsAfterTheWaitFailsAResumeCountThatCannotBeWritten() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertFalse(it) }
}
@Test fun aSpillThatStartsAfterTheWaitIsReleasedByTheNextCount() {
val fixture = fixture(17)
fixture.control.writeText("0")
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)
assertEquals(1, fixture.readBacks)
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) }
assertEquals(listOf(1 to 0), fixture.restores)
assertEquals(0, fixture.readBacks)
assertEquals(4_000_000L, fixture.gameResident)
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 aHelperThatReadsBackBeforeTheContinueStillResumes() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
fixture.restoreDelayMs = 0L
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.releasedBeforeContinue)
assertEquals(listOf(1 to 0), fixture.restores)
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aLateSpillWithoutAnAcknowledgementFailsTheResumeUntilItsHelperLetsGo() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.handlerReplaced = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.ackFails = true
fixture.startLateSpill()
fixture.restoreDelayMs = 5_000L
fixture.controller.resume { assertFalse(it) }
assertTrue(fixture.game.threads.all { it.state == 't' })
fixture.advance(5_000L)
fixture.controller.resume { assertTrue(it) }
assertEquals(1, fixture.readBacks)
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aReadBackWhoseMarkerCouldNotBeWrittenEndsWhenTheHelperLetsGo() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.game.tracer = HELPER
fixture.sync()
fixture.markerFails = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
val start = fixture.now
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.now - start < 5_000L)
fixture.controller.freeze { assertTrue(it) }
fixture.controller.resume { assertTrue(it) }
}
@Test fun aLateFallbackDoesNotNeedTheCountWritten() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.spillSilent = false
fixture.spillFallsBack = true
fixture.advance(1_000L)
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertTrue(it) }
assertEquals(1, fixture.pagedIn.size)
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aCancelledFreezeWhoseRestoreDoesNotFinishLeavesTheRollbackPending() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.restoreDelayMs = 60_000L
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertTrue(fixture.controller.rollbackPending)
assertEquals(listOf(1 to 1), fixture.restores)
fixture.afterSleep = null
fixture.restoreDelayMs = 0L
fixture.controller.resume { assertTrue(it) }
assertFalse(fixture.controller.rollbackPending)
}
@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) }
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")
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() {
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")
fixture.spillSilent = true
fixture.controller.freeze(pageOut = true, spill = true) { }
fixture.spillSilent = false
fixture.spillFallsBack = true
fixture.advance(1_000L)
fixture.controller.resume { assertTrue(it) }
assertEquals(1, fixture.pagedIn.size)
}
@Test fun aGuestThatFellBackToZramResumesWhenTheCountCannotBeWritten() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillFallsBack = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
File(fixture.control.parentFile, ".dd-zram.resume.new").mkdirs()
fixture.controller.resume { assertTrue(it) }
assertTrue(fixture.game.threads.none { it.state == 't' || it.state == 'T' })
}
@Test fun aRestoreThatFinishedLateDoesNotHoldBackTheNextResume() {
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) }
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) }
fixture.controller.resume { assertTrue(it) }
}
@Test fun aGuestThatCouldNotSpillIsReadBackFromZram() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.spillFallsBack = true
fixture.controller.freeze(pageOut = true, spill = true) { assertTrue(it) }
assertEquals(listOf(0 to 0L), fixture.spills)
val before = fixture.signals.size
fixture.controller.resume { assertTrue(it) }
assertEquals(listOf(GAME), fixture.signals.drop(before).filter { it.signal == URG }.map { it.pid })
assertTrue(fixture.restores.isEmpty())
assertEquals(1, fixture.pagedIn.size)
}
@Test fun aSpillCutShortByACancelledFreezeIsStillRestored() {
val fixture = fixture(17)
fixture.control.writeText("0")
fixture.afterSleep = { if (fixture.spills.isNotEmpty()) fixture.controller.cancelFreeze() }
fixture.controller.freeze(pageOut = true, spill = true) { assertFalse(it) }
assertEquals(listOf<String?>("1"), fixture.resumeAtContinue)
assertEquals(listOf(1 to 0), fixture.restores)
}
@Test fun theMonitorIsHeldOffWhilePagingOutAndReadingBack() {
val fixture = fixture(17)
fixture.control.writeText("0")
@@ -485,7 +929,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)
@@ -493,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?>()
@@ -507,6 +965,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
@@ -522,9 +981,32 @@ class SessionSuspendControllerTest {
var unacknowledged = -1
var handlerStalls = false
var handlerReplaced = false
var spillFallsBack = false
var spillSilent = false
var restoreDelayMs = RESTORE_DELAY_MS
val spills = mutableListOf<Pair<Int, Long>>()
val restores = mutableListOf<Pair<Int, Int>>()
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
private var spilledBase: String? = null
private var restoring = false
private var restoredPending = false
private var gameStopPending = false
private var countSeenAt = -1L
private var gameContinued = false
var releasedBeforeContinue = false
var ackFails = false
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,
@@ -535,12 +1017,15 @@ class SessionSuspendControllerTest {
this.unacknowledged = unacknowledged
},
pagedIn = { processes, swap, swapBefore, _, _ -> pagedIn += Triple(processes, swap, swapBefore) },
spilled = { processes, spilledKb, _, _ -> spills += processes to spilledKb },
restored = { processes, unacknowledged, _, _ -> restores += processes to unacknowledged },
)
init { sync() }
private fun signal(pid: Int, signal: Int) {
signals += SentSignal(pid, signal)
helperStep()
val request = if (signal == URG) File(control.parentFile, "${control.name}.hold").takeIf { it.isFile }?.readText() else null
if (signal == URG) held += request
val group = groups.first { it.pid == pid }
@@ -550,14 +1035,34 @@ 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 == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
if (request?.startsWith("4") == true) {
if (!handlerReplaced) {
spilling = true
File(control.parentFile, "${control.name}.ack.$GAME").writeText("")
}
spilledBase = request.substringAfter(' ', "0").trim()
}
else if (request == "0") { pagingOut = false; pagingIn = true } else pagingOut = true
} else if (signal == CONT) {
if (pid == GAME) resumeAtContinue += resume.takeIf { it.isFile }?.readText()
if (clockAtContinue == null && clock.isFile) {
clockAtContinue = ByteBuffer.wrap(clock.readBytes()).order(ByteOrder.LITTLE_ENDIAN).long
}
continuing = true
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
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)) && !(pid == OTHER && otherHeld)) {
group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
}
}
sync()
}
@@ -565,14 +1070,88 @@ 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() {
countSeenAt = -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
fun startLateSpill() {
handlerReplaced = false
spilling = true
if (!ackFails) File(control.parentFile, "${control.name}.ack.$GAME").writeText("")
}
// The helper reads back as soon as it sees a new count, SIGCONT or not; it detaches first and publishes
// its marker on a later step.
private fun helperStep() {
val count = resume.takeIf { it.isFile }?.readText()?.trim() ?: "0"
if (restoredPending) {
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
gameContinued = false
}
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
}
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 (lateSpillSeesTheCount && count != spilledBase) {
ack.writeText("-2")
releaseGame()
} else if (spillFallsBack) {
gameSwapKb += gameResidentKb
gameResidentKb = 0L
ack.writeText("0")
} else {
if (!ackFails) ack.writeText(gameResidentKb.toString())
gameResidentKb = 0L
restoring = true
}
}
helperStep()
if (pagingOut && !handlerReplaced) {
File(control.parentFile, "${control.name}.ack.$GAME").apply { if (!exists()) writeText("") }
}
@@ -591,7 +1170,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()
@@ -611,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()
@@ -619,6 +1198,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")
}
}
}
@@ -661,5 +1241,8 @@ class SessionSuspendControllerTest {
const val STOP = 19
const val CONT = 18
const val URG = 23
const val RESTORE_DELAY_MS = 300L
const val HELPER = 300
const val OTHER = 400
}
}
@@ -0,0 +1,95 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class SuspendRecoveryTest {
@Test fun theFirstAttemptIsDueAtOnceAndLaterOnesBackOff() {
val recovery = SuspendRecovery(maxAttempts = 3, firstDelayMs = 1_000L)
assertTrue(recovery.due(0L))
assertEquals(1_000L, recovery.failed(0L))
assertFalse(recovery.due(999L))
assertTrue(recovery.due(1_000L))
assertEquals(2_000L, recovery.failed(1_000L))
assertFalse(recovery.due(2_999L))
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 }
}
}
// Only a scheduled retry or a poll runs a pass; time with neither runs nothing.
fun runUntil(end: Long, pollMs: Long? = null) {
while (true) {
val nextPoll = pollMs?.let { now - now % it + it } ?: Long.MAX_VALUE
val next = minOf(nextPoll, scheduled.firstOrNull() ?: Long.MAX_VALUE)
if (next > end) break
now = next
scheduled.remove(next)
pass()
}
now = end
}
}
@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)
assertEquals(listOf(5_000L), service.scheduled.toList())
service.counterWritable = true
service.runUntil(4_999L)
assertTrue(service.suspended)
service.runUntil(5_000L)
assertFalse(service.suspended)
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)
assertNull(recovery.failed(1_000L))
assertFalse(recovery.due(1_000_000L))
recovery.reset()
assertTrue(recovery.due(0L))
}
}
+16
View File
@@ -97,6 +97,22 @@ out, and resuming reads it back when available memory is at least twice what tho
have in swap at that moment and, after it, 1 GiB or a tenth of RAM, whichever is larger, stays
available.
## Writing a sleeping session to storage
With the `diskSpill` session pref on, the suspend for sleep writes each preloaded process's
private memory to storage instead of zram (request `4`). The preload's worker starts a helper
process that shares the process's memory, stops every other thread with ptrace (which also holds
threads that block every signal, as Mesa's queue threads do, and which `SIGCONT` does not undo),
writes readable private anonymous memory to an unlinked file next to the control file, drops it,
and answers the kB it wrote in `/tmp/.dd-zram.ack.<pid>`. Regions registered with userfaultfd,
locked or I/O memory and the preload's own memory stay. The app adds one to
`/tmp/.dd-zram.resume` before it continues any process; the helper then reads everything back
(through `/proc/<pid>/mem` where the pages are not writable), answers `/tmp/.dd-zram.restored.<pid>`
and lets the threads go. A process that cannot be traced answers `0` and pages out to zram instead.
On an AYN Thor with Bully at its menu, 30 processes wrote 1,227 MB in 2.1 seconds and read it
back in 1.3 seconds; system anonymous memory fell from 2.53 to 1.21 GB while asleep.
## Threads
When a worker can be started, page-out runs outside the game's threads. The preload's signal
+464 -10
View File
@@ -13,6 +13,8 @@
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <time.h>
#if defined(__i386__)
#include <asm/ldt.h>
#endif
@@ -40,7 +42,18 @@
#define ZR_INLINE_KB (32UL << 10)
#define ZR_INLINE_CHUNKS 512UL
#define ZR_FAILED (~0UL)
#define ZR_CANCELLED (-2L)
#define ZR_FUTEX_WAIT 0
#define ZR_PTRACE_DETACH 17
#define ZR_PTRACE_SEIZE 0x4206
#define ZR_PTRACE_INTERRUPT 0x4207
#define ZR_PTRACE_SETOPTIONS 0x4200
#define ZR_PTRACE_O_EXITKILL (1 << 20)
#define ZR_SPILL_CHUNK (8UL << 20)
#define ZR_SPILL_RUNS ((16UL << 20) / sizeof(struct zr_run))
#define ZR_SPILL_TIDS 8192
#define ZR_PARK_MS 3000
#define ZR_RESUME_POLL_MS 50
#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)
@@ -206,6 +219,23 @@ static struct zr_slot {
static uint16_t zr_gen = 1;
static unsigned long zr_cursor;
static unsigned long zr_visits;
static struct zr_run {
unsigned long addr, len, off, writable;
} *zr_runs;
static char *zr_bounce;
static unsigned long zr_run_count;
static long zr_owner;
static long zr_reaper;
static int zr_seized;
static int zr_tids[ZR_SPILL_TIDS];
static signed char zr_stopped[ZR_SPILL_TIDS];
static unsigned char zr_signals[ZR_SPILL_TIDS];
static char *zr_helper_stack;
static int zr_helper_done;
static int zr_helper_discarded;
static int zr_helper_released;
static unsigned long zr_helper_spilled;
static unsigned long zr_baseline; // the resume count the spill was asked under
static int zr_prefix(const char *text, const char *prefix) {
while (*prefix)
@@ -213,6 +243,11 @@ static int zr_prefix(const char *text, const char *prefix) {
return 1;
}
// A named mapping never merges with the game's anonymous memory, so excluding it from a spill excludes only it.
static void zr_name(long addr, unsigned long len) {
zr_sys(SYS_prctl, 0x53564d41, 0, addr, len, "dd-zram");
}
static char *zr_find(char *text, char c, size_t n) {
for (; n > 0; n--, text++)
if (*text == c) return text;
@@ -221,11 +256,15 @@ static char *zr_find(char *text, char c, size_t n) {
static char zr_ctl[ZR_PATH] = ZR_CTL;
static char zr_hold[ZR_PATH + sizeof(".hold")];
static char zr_resume[ZR_PATH + sizeof(".resume")];
static int zr_open(const char *path) {
return (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC, 0);
}
// The number after a request's mode: kB to trim, or for a spill the resume count it was asked under.
static unsigned long zr_request_arg;
static int zr_mode(unsigned long *want) {
char text[24];
long n = 0;
@@ -240,12 +279,13 @@ static int zr_mode(unsigned long *want) {
n = zr_sys(SYS_read, fd, text, sizeof(text));
zr_sys(SYS_close, fd);
}
if (n < 1 || text[0] < '0' || text[0] > '3') return -1;
if (n < 1 || text[0] < '0' || text[0] > '4') return -1;
unsigned long kb = 0;
for (long i = 2; i < n && text[i] >= '0' && text[i] <= '9'; i++)
kb = kb * 10 + (unsigned long)(text[i] - '0');
zr_request_arg = kb;
*want = kb / (zr_page / 1024);
if (text[0] >= '2' && *want == 0) return -1;
if ((text[0] == '2' || text[0] == '3') && *want == 0) return -1;
return text[0] - '0';
}
@@ -420,42 +460,445 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
return done;
}
static void zr_ack(long value, int trim) {
const char *suffix = trim ? ".trim." : ".ack.";
char path[sizeof(zr_ctl) + sizeof(".trim.") + 20];
static void zr_ack(long value, const char *suffix) {
char path[sizeof(zr_ctl) + sizeof(".restored.") + 20];
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);
long pid = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE);
if (pid == 0) 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;
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
if (fd < 0) return;
n = 0;
if (value < -1) {
path[n++] = '-';
value = -value;
}
for (d = 0; value >= 0 && (d == 0 || value > 0); value /= 10) digits[d++] = (char)('0' + value % 10);
for (n = 0; d > 0;) path[n++] = digits[--d];
while (d > 0) path[n++] = digits[--d];
if (n > 0) zr_sys(SYS_write, fd, path, n);
zr_sys(SYS_close, fd);
}
#if defined(__aarch64__)
static int zr_read_small(const char *path, char *text, long size) {
int fd = zr_open(path);
if (fd < 0) return 0;
long n;
do n = zr_sys(SYS_read, fd, text, size); while (n == -EINTR);
zr_sys(SYS_close, fd);
return n > 0 ? (int)n : 0;
}
static void zr_nap(int *word, int value, long ms) {
struct { long sec, nsec; } wait = {ms / 1000, ms % 1000 * 1000000};
zr_sys(SYS_futex, word, ZR_FUTEX_WAIT, value, &wait, NULL, 0);
}
static long zr_now_ms(void) {
struct { long sec, nsec; } now = {0, 0};
zr_sys(SYS_clock_gettime, CLOCK_MONOTONIC, &now);
return now.sec * 1000 + now.nsec / 1000000;
}
static size_t zr_digits(char *out, long value) {
char digits[20];
size_t d = 0, n = 0;
do digits[d++] = (char)('0' + value % 10); while ((value /= 10) > 0);
while (d > 0) out[n++] = digits[--d];
return n;
}
static int zr_seized_index(long tid) {
for (int i = 0; i < zr_seized; i++)
if (zr_tids[i] == tid) return i;
return -1;
}
// Seizes and interrupts the owner's threads it has not seized yet; returns how many it added, or -1.
static long zr_seize_new(void) {
char path[48] = "/proc/";
size_t n = 6 + zr_digits(path + 6, zr_owner);
for (const char *p = "/task"; *p; p++) path[n++] = *p;
path[n] = 0;
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0);
if (fd < 0) return -1;
long added = 0, got;
while ((got = zr_sys(SYS_getdents64, fd, zr_maps, sizeof(zr_maps))) > 0) {
for (long at = 0; at < got;) {
unsigned short reclen = *(unsigned short *)(zr_maps + at + 16);
const char *name = zr_maps + at + 19;
at += reclen;
long tid = 0;
for (const char *p = name; *p >= '0' && *p <= '9'; p++) tid = tid * 10 + (*p - '0');
if (tid <= 0 || tid == zr_reaper || zr_seized_index(tid) >= 0) continue;
if (zr_seized == ZR_SPILL_TIDS) {
added = -1;
break;
}
long r = zr_sys(SYS_ptrace, ZR_PTRACE_SEIZE, tid, 0, 0);
if (r == -ESRCH) continue;
if (r < 0) {
added = -1;
break;
}
zr_tids[zr_seized] = (int)tid;
zr_signals[zr_seized] = 0;
zr_stopped[zr_seized++] = 0;
zr_sys(SYS_ptrace, ZR_PTRACE_INTERRUPT, tid, 0, 0);
added++;
}
if (added < 0) break;
}
zr_sys(SYS_close, fd);
return got < 0 ? -1 : added;
}
static void zr_detach_all(void) {
for (int i = 0; i < zr_seized; i++)
if (zr_stopped[i] >= 0) zr_sys(SYS_ptrace, ZR_PTRACE_DETACH, zr_tids[i], 0, zr_signals[i]);
zr_seized = 0;
}
// A thread stopped by ptrace stays stopped whatever its signal mask, and SIGCONT does not start it again:
// only the detach after the restore does.
static int zr_seize_all(void) {
zr_seized = 0;
long start = zr_now_ms(), added;
int idle = 0;
do {
added = zr_seize_new();
if (added < 0) return 0;
for (;;) {
int status, waiting = 0;
long tid;
while ((tid = zr_sys(SYS_wait4, -1, &status, __WALL | WNOHANG, NULL)) > 0) {
int i = zr_seized_index(tid);
if (i < 0) continue;
zr_stopped[i] = WIFSTOPPED(status) ? 1 : -1;
// A signal that reached the thread before the interrupt stops it in that signal's delivery, which a
// detach without the signal would drop.
if (WIFSTOPPED(status) && (status >> 16) == 0) zr_signals[i] = (unsigned char)WSTOPSIG(status);
}
for (int i = 0; i < zr_seized; i++) waiting += zr_stopped[i] == 0;
if (waiting == 0) break;
if (zr_now_ms() - start >= ZR_PARK_MS) return 0;
zr_nap(&idle, 0, 2);
}
} while (added > 0);
return 1;
}
// The spill must not drop the memory it runs on: the stacks, this file's state and the run index.
static int zr_own(unsigned long start, unsigned long end) {
const unsigned long marks[] = {
(unsigned long)zr_slots, (unsigned long)&zr_owner, (unsigned long)zr_maps, (unsigned long)zr_entries,
(unsigned long)zr_tids, (unsigned long)zr_stack, (unsigned long)zr_runs, (unsigned long)zr_helper_stack,
(unsigned long)zr_bounce,
};
for (unsigned long i = 0; i < sizeof(marks) / sizeof(marks[0]); i++)
if (marks[i] >= start && marks[i] < end) return 1;
return 0;
}
static int zr_flag(const char *flags, char a, char b) {
for (const char *p = flags; p[0] && p[1]; p++)
if (p[0] == a && p[1] == b && (p == flags || p[-1] == ' ') && (p[2] == ' ' || p[2] == 0 || p[2] == '\n'))
return 1;
return 0;
}
// Private anonymous memory that can be read, whatever else its protection allows now.
static int zr_spillable(const char *line, unsigned long *start, unsigned long *end, int *writable) {
const char *p = line;
*start = zr_hex(&p);
if (*p++ != '-') return 0;
*end = zr_hex(&p);
if (*p++ != ' ' || p[0] != 'r' || p[3] != 'p') return 0;
*writable = p[1] == 'w';
for (int field = 0; field < 4; field++) {
while (*p && *p != ' ') p++;
while (*p == ' ') p++;
}
return *p == 0 || zr_prefix(p, "[heap]") || zr_prefix(p, "[stack]") || zr_prefix(p, "[anon:");
}
static long zr_io(long call, int fd, unsigned long addr, unsigned long len, unsigned long off, int *direct) {
unsigned long done = 0;
while (done < len) {
unsigned long step = len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : len - done;
long n = zr_sys(call, fd, addr + done, step, off + done);
if (n == -EINTR) continue;
if (n == -EINVAL && *direct) {
long flags = zr_sys(SYS_fcntl, fd, F_GETFL);
if (flags < 0 || zr_sys(SYS_fcntl, fd, F_SETFL, flags & ~O_DIRECT) < 0) return -1;
*direct = 0;
continue;
}
if (n <= 0) return -1;
// f2fs on an encrypted volume may serve O_DIRECT through the page cache without saying so.
if (call == SYS_pwrite64) zr_sys(SYS_sync_file_range, fd, off + done, n, 7);
zr_sys(SYS_fadvise64, fd, off + done, n, 4);
done += (unsigned long)n;
}
return 0;
}
// Pages that cannot be written in place go back through /proc/<pid>/mem, which the tracer may write.
static int zr_restore_run(int fd, int mem, const struct zr_run *run, int *direct) {
if (run->writable) return (int)zr_io(SYS_pread64, fd, run->addr, run->len, run->off, direct);
for (unsigned long done = 0; done < run->len; done += ZR_SPILL_CHUNK) {
unsigned long step = run->len - done > ZR_SPILL_CHUNK ? ZR_SPILL_CHUNK : run->len - done;
if (mem < 0 || zr_io(SYS_pread64, fd, (unsigned long)zr_bounce, step, run->off + done, direct) < 0) return -1;
for (unsigned long put = 0; put < step;) {
long n = zr_sys(SYS_pwrite64, mem, zr_bounce + put, step - put, run->addr + done + put);
if (n == -EINTR) continue;
if (n <= 0) return -1;
put += (unsigned long)n;
}
}
return 0;
}
static unsigned long zr_spill_range(int pagemap, int fd, unsigned long start, unsigned long end, int writable,
unsigned long *off, int *direct, int *full) {
unsigned long spilled = 0;
for (unsigned long addr = start; addr < end && !*full;) {
unsigned long count = (end - addr) / zr_page;
if (count > ZR_BATCH) count = ZR_BATCH;
if (zr_sys(SYS_lseek, pagemap, (long)(addr / zr_page * sizeof(uint64_t)), SEEK_SET) < 0) return spilled;
long got = zr_sys(SYS_read, pagemap, zr_entries, count * sizeof(uint64_t));
if (got < (long)sizeof(uint64_t)) return spilled;
unsigned long pages = (unsigned long)got / sizeof(uint64_t);
for (unsigned long i = 0; i < pages && !*full;) {
if (!(zr_entries[i] & (ZR_PRESENT | ZR_SWAPPED))) {
i++;
continue;
}
unsigned long j = i;
while (j < pages && (zr_entries[j] & (ZR_PRESENT | ZR_SWAPPED))) j++;
unsigned long from = addr + i * zr_page, len = (j - i) * zr_page;
if (zr_run_count == ZR_SPILL_RUNS || zr_io(SYS_pwrite64, fd, from, len, *off, direct) < 0) {
*full = 1;
break;
}
zr_helper_discarded = 1;
if (zr_sys(SYS_madvise, from, len, MADV_DONTNEED) == 0) {
zr_runs[zr_run_count++] = (struct zr_run){from, len, *off, (unsigned long)writable};
*off += len;
spilled += len;
}
i = j;
}
addr += pages * zr_page;
}
return spilled;
}
static unsigned long zr_spill_all(int fd, int *direct) {
int smaps = zr_open("/proc/self/smaps");
int pagemap = zr_open("/proc/self/pagemap");
unsigned long spilled = 0, off = 0, s = 0, e = 0;
int take = 0, full = 0, writable = 0;
size_t have = 0;
while (smaps >= 0 && pagemap >= 0 && !full) {
long n = zr_sys(SYS_read, smaps, zr_maps + have, sizeof(zr_maps) - 1 - have);
if (n == -EINTR) continue;
if (n <= 0) break;
have += (size_t)n;
zr_maps[have] = 0;
char *line = zr_maps, *nl;
while (!full && (nl = zr_find(line, '\n', have - (size_t)(line - zr_maps))) != NULL) {
*nl = 0;
if ((line[0] >= '0' && line[0] <= '9') || (line[0] >= 'a' && line[0] <= 'f')) {
take = zr_spillable(line, &s, &e, &writable) && e > s && !zr_own(s, e);
} else if (take && zr_prefix(line, "VmFlags:")) {
const char *flags = line + 8;
// Tagged memory (mt) stays: dropping its pages drops the tags, which reading the bytes back cannot restore.
if (!zr_flag(flags, 'u', 'm') && !zr_flag(flags, 'u', 'w') && !zr_flag(flags, 'l', 'o') &&
!zr_flag(flags, 'i', 'o') && !zr_flag(flags, 'p', 'f') && !zr_flag(flags, 'm', 't'))
spilled += zr_spill_range(pagemap, fd, s, e, writable, &off, direct, &full);
take = 0;
}
line = nl + 1;
}
have -= (size_t)(line - zr_maps);
for (size_t i = 0; i < have; i++) zr_maps[i] = line[i];
if (have == sizeof(zr_maps) - 1) have = 0;
}
if (pagemap >= 0) zr_sys(SYS_close, pagemap);
if (smaps >= 0) zr_sys(SYS_close, smaps);
return spilled;
}
static int zr_spill_file(void) {
char path[sizeof(zr_ctl) + sizeof(".spill.") + 20];
char digits[20];
size_t n = 0, d = 0;
for (const char *p = zr_ctl; *p; p++) path[n++] = *p;
for (const char *p = ".spill."; *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;
int fd = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC | O_DIRECT, 0600);
if (fd >= 0 && zr_sys(SYS_unlinkat, AT_FDCWD, path, 0) < 0) {
zr_sys(SYS_close, fd);
return -1;
}
return fd;
}
// A count other than the request's; a marker that cannot be read is no resume.
static int zr_resumed(void) {
char now[24];
int got = zr_read_small(zr_resume, now, sizeof(now));
unsigned long count = 0;
int digits = 0;
for (int i = 0; i < got && now[i] >= '0' && now[i] <= '9'; i++, digits++) count = count * 10 + (unsigned long)(now[i] - '0');
return digits > 0 && count != zr_baseline;
}
// Runs in a process that shares the owner's memory, so it keeps running while every owner thread is stopped.
// Once pages are dropped, the owner must not outlive a helper that ends without detaching: the kernel kills
// every thread still traced when its tracer exits. Only a stopped tracee takes options, which all are here.
static int zr_exit_kill(void) {
for (int i = 0; i < zr_seized; i++) {
if (zr_stopped[i] <= 0) continue;
long r = zr_sys(SYS_ptrace, ZR_PTRACE_SETOPTIONS, zr_tids[i], 0, ZR_PTRACE_O_EXITKILL);
if (r < 0 && r != -ESRCH) return 0;
}
return 1;
}
static void zr_helper(void) {
zr_sys(SYS_prctl, PR_SET_NAME, "zr-spill");
if (!zr_seize_all() || zr_resumed() || !zr_exit_kill()) {
zr_detach_all();
return;
}
int fd = zr_spill_file();
if (fd < 0) {
zr_detach_all();
return;
}
int direct = 1, idle = 0;
zr_run_count = 0;
unsigned long spilled = zr_spill_all(fd, &direct);
zr_helper_spilled = spilled;
zr_helper_done = 1;
// nothing written (a full volume): the owner pages out to zram instead and acknowledges that
if (spilled > 0) {
zr_ack((long)(spilled / 1024), ".ack.");
while (!zr_resumed()) {
// reparented: the owner is gone and there is nothing to read back into
if (zr_sys(SYS_getppid) != zr_owner) {
zr_sys(SYS_close, fd);
return;
}
zr_nap(&idle, 0, ZR_RESUME_POLL_MS);
}
long start = zr_now_ms();
char path[48] = "/proc/";
size_t n = 6 + zr_digits(path + 6, zr_owner);
for (const char *p = "/mem"; *p; p++) path[n++] = *p;
path[n] = 0;
int mem = (int)zr_sys(SYS_openat, AT_FDCWD, path, O_RDWR | O_CLOEXEC, 0);
int restored = 1;
for (unsigned long i = 0; i < zr_run_count; i++) {
if (zr_restore_run(fd, mem, &zr_runs[i], &direct) < 0) {
zr_sys(SYS_kill, zr_owner, SIGKILL);
restored = 0;
}
}
if (mem >= 0) zr_sys(SYS_close, mem);
zr_sys(SYS_close, fd);
zr_helper_released = restored;
zr_detach_all();
// after the detach, so a controller that sees the marker finds the process out of its tracing stop
if (restored) zr_ack(zr_now_ms() - start, ".restored.");
return;
}
zr_helper_released = 1;
zr_sys(SYS_close, fd);
zr_detach_all();
}
static void *zr_area(unsigned long len) {
long area = zr_sys(ZR_MMAP, 0, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if ((unsigned long)area > -4096UL) return NULL;
zr_name(area, len);
return (void *)area;
}
static int zr_spill(void) {
if (zr_runs == NULL) zr_runs = zr_area(ZR_SPILL_RUNS * sizeof(struct zr_run));
if (zr_helper_stack == NULL) zr_helper_stack = zr_area(ZR_STACK);
if (zr_bounce == NULL) zr_bounce = zr_area(ZR_SPILL_CHUNK);
if (zr_runs == NULL || zr_helper_stack == NULL || zr_bounce == NULL) return 0;
zr_baseline = zr_request_arg;
zr_helper_done = 0;
zr_helper_spilled = 0;
zr_helper_discarded = 0;
zr_helper_released = 0;
zr_reaper = zr_sys(SYS_gettid);
__atomic_store_n(&zr_owner, zr_sys(SYS_getpid), __ATOMIC_RELEASE);
long child = zr_clone(CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SYSVSEM, zr_helper_stack + ZR_STACK, NULL, NULL, NULL);
if (child > 0) {
int status;
while (zr_sys(SYS_wait4, child, &status, __WALL, NULL) == -EINTR) {
}
// A helper that ended between dropping pages and reading them back took them with it.
if (zr_helper_discarded && !zr_helper_released) zr_sys(SYS_kill, zr_sys(SYS_getpid), SIGKILL);
}
__atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE);
return child > 0 && zr_helper_done && zr_helper_spilled > 0;
}
#endif
static void zr_request(int worker) {
unsigned long want = 0;
int mode = zr_mode(&want);
if (mode < 0) return;
if (mode == 4) {
// A request that reaches this after the resume it was asked before has nothing left to do: the
// controller no longer waits for it, and holding the process now would stop it after the resume.
#if defined(__aarch64__)
zr_baseline = zr_request_arg;
if (zr_resumed()) return;
#endif
zr_ack(-1, ".ack.");
#if defined(__aarch64__)
if (worker && zr_spill()) return;
// it acknowledged the start, so the controller waits for a final answer
if (zr_resumed()) {
zr_ack(ZR_CANCELLED, ".ack.");
return;
}
#endif
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
zr_walk(1, 1, 0, 0);
zr_gen++;
zr_ack(0, ".ack.");
return;
}
if (!worker && want > ZR_INLINE_KB / (zr_page / 1024)) want = ZR_INLINE_KB / (zr_page / 1024);
zr_visits = worker ? ZR_FAILED : ZR_INLINE_CHUNKS;
if (mode > 0) zr_ack(-1, mode > 1);
if (mode > 0) zr_ack(-1, mode > 1 ? ".trim." : ".ack.");
if (mode < 2) {
zr_walk(mode, 1, 0, 0);
zr_gen++;
if (mode == 1) zr_ack(1, 0);
if (mode == 1) zr_ack(1, ".ack.");
return;
}
unsigned long from = zr_cursor;
unsigned long done = zr_walk(mode, want, from, ~0UL);
if (done < want && from > 0) done += zr_walk(mode, want - done, 0, from);
zr_ack((long)(done * (zr_page / 1024)), 1);
zr_ack((long)(done * (zr_page / 1024)), ".trim.");
}
static void zr_drain(int worker) {
@@ -467,6 +910,13 @@ static void zr_drain(int worker) {
}
void zr_thread(void) {
#if defined(__aarch64__)
long owner = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE);
if (owner != 0 && zr_sys(SYS_getpid) != owner) {
zr_helper();
return;
}
#endif
zr_sys(SYS_prctl, PR_SET_NAME, "zr-worker");
zr_drain(1);
}
@@ -524,6 +974,7 @@ static int zr_start(void) {
MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0);
if ((unsigned long)base > -4096UL) return 0;
zr_stack = (char *)base;
zr_name(base, ZR_STACK);
}
struct { long sec, nsec; } wait = {0, 5000000};
for (int i = 0; i < 20 && __atomic_load_n(&zr_stack_busy, __ATOMIC_ACQUIRE); i++)
@@ -579,6 +1030,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) {
}
static void zr_child(void) {
__atomic_store_n(&zr_owner, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_requests, 0, __ATOMIC_RELEASE);
__atomic_store_n(&zr_stack_busy, 0, __ATOMIC_RELEASE);
}
@@ -595,6 +1047,8 @@ static void zr_paths(void) {
size_t n = strlen(zr_ctl);
memcpy(zr_hold, zr_ctl, n);
memcpy(zr_hold + n, ".hold", sizeof(".hold"));
memcpy(zr_resume, zr_ctl, n);
memcpy(zr_resume + n, ".resume", sizeof(".resume"));
}
__attribute__((constructor)) static void zr_init(void) {
+462
View File
@@ -0,0 +1,462 @@
import os
from pathlib import Path
import platform
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#define THREADS 4
struct shared {
volatile long progress;
volatile long errors;
volatile int stop;
volatile int quiet; // readers leave the blocks alone (a page-out they would undo is being measured)
volatile int quieted; // readers that have stopped reading
volatile long touched; // pages readers have looked at, counted as they go
};
static const char *ctl;
static size_t size;
static int block_urg;
static struct shared *shared;
static unsigned char *blocks[THREADS];
static void fill(unsigned char *p, size_t n, unsigned seed) {
for (size_t i = 0; i < n; i++) p[i] = (unsigned char)((i * 2654435761u + seed) >> 7);
}
static int same(const unsigned char *p, size_t n, unsigned seed) {
for (size_t i = 0, next = 0; i < n; i += 61) {
if (i >= next) {
__atomic_add_fetch(&shared->touched, 1, __ATOMIC_RELAXED);
next = i + 4096;
}
if (p[i] != (unsigned char)((i * 2654435761u + seed) >> 7)) return 0;
}
return 1;
}
static void *work(void *arg) {
long id = (long)arg;
if (block_urg && id == 0) {
sigset_t set;
sigfillset(&set);
pthread_sigmask(SIG_BLOCK, &set, NULL);
}
unsigned seed = (unsigned)id * 77u + 1u;
int idle = 0;
while (!shared->stop) {
if (shared->quiet) {
if (!idle) {
idle = 1;
__atomic_add_fetch(&shared->quieted, 1, __ATOMIC_RELEASE);
}
continue;
}
if (idle) {
idle = 0;
__atomic_sub_fetch(&shared->quieted, 1, __ATOMIC_RELEASE);
}
if (!same(blocks[id], size, seed)) __atomic_add_fetch(&shared->errors, 1, __ATOMIC_RELAXED);
__atomic_add_fetch(&shared->progress, 1, __ATOMIC_RELAXED);
}
return NULL;
}
static void put(const char *suffix, const char *text) {
char path[512];
snprintf(path, sizeof(path), "%s%s", ctl, suffix);
FILE *f = fopen(path, "w");
if (!f) exit(20);
fputs(text, f);
fclose(f);
}
static long get(const char *suffix, pid_t pid) {
char path[512], text[32] = {0};
snprintf(path, sizeof(path), "%s%s%d", ctl, suffix, pid);
FILE *f = fopen(path, "r");
if (!f) return -2;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
return n == 0 ? -1 : atol(text);
}
static long rss_kb(pid_t pid) {
char path[64], line[256];
long kb = -1;
snprintf(path, sizeof(path), "/proc/%d/status", pid);
FILE *f = fopen(path, "r");
while (f && fgets(line, sizeof(line), f))
if (!strncmp(line, "VmRSS:", 6)) kb = atol(line + 6);
if (f) fclose(f);
return kb;
}
static void nap(long ms) {
struct timespec t = {ms / 1000, ms % 1000 * 1000000};
nanosleep(&t, NULL);
}
static long wait_for(const char *suffix, pid_t pid, long ms) {
for (long waited = 0; waited < ms; waited += 20) {
long v = get(suffix, pid);
if (v >= 0) return v;
nap(20);
}
return -3;
}
static pid_t find_helper(pid_t owner) {
DIR *proc = opendir("/proc");
struct dirent *entry;
while (proc && (entry = readdir(proc)) != NULL) {
pid_t pid = (pid_t)atoi(entry->d_name);
if (pid <= 0) continue;
char path[64], text[512];
snprintf(path, sizeof(path), "/proc/%d/stat", pid);
FILE *f = fopen(path, "r");
if (!f) continue;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
text[n] = 0;
char *close = strrchr(text, ')');
int ppid = 0;
if (strstr(text, "(zr-spill)") && close && sscanf(close + 2, "%*c %d", &ppid) == 1 && ppid == owner) {
closedir(proc);
return pid;
}
}
if (proc) closedir(proc);
return -1;
}
static int thread_in_state(pid_t pid, char state) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/task", pid);
DIR *tasks = opendir(path);
struct dirent *entry;
int found = 0;
while (tasks && !found && (entry = readdir(tasks)) != NULL) {
if (atoi(entry->d_name) <= 0) continue;
char stat[64], text[512];
snprintf(stat, sizeof(stat), "/proc/%d/task/%s/stat", pid, entry->d_name);
FILE *f = fopen(stat, "r");
if (!f) continue;
size_t n = fread(text, 1, sizeof(text) - 1, f);
fclose(f);
text[n] = 0;
char *close = strrchr(text, ')');
found = close && close[1] == ' ' && close[2] == state;
}
if (tasks) closedir(tasks);
return found;
}
int main(int argc, char **argv) {
if (argc > 1 && !strcmp(argv[1], "probe")) {
// whether a child may seize its parent, as the spill helper does (Yama's ptrace_scope 1 refuses)
pid_t parent = getpid(), probe = fork();
if (probe == 0) _exit(ptrace(PTRACE_SEIZE, parent, 0, 0) == 0 ? 0 : 1);
int status = 0;
waitpid(probe, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 1;
}
if (argc > 1 && !strcmp(argv[1], "pageout")) {
// whether this host pages anonymous memory out at all (swap, and a kernel that is not emulated)
size_t n = 64u << 20;
unsigned char *p = mmap(NULL, n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (p == MAP_FAILED) return 1;
fill(p, n, 3);
long before = rss_kb(getpid());
madvise(p, n, 21 /* MADV_PAGEOUT */);
return rss_kb(getpid()) < before - 32 * 1024 ? 0 : 1;
}
ctl = argv[1];
size = (size_t)atol(argv[2]) << 20;
block_urg = argc > 3 && !strcmp(argv[3], "block");
int undumpable = argc > 3 && !strcmp(argv[3], "undumpable");
if (undumpable) prctl(PR_SET_DUMPABLE, 0);
shared = mmap(NULL, sizeof(*shared), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (shared == MAP_FAILED) return 2;
char resume[512];
snprintf(resume, sizeof(resume), "%s.resume", ctl);
unlink(resume);
put(".hold", "");
pid_t child = fork();
if (child == 0) {
// the blocks are the child's alone: a page-out skips pages another process still maps
for (int i = 0; i < THREADS; i++) {
blocks[i] = i % 2 ? malloc(size) : mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (!blocks[i] || blocks[i] == MAP_FAILED) _exit(3);
fill(blocks[i], size, (unsigned)i * 77u + 1u);
}
if (mprotect(blocks[2], size, PROT_READ) != 0) _exit(4);
pthread_t t[THREADS];
for (long i = 0; i < THREADS; i++) pthread_create(&t[i], NULL, work, (void *)i);
for (int i = 0; i < THREADS; i++) pthread_join(t[i], NULL);
_exit(0);
}
while (shared->progress < 50) nap(10);
long before = rss_kb(child);
if (undumpable) {
shared->quiet = 1;
for (int waited = 0; __atomic_load_n(&shared->quieted, __ATOMIC_ACQUIRE) < THREADS && waited < 5000; waited += 1) nap(1);
if (__atomic_load_n(&shared->quieted, __ATOMIC_ACQUIRE) < THREADS) {
// a reader still scanning would fault pages back in before the resident set is measured
shared->stop = 1;
kill(child, SIGKILL);
waitpid(child, NULL, 0);
return 5;
}
}
int stale = argc > 3 && !strcmp(argv[3], "stale");
long stale_ack = 0, stale_ran = 0;
if (stale) {
put(".resume", "1"); // resumed already: this request comes too late
put(".hold", "4 0");
kill(child, SIGURG);
for (long waited = 0; waited < 2000 && !stale_ack; waited += 20) {
char path[512];
snprintf(path, sizeof(path), "%s.ack.%d", ctl, child);
stale_ack = access(path, F_OK) == 0; // any acknowledgement, even an empty or cancelled one
nap(20);
}
long at = shared->progress;
nap(500);
stale_ran = shared->progress - at;
}
// a request asked under the current count, which the same handler answers
put(".hold", stale ? "4 1" : "4 0");
kill(child, SIGURG);
if (argc > 3 && (!strcmp(argv[3], "killspill") || !strcmp(argv[3], "killrestore"))) {
// The helper dies while it writes the pages out or reads them back: no owner thread may run after that.
int restore = !strcmp(argv[3], "killrestore");
long low = before, caught = 0;
if (restore) {
if (wait_for(".ack.", child, 20000) > 0) low = rss_kb(child);
put(".resume", "1");
}
for (int waited = 0; !caught && waited < 20000; waited++) {
if ((restore ? get(".restored.", child) : get(".ack.", child)) >= 0) break; // finished before it was caught
long rss = rss_kb(child);
if (restore ? rss > low + 16 * 1024 : rss < low - 16 * 1024) caught = 1;
else nap(1);
}
// The helper is stopped inside the phase and the phase is checked again before it is killed, so it cannot
// finish in between.
// The owner's worker is stopped too, as in killhelper: only the kernel's exit kill can end the owner.
pid_t helper = caught ? find_helper(child) : -1;
int stopped = 0;
if (helper > 0) {
kill(child, SIGSTOP);
for (int waited = 0; !stopped && waited < 1000; waited++) {
stopped = thread_in_state(child, 'T');
if (!stopped) nap(1);
}
kill(helper, SIGSTOP);
int held = 0;
for (int waited = 0; !held && waited < 1000; waited++) {
held = thread_in_state(helper, 'T');
if (!held) nap(1);
}
long rss = rss_kb(child);
int done = (restore ? get(".restored.", child) : get(".ack.", child)) >= 0;
caught = held && !done && (restore ? rss > low + 16 * 1024 : rss < low - 16 * 1024);
}
long at = shared->touched, errors = shared->errors;
if (helper > 0) kill(helper, SIGKILL);
int status = 0, waited = 0, died;
while (!(died = waitpid(child, &status, WNOHANG) == child) && waited < 2000) {
nap(1);
waited += 1;
}
if (!died) {
kill(child, SIGKILL);
waitpid(child, &status, 0);
}
printf("caught=%ld helper=%d stopped=%d died=%d exit=%d moved=%ld errors=%ld\n", caught, (int)helper, stopped, died,
WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status), shared->touched - at,
shared->errors - errors);
return 0;
}
long spilled = wait_for(".ack.", child, 20000);
if (argc > 3 && !strcmp(argv[3], "killhelper")) {
// the helper dies holding pages it dropped: the owner must die with it rather than run without them
// The owner's worker, the one thread the helper does not trace, is group-stopped first: it cannot reap the
// helper and kill the owner itself, so only the kernel's PTRACE_O_EXITKILL can end the owner.
pid_t helper = find_helper(child);
kill(child, SIGSTOP);
int stopped = 0;
for (int waited = 0; !stopped && waited < 1000; waited += 10) {
stopped = thread_in_state(child, 'T');
if (!stopped) nap(10);
}
if (helper > 0) kill(helper, SIGKILL);
int status = 0, waited = 0, died;
while (!(died = waitpid(child, &status, WNOHANG) == child) && waited < 2000) {
nap(10);
waited += 10;
}
if (!died) {
kill(child, SIGKILL);
waitpid(child, &status, 0);
}
printf("spilled=%ld helper=%d stopped=%d waited=%d died=%d exit=%d\n", spilled, (int)helper, stopped, waited,
died, WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status));
return 0;
}
long after = rss_kb(child);
shared->quiet = 0;
long frozen_at = shared->progress;
nap(500);
long frozen_now = shared->progress;
put(".resume", stale ? "2" : "1");
long restored = spilled > 0 ? wait_for(".restored.", child, 20000) : 0;
for (int waited = 0; shared->progress == frozen_now && waited < 10000; waited += 10) nap(10);
long resumed = shared->progress;
long back = rss_kb(child);
shared->stop = 1;
int status = 0;
waitpid(child, &status, 0);
printf("before=%ld after=%ld back=%ld spilled=%ld restored=%ld frozen=%ld resumed=%ld errors=%ld exit=%d "
"stale=%ld stale_ran=%ld\n",
before, after, back, spilled, restored, frozen_now - frozen_at, resumed - frozen_now, shared->errors,
WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status), stale_ack, stale_ran);
return 0;
}
"""
def _fields(text):
return {k: int(v) for k, v in (part.split("=") for part in text.split())}
@unittest.skipUnless(platform.machine() == "aarch64" and shutil.which("cc"), "the spill runs only on arm64")
class ZramSpillPreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dir = Path(tempfile.mkdtemp())
cls.ctl = cls.dir / "ctl"
lib = cls.dir / "libzram.so"
prog = cls.dir / "spill"
(cls.dir / "spill.c").write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-shared", "-fPIC", f'-DZR_CTL="{cls.ctl}"', "-o", str(lib),
str(PRELOAD / "zram.c")], check=True)
subprocess.run(["cc", "-O2", "-pthread", "-o", str(prog), str(cls.dir / "spill.c")], check=True)
cls.lib, cls.prog = lib, prog
cls.can_trace = subprocess.run([str(prog), "probe"]).returncode == 0
cls.can_page_out = subprocess.run([str(prog), "pageout"]).returncode == 0
def need_tracing(self):
if not self.can_trace:
self.skipTest("this host does not let a child seize its parent (Yama ptrace_scope)")
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.dir, ignore_errors=True)
def run_spill(self, *extra):
self.ctl.write_text("0")
env = dict(os.environ, LD_PRELOAD=str(self.lib))
env.pop("DDNATV_ROOT", None)
out = subprocess.run([str(self.prog), str(self.ctl), "64", *extra], env=env, check=True,
capture_output=True, text=True, timeout=90).stdout
return _fields(out)
def test_spills_to_disk_holds_every_thread_and_restores_intact(self):
self.need_tracing()
r = self.run_spill()
self.assertEqual(r["exit"], 0)
self.assertGreater(r["spilled"], 200 * 1024)
self.assertLess(r["after"], r["before"] - 200 * 1024)
self.assertEqual(r["frozen"], 0)
self.assertGreaterEqual(r["restored"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_a_thread_that_blocks_every_signal_is_held_too(self):
self.need_tracing()
r = self.run_spill("block")
self.assertEqual(r["exit"], 0)
self.assertGreater(r["spilled"], 200 * 1024)
self.assertEqual(r["frozen"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_a_request_that_arrives_after_the_resume_is_dropped(self):
r = self.run_spill("stale")
self.assertEqual(r["exit"], 0)
self.assertEqual(r["stale"], 0) # no acknowledgement of any kind: nothing was held or written
self.assertGreater(r["stale_ran"], 0) # it kept running throughout
# the next request, asked under the current count, is answered by the same handler
self.assertGreaterEqual(r["spilled"], 0)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
def test_an_owner_dies_with_a_helper_that_dies_holding_its_pages(self):
self.need_tracing()
r = self.run_spill("killhelper")
self.assertGreater(r["spilled"], 0)
self.assertGreater(r["helper"], 0)
# the worker was stopped before the helper died, so the kernel, not the worker, ended the owner
self.assertEqual(r["stopped"], 1)
self.assertEqual(r["died"], 1)
self.assertEqual(r["exit"], 128 + 9)
def test_no_owner_thread_runs_after_its_helper_dies_mid_spill(self):
self.need_tracing()
r = self.run_spill("killspill")
self.assertEqual(r["caught"], 1) # the helper was killed while it was still writing
self.assertEqual(r["stopped"], 1)
self.assertEqual(r["died"], 1)
self.assertEqual(r["exit"], 128 + 9)
self.assertEqual(r["moved"], 0)
self.assertEqual(r["errors"], 0)
def test_no_owner_thread_runs_after_its_helper_dies_mid_read_back(self):
self.need_tracing()
r = self.run_spill("killrestore")
self.assertEqual(r["caught"], 1) # the helper was killed while it was still reading back
self.assertEqual(r["stopped"], 1)
self.assertEqual(r["died"], 1)
self.assertEqual(r["exit"], 128 + 9)
self.assertEqual(r["moved"], 0)
self.assertEqual(r["errors"], 0)
def test_a_process_that_cannot_be_traced_falls_back_to_zram(self):
r = self.run_spill("undumpable")
self.assertEqual(r["exit"], 0)
self.assertEqual(r["spilled"], 0)
# the fallback pages out to zram before it answers: where the host can page out, the resident set
# has shrunk by then
if self.can_page_out:
self.assertLess(r["after"], r["before"] - 64 * 1024)
self.assertGreater(r["resumed"], 0)
self.assertEqual(r["errors"], 0)
if __name__ == "__main__":
unittest.main()