feat: page the session out to zram before suspending it, and zram is always on where supported

This commit is contained in:
xXJsonDeruloXx committed 2026-10-22 09:02:37 -04:00
1 parent aaa2e40def
commit 240b7fcce6
43 files changed
+122 -168

No files matched your search

@@ -392,8 +392,6 @@ class MainActivity : ComponentActivity() {
private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO)
private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL)
private var steamDownloadsInBackground by mutableStateOf(false)
private var zramCompression by mutableStateOf(false)
private var zramSupported by mutableStateOf<Boolean?>(null)
private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO)
private var backActionsInverted by mutableStateOf(false)
private var gameStorage by mutableStateOf("")
@@ -1616,8 +1614,6 @@ class MainActivity : ComponentActivity() {
touchMode = touchMode,
suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground,
zramCompression = if (mode == SessionService.MODE_STEAM) zramCompression else null,
zramSupported = zramSupported,
pipSupported = com.droiddeck.launcher.session.SessionPipController.supported(this),
pipAutoEnter = pipAutoEnter,
unfoldedControls = if (mode == SessionService.MODE_STEAM &&
@@ -1685,7 +1681,6 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setSteamDownloadsInBackground(this, enabled)
steamDownloadsInBackground = enabled
},
onZramCompression = { on -> SessionPrefs.setZramCompression(this, on); zramCompression = on },
onPipAutoEnter = { on -> SessionPrefs.setPipAutoEnter(this, on); pipAutoEnter = on },
onUnfoldedControls = { on -> SessionPrefs.setUnfoldedControls(this, on); unfoldedControls = on },
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
@@ -1912,9 +1907,6 @@ class MainActivity : ComponentActivity() {
storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this)
settingsMode = mode
Thread({
val zram = com.droiddeck.launcher.core.ZramSupport.supported()
val zramOn = SessionPrefs.zramCompression(this)
ui.post { zramSupported = zram; zramCompression = zramOn }
drivers.refreshDrivers()
val storage = GameStorage.options(this)
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
@@ -1,26 +1,10 @@
package com.droiddeck.launcher.core
import android.app.ActivityManager
import android.content.Context
import android.os.Build
import java.io.File
object ZramSupport {
private const val GIB = 1L shl 30
fun supported(): Boolean = kernelAtLeast(System.getProperty("os.version").orEmpty(), 5, 4) && swapTotalKb() > 0
fun recommended(context: Context): Boolean {
if (!supported()) return false
val memory = ActivityManager.MemoryInfo()
context.getSystemService(ActivityManager::class.java).getMemoryInfo(memory)
val advertised = if (Build.VERSION.SDK_INT >= 34) memory.advertisedMem else 0L
return belowTwelveGb(advertised, memory.totalMem)
}
fun belowTwelveGb(advertisedBytes: Long, totalBytes: Long): Boolean =
if (advertisedBytes > 0) advertisedBytes < 11 * GIB else totalBytes < 10 * GIB
fun kernelAtLeast(release: String, major: Int, minor: Int): Boolean {
val parts = Regex("^(\\d+)\\.(\\d+)").find(release)?.groupValues ?: return false
val ma = parts[1].toInt()
@@ -7,7 +7,6 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.CpuAllocationDefaults
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.core.ZramSupport
import com.droiddeck.launcher.gpu.Cardboard
import com.droiddeck.launcher.gpu.ScreenEffects
import org.json.JSONObject
@@ -1034,15 +1033,6 @@ object SessionPrefs {
}.apply()
}
fun zramCompression(context: Context): Boolean {
val prefs = prefs(context)
return if (prefs.contains("zramCompression")) prefs.getBoolean("zramCompression", false) else ZramSupport.recommended(context)
}
fun setZramCompression(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramCompression", on).apply()
}
fun gameStorage(context: Context): String = prefs(context).getString("gameStorage", "") ?: ""
@@ -581,6 +581,17 @@ class SessionService : Service() {
resumeAudio = {
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
},
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"),
pagedOut = { processes, residentKb, swapKb, swapBeforeKb, millis ->
Log.i(TAG, "paged out $processes processes in $millis ms: resident ${residentKb / 1024} MB, " +
"zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
mainHandler.post {
SessionEvents.record("session.paged_out", mapOf(
"processes" to processes, "residentMb" to residentKb / 1024,
"swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024, "ms" to millis,
))
}
},
)
mainHandler.post { updateSuspendPolicy() }
updateDownloadMonitoring()
@@ -661,8 +672,7 @@ class SessionService : Service() {
guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0"))
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0"))
if (SessionState.mode == MODE_STEAM && SessionPrefs.zramCompression(this) &&
com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
if (com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this)
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
@@ -1386,7 +1396,9 @@ class SessionService : Service() {
"nativeSleep" to (nativeSleepToken != null),
))
if (shouldSuspend) {
controller.freeze { success ->
controller.freeze(
pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn,
) { success ->
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
suspendOperationPending = false
@@ -18,6 +18,8 @@ internal class SessionSuspendController(
private val sleep: (Long) -> Unit = Thread::sleep,
private val nowMillis: () -> Long = { System.nanoTime() / 1_000_000 },
private val executor: ExecutorService = Executors.newSingleThreadExecutor(),
private val zramControl: File? = null,
private val pagedOut: (processes: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit = { _, _, _, _, _ -> },
) {
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
@@ -40,7 +42,7 @@ internal class SessionSuspendController(
@Volatile private var closing = false
private var frozen = emptyList<ProcessRecord>()
fun freeze(completion: (Boolean) -> Unit) {
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
submit({
val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started }
var complete = false
@@ -59,6 +61,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)
val deadline = nowMillis() + FREEZE_TIMEOUT_MS
var previous: Map<TaskIdentity, Long>? = null
for (pass in 0 until FREEZE_MAX_PASSES) {
@@ -233,6 +236,57 @@ internal class SessionSuspendController(
return tasks.takeIf { stopped && it.isNotEmpty() }
}
// A stopped process cannot run libblsession's SIGURG handler, so the page-out has to finish
// before the stop. Android's low-memory killer otherwise finds the frozen game resident in RAM
// with most of zram still free.
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
val control = zramControl?.takeIf { it.isFile } ?: return
try {
addSnapshot(records, root, helpers)
control.writeText("1")
} catch (_: IOException) {
return
}
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libblsession.so") } }
} catch (_: IOException) {
false
}
}
if (targets.isEmpty()) return
val start = nowMillis()
val before = memoryKb(targets)
for (record in targets) send(record, SIGURG)
var previous = before.second
var steady = 0
while (steady < PAGE_OUT_STEADY_POLLS && nowMillis() - start < PAGE_OUT_TIMEOUT_MS) {
sleep(PAGE_OUT_POLL_MS)
val swap = memoryKb(targets).second
steady = if (swap == previous) steady + 1 else 0
previous = swap
}
val after = memoryKb(targets)
pagedOut(targets.size, after.first, after.second, before.second, nowMillis() - start)
}
private fun memoryKb(records: List<ProcessRecord>): Pair<Long, Long> {
var resident = 0L
var swap = 0L
for (record in records) {
try {
File(procRoot, "${record.pid}/status").useLines { lines ->
for (line in lines) {
val kb = line.substringAfter(':').trim().substringBefore(' ').toLongOrNull() ?: continue
if (line.startsWith("VmRSS:")) resident += kb else if (line.startsWith("VmSwap:")) swap += kb
}
}
} catch (_: IOException) {
}
}
return resident to swap
}
// PRoot traces every guest. A stop sent while it runs becomes a group stop that it restarts
// thread by thread; once it is stopped, each thread that takes a SIGSTOP stays parked in its
// signal-delivery stop. So the roots stop first and every guest thread gets its own SIGSTOP.
@@ -310,6 +364,10 @@ internal class SessionSuspendController(
private companion object {
const val SIGSTOP = 19
const val SIGCONT = 18
const val SIGURG = 23
const val PAGE_OUT_POLL_MS = 250L
const val PAGE_OUT_STEADY_POLLS = 3
const val PAGE_OUT_TIMEOUT_MS = 12_000L
const val RESTORE_CHECKS = 80
const val FREEZE_TIMEOUT_MS = 8_000L
const val FREEZE_MAX_PASSES = 256
@@ -65,8 +65,6 @@ class ModeSettings(
val touchMode: String,
val suspendPolicy: String,
val steamDownloadsInBackground: Boolean = false,
val zramCompression: Boolean? = null,
val zramSupported: Boolean? = null,
val pipSupported: Boolean = false,
val pipAutoEnter: Boolean = false,
val oscMode: String?,
@@ -120,7 +118,6 @@ class ModeSettingsActions(
val onTouch: (String) -> Unit,
val onSuspendPolicy: (String) -> Unit,
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
val onZramCompression: (Boolean) -> Unit = {},
val onPipAutoEnter: (Boolean) -> Unit = {},
val onOsc: (String) -> Unit,
val onBackActionsInverted: (Boolean) -> Unit = {},
@@ -326,12 +323,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
stringResource(R.string.mode_background_downloads_hint),
s.steamDownloadsInBackground, onChange = a.onSteamDownloadsInBackground,
)
if (s.zramCompression != null) ToggleRow(
host, "zram", stringResource(R.string.mode_zram),
stringResource(if (s.zramSupported == false) R.string.mode_zram_unsupported else R.string.mode_zram_hint),
s.zramCompression && s.zramSupported != false, enabled = s.zramSupported == true,
onChange = a.onZramCompression,
)
if (s.syncBackend != null) ChoiceRow(
host, "sync", stringResource(R.string.sync_backend_title), stringResource(R.string.sync_backend_hint),
listOf(