Compare commits

..
Author SHA1 Message Date
The412Banner fe55ec24c1 fix(flatpak): give apps with host access the home folder and its ROMs mount 2026-12-05 12:16:26 +00:00
K11MCH1 8a27ea841c Add RedMagic Air Triggers to the session's controller settings (#3737)
* Add RedMagic Air Triggers to the session's controller settings

Controller > Device settings gets a "Redmagic Air Triggers" panel on
RedMagic phones whose Game Space exposes its trigger provider. The
toggle switches the shoulder triggers to plain F7/F8 keys through Game
Space's exported TgkDataProvider (no permission, no trigger panel or
markers), and each trigger presses a button of the active touch layout:
LT and RT by default, or any button picked in the dropdowns, saved per
layout.

The triggers go back to their earlier state when the toggle is off,
the session pauses or ends, or the app is killed mid-session (the next
session start closes what this app opened). A distribute state another
app turned on is left alone.

* Show Air Trigger presses on screen and light the triggers

A trigger now presses its button through the on-screen controls when
that button is shown, so it shows as pressed and shares a toggle
button's state with touches. A hidden button still gets the trigger's
own input source.

Game Space lights the triggers only from its own trigger view, through
ColorfulLightManager, which apps cannot call. DroidDeck sends the same
requestColorfulLight to the ColorfulLightService binder: the shoulder
scene while the triggers are on, and the press/release lights the
user's RedMagic lighting settings ask for.

* Set the trigger light effect so the Air Trigger LEDs turn on

RedMagic's light service writes no trigger light until a shoulder
effect has been set, and only Game Space's own trigger view sets one.
After entering the shoulder light scene, send the effect the user picked
in RedMagic's lighting settings (selection in lighting_shoulder_config_json).

* Cancel forced Air Trigger releases and close the triggers while paused

A trigger press that DroidDeck ends itself (focus loss, the triggers
closing, another button chosen mid-press) now cancels the button like a
cancelled touch, so a command button such as the keyboard does not run.

A toggle latched while its button was hidden is handed to the visible
button on the next trigger press instead of staying held underneath it.

The triggers also close while the session is paused and reopen when it
resumes.

* Keep an Air Trigger hold when a touch on the same button is cancelled

A cancelled touch stream cleared every press of the button, including
the Air Trigger still holding it, so the button let go while the trigger
stayed down. Touch cancels now end only the finger presses. Releasing
all input still clears the button completely.

* Release Air Trigger-only button holds when all input is released

Releasing all input only cancelled buttons a finger owned. A button held
only by an Air Trigger kept its pressed state after its output was
released, so it stayed lit and a finger on it did nothing until the
trigger was lifted. A full release now cancels every button.
2026-12-05 19:38:03 +09:00
51 changed files with 903 additions and 2038 deletions

No files matched your search

@@ -100,6 +100,11 @@ import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold
import com.droiddeck.launcher.input.GestureTouchStreamGate
import com.droiddeck.launcher.input.PenRouter
import com.droiddeck.launcher.input.AirTrigger
import com.droiddeck.launcher.input.AirTriggerButtons
import com.droiddeck.launcher.input.AirTriggerInput
import com.droiddeck.launcher.input.AirTriggerPrefs
import com.droiddeck.launcher.input.RedMagicAirTriggers
import com.droiddeck.launcher.input.PenStream
import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.PointerSpace
@@ -241,6 +246,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private lateinit var sessionRoot: FrameLayout
private var inputRouter: InputRouter? = null
private var physicalInputBindings: com.droiddeck.launcher.input.PhysicalInputBindings? = null
private var airTriggerInput: AirTriggerInput? = null
private var airTriggersOpen = false
private var airTriggerMenu by mutableStateOf<com.droiddeck.launcher.ui.AirTriggerMenu?>(null)
private var inputSettingsOpen by mutableStateOf(false)
@Volatile private var inputUsesLocalActions = false
private var inputUsesPointer = false
@@ -974,6 +982,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
bridge.setBuiltinPad(SessionState.mode != SessionService.MODE_STEAM || SessionPrefs.builtinPad(this))
padBridge = bridge
inputRouter = InputRouter(inputOutput).also { bridge.setInputRouter(it); DeckControls.setRouter(it); physicalInputBindings = com.droiddeck.launcher.input.PhysicalInputBindings(it) }
if (RedMagicAirTriggers.supported(this)) {
airTriggerInput = AirTriggerInput(bridge, ::holdOnScreen, RedMagicAirTriggers::light)
RedMagicAirTriggers.restore(this)
}
refreshInputProfile()
bridge.setOnChordInput(backQamInput::onChordInput)
SessionState.padBridge = bridge
@@ -1383,6 +1395,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
LaunchedEffect(drawerOpen, menuOwnsController, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, inputSettingsOpen, pipUi, SessionState.suspended, resumed, appTextFocus) {
updateOnScreenControls()
refreshAirTriggers()
padBridge?.setInputEnabled(resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen && !gestureSettingsOpen && !inputSettingsOpen && !pipUi && !appTextFocus && !SessionState.suspended)
if (!drawerOpen && backTapOpenedDrawer) {
backTaps.cancel()
@@ -1936,6 +1949,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
wowChat = wowChat.remembered,
onWowChat = wowChat::choose,
controller = controllerSettings,
airTriggers = airTriggerMenu,
onAirTriggers = { on -> AirTriggerPrefs.setEnabled(this@SessionActivity, on); refreshAirTriggers() },
onAirTriggerButton = { trigger, id ->
AirTriggerPrefs.setButton(this@SessionActivity, primaryInputLayout?.id.orEmpty(), trigger, id)
refreshAirTriggers()
},
onControllerSize = { percent -> updateControllerPrefs { ControllerPrefs.setSize(this@SessionActivity, percent) } },
onControllerOpacity = { percent ->
ControllerPrefs.setOnScreenOpacity(this@SessionActivity, percent)
@@ -3680,6 +3699,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun onSessionEnded(status: Int) {
ended = true
runOnUiThread { refreshAirTriggers() }
++steamVrRequestGeneration
if (isInPictureInPictureMode) {
runOnUiThread { finish() }
@@ -3737,6 +3757,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun releasePads(keepBackTap: Boolean = false) {
inputMotion.stop()
physicalInputBindings?.release()
airTriggerInput?.release()
com.droiddeck.launcher.input.HomeButtonShortcuts.cancel(this)
backQamInput.cancel(keepTap = keepBackTap)
padBridge?.releaseAll()
@@ -3869,6 +3890,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
return dispatchSessionKeyEvent(normalized, orderedImeKey)
}
private fun physicalInputAccepted() = resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible
private fun dispatchSessionKeyEvent(event: KeyEvent, orderedImeKey: Boolean): Boolean {
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) {
@@ -3888,10 +3912,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
}
if (penStream.holdsKey(event) || (penSettings.mode != SessionPrefs.PEN_TOUCH && PenStream.isPenKey(event))) return penStream.onKey(event)
if (airTriggerInput?.onKey(event) { physicalInputAccepted() && !pipUi && !appTextFocus } == true) return true
if (appTextFocus) return super.dispatchKeyEvent(event)
if (!pipUi) {
if (physicalInputBindings?.onKey(event, resumed && !menuOwnsController && !pcKeyboardOpen && !achievementsOpen &&
!inputSettingsOpen && !gestureSettingsOpen && !SessionState.suspended && !loading.visible) == true) return true
if (physicalInputBindings?.onKey(event, physicalInputAccepted()) == true) return true
if (physicalShortcuts.onKey(
event,
enabled = resumed && SessionState.running && !SessionState.suspended &&
@@ -5116,6 +5140,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|| inputProfile.keys.any { it.action is InputAction.MouseButton }
physicalInputBindings?.configure(inputProfile.keys)
padBridge?.setInputProfile(inputProfile)
refreshAirTriggers()
DeckControls.refresh()
onScreenControls?.updateLayout(primaryInputLayout)
bottomInputControls?.updateLayout(primaryInputLayout)
@@ -5126,6 +5151,21 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
secondScreenPresentation?.refreshControls()
}
private fun refreshAirTriggers() {
val input = airTriggerInput ?: return
val layout = primaryInputLayout
val enabled = AirTriggerPrefs.enabled(this)
val chosen = AirTrigger.entries.associateWith { AirTriggerButtons.resolve(layout, it, AirTriggerPrefs.button(this, layout?.id.orEmpty(), it)) }
val active = enabled && resumed && !ended && !SessionState.suspended
input.configure(if (active) chosen else emptyMap())
if (active != airTriggersOpen) {
airTriggersOpen = active
if (active) RedMagicAirTriggers.open(this) else RedMagicAirTriggers.restore(this)
}
airTriggerMenu = com.droiddeck.launcher.ui.AirTriggerMenu(enabled, chosen.mapValues { it.value.id },
AirTriggerButtons.options(layout).map { it.id to it.name })
}
private fun tapQam() {
if (SessionState.mode == SessionService.MODE_STEAM) padBridge?.triggerQam()
}
@@ -5582,10 +5622,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var sessionTouchDown = false
private var screenTapsClick = true
private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull(
private fun inputSurfaces() = listOfNotNull(
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
secondScreenPresentation?.controlsView, swappedInputSurface,
).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
)
private fun onScreenLeftMouseButtonShown(): Boolean =
inputSurfaces().any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
private fun holdOnScreen(elementId: String, trigger: AirTrigger, held: Boolean, cancelled: Boolean): Boolean {
val surfaces = inputSurfaces().filter { it.inputRole == InputRole.PRIMARY }
if (held) return surfaces.any { it.isShown && it.hold(elementId, trigger.ordinal, true) }
surfaces.forEach { it.hold(elementId, trigger.ordinal, false, cancelled) }
return true
}
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
@@ -6703,6 +6753,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (::padMouse.isInitialized) padMouse.reset()
resumed = false
refreshAirTriggers()
boostGpuClock(false)
updateKeyboardRoute()
updatePointerCapture()
@@ -7296,7 +7347,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!hasFocus) {
cancelTouchGestures()
releaseHeldGuestInput()
airTriggerInput?.release()
}
// Game Space clears the distribute state when the launcher or Game Space itself comes to the front.
if (hasFocus && airTriggersOpen) RedMagicAirTriggers.open(this)
if (hasFocus && !pipUi) {
retryFieldKeyboard(true)
goFullscreen()
@@ -7384,6 +7438,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
inputMotion.stop()
padBridge?.setInputEnabled(false)
physicalInputBindings?.close()
airTriggerInput?.close()
airTriggerInput = null
if (airTriggersOpen) RedMagicAirTriggers.restore(this)
padBridge?.stop()
DeckControls.clearRouter(inputRouter)
inputRouter = null
@@ -0,0 +1,203 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.content.SharedPreferences
import android.net.Uri
import android.os.IBinder
import android.os.Parcel
import android.provider.Settings
import android.util.Log
import android.view.InputDevice
import android.view.KeyEvent
import java.util.EnumMap
import java.util.EnumSet
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
import org.json.JSONObject
enum class AirTrigger(val keyCode: Int, val control: InputControl, val pressLight: Int, val releaseLight: Int) {
LEFT(KeyEvent.KEYCODE_F7, InputControl.LT, 106, 107), RIGHT(KeyEvent.KEYCODE_F8, InputControl.RT, 108, 109);
companion object {
// InputReader merges both trigger nodes into one device named after the left one.
private const val DEVICE_PREFIX = "nubia_tgk"
fun isTriggerDevice(name: String?) = name?.startsWith(DEVICE_PREFIX) == true
fun of(keyCode: Int, deviceName: String?): AirTrigger? =
if (isTriggerDevice(deviceName)) entries.firstOrNull { it.keyCode == keyCode } else null
}
}
object AirTriggerButtons {
fun options(layout: SavedInputLayout?): List<InputSurfaceElement> {
val placed = layout?.let { (it.elements + it.rotated).distinctBy { element -> element.id } }.orEmpty()
.filter { it.kind == InputElementKind.BUTTON || it.kind == InputElementKind.TRIGGER }
return placed + AirTrigger.entries.filter { trigger -> placed.none { it.control == trigger.control } }
.map { InputSurfaceElement(it.control, 0f, 0f, 0f, 0f) }
}
fun resolve(layout: SavedInputLayout?, trigger: AirTrigger, chosen: String?): InputSurfaceElement {
val options = options(layout)
return chosen?.let { id -> options.firstOrNull { it.id == id } } ?: options.first { it.control == trigger.control }
}
}
object AirTriggerPrefs {
private const val FILE = "redmagic-air-triggers"
private const val ENABLED = "enabled"
internal const val OWNED = "distribute-owned"
fun prefs(context: Context): SharedPreferences = context.getSharedPreferences(FILE, Context.MODE_PRIVATE)
fun enabled(context: Context) = prefs(context).getBoolean(ENABLED, false)
fun setEnabled(context: Context, on: Boolean) = prefs(context).edit().putBoolean(ENABLED, on).apply()
fun button(context: Context, layoutId: String, trigger: AirTrigger): String? = prefs(context).getString(key(layoutId, trigger), null)
fun setButton(context: Context, layoutId: String, trigger: AirTrigger, elementId: String) =
prefs(context).edit().putString(key(layoutId, trigger), elementId).apply()
private fun key(layoutId: String, trigger: AirTrigger) = "${trigger.name.lowercase()}.$layoutId"
}
/** Game Space's exported provider switches the triggers to plain F7/F8 keys without its panel, and needs no permission. */
object RedMagicAirTriggers {
private const val TAG = "AirTriggers"
private const val AUTHORITY = "cn.nubia.tgk.data.TgkDataProvider"
private val URI = Uri.parse("content://$AUTHORITY")
private const val OPEN = "openTouchGameKeyDistribute"
private const val CLOSE = "closeTouchGameKeyDistribute"
private const val LIGHT_SERVICE = "ColorfulLightService"
private const val LIGHT_INTERFACE = "com.zte.hardware.IColorfulLightManager"
// IColorfulLightManager transaction codes; its ColorfulLightManager wrapper is a blocked hidden API.
private const val REQUEST_LIGHT = IBinder.FIRST_CALL_TRANSACTION
private const val SET_SHOULDER_EFFECT = IBinder.FIRST_CALL_TRANSACTION + 2
private const val SHOULDER_LIGHT_ON = 110
private const val SHOULDER_LIGHT_OFF = 111
private const val SHOULDER_SETTINGS = "lighting_shoulder_config_json"
private val worker = ThreadPoolExecutor(0, 1, 10, TimeUnit.SECONDS, LinkedBlockingQueue()) { Thread(it, "air-triggers") }
private val lights: IBinder? by lazy {
runCatching { Class.forName("android.os.ServiceManager").getMethod("getService", String::class.java).invoke(null, LIGHT_SERVICE) as IBinder? }
.getOrNull()?.takeIf { runCatching { it.interfaceDescriptor }.getOrNull() == LIGHT_INTERFACE }
}
@Suppress("DEPRECATION")
fun supported(context: Context) = context.packageManager.resolveContentProvider(AUTHORITY, 0) != null &&
InputDevice.getDeviceIds().any { AirTrigger.isTriggerDevice(InputDevice.getDevice(it)?.name) }
fun open(context: Context) {
val app = context.applicationContext
worker.execute {
val prefs = AirTriggerPrefs.prefs(app)
if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false) && Settings.Global.getInt(app.contentResolver, OPEN, 0) != 1)
prefs.edit().putBoolean(AirTriggerPrefs.OWNED, true).commit()
call(app, OPEN)
if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false)) return@execute
requestLight(SHOULDER_LIGHT_ON)
// The light service drops every trigger light until an effect is set, which Game Space only does from its own view.
shoulderEffect(Settings.Global.getString(app.contentResolver, SHOULDER_SETTINGS))?.let { effect ->
transact(SET_SHOULDER_EFFECT) { writeString(effect) }
}
}
}
/** The trigger light effect the user picked in RedMagic's lighting settings, such as "02101000" for steady. */
internal fun shoulderEffect(settings: String?): String? = settings
?.let { runCatching { JSONObject(it).optString("selection") }.getOrNull() }
?.takeIf { it.length == 8 }
/** Closes only what this app opened, so a distribute another app turned on stays on. */
fun restore(context: Context) {
val app = context.applicationContext
worker.execute {
val prefs = AirTriggerPrefs.prefs(app)
if (!prefs.getBoolean(AirTriggerPrefs.OWNED, false)) return@execute
requestLight(SHOULDER_LIGHT_OFF)
if (call(app, CLOSE)) prefs.edit().remove(AirTriggerPrefs.OWNED).commit()
}
}
fun light(code: Int) = worker.execute { requestLight(code) }
private fun requestLight(action: Int) = transact(REQUEST_LIGHT) { writeInt(action) }
private fun transact(code: Int, write: Parcel.() -> Unit) {
val binder = lights ?: return
val data = Parcel.obtain()
val reply = Parcel.obtain()
try {
data.writeInterfaceToken(LIGHT_INTERFACE)
data.write()
binder.transact(code, data, reply, 0)
reply.readException()
} catch (e: Exception) {
Log.w(TAG, "light call $code failed", e)
} finally {
data.recycle()
reply.recycle()
}
}
private fun call(context: Context, method: String) = runCatching { context.contentResolver.call(URI, method, null, null) != null }
.onFailure { Log.w(TAG, "$method failed", it) }.getOrDefault(false)
}
/** Presses the chosen button on screen when it is shown, so it animates and keeps one toggle state; otherwise uses a source of its own. */
class AirTriggerInput(
private val pad: PadBridge,
private val onScreen: (elementId: String, trigger: AirTrigger, held: Boolean, cancelled: Boolean) -> Boolean = { _, _, _, _ -> false },
private val light: (Int) -> Unit = {},
) {
private val sources = EnumMap<AirTrigger, InputSurfaceSource>(AirTrigger::class.java)
private val held = EnumSet.noneOf(AirTrigger::class.java)
private val heldOnScreen = EnumMap<AirTrigger, String>(AirTrigger::class.java)
fun configure(elements: Map<AirTrigger, InputSurfaceElement>) {
for (trigger in AirTrigger.entries) {
val element = elements[trigger]
if (sources[trigger]?.element == element) continue
heldOnScreen.remove(trigger)?.let { onScreen(it, trigger, false, true) }
sources.remove(trigger)?.close()
if (element != null) sources[trigger] = InputSurfaceSource(pad, InputRole.PRIMARY, element)
}
}
fun onKey(event: KeyEvent, enabled: () -> Boolean): Boolean {
if (AirTrigger.entries.none { it.keyCode == event.keyCode }) return false
val trigger = AirTrigger.of(event.keyCode, event.device?.name) ?: return false
return onKey(trigger, event.action, event.repeatCount, event.action == KeyEvent.ACTION_DOWN && enabled())
}
fun onKey(trigger: AirTrigger, action: Int, repeatCount: Int, enabled: Boolean): Boolean {
val source = sources[trigger]
when (action) {
KeyEvent.ACTION_DOWN -> if (source != null && enabled && repeatCount == 0 && held.add(trigger)) press(trigger, source)
KeyEvent.ACTION_UP -> if (held.remove(trigger)) { unpress(trigger, cancelled = false); return true }
}
return source != null
}
private fun press(trigger: AirTrigger, source: InputSurfaceSource) {
if (onScreen(source.element.id, trigger, true, false)) {
heldOnScreen[trigger] = source.element.id
// The router counts held keys, so a toggle latched while its button was hidden is released before the button takes over.
if (source.latched) source.release()
} else source.update(1f)
light(trigger.pressLight)
}
private fun unpress(trigger: AirTrigger, cancelled: Boolean) {
heldOnScreen.remove(trigger)?.let { onScreen(it, trigger, false, cancelled) }
?: sources[trigger]?.let { if (cancelled) it.cancel() else it.update(0f) }
light(trigger.releaseLight)
}
fun release() {
held.toList().forEach { held.remove(it); unpress(it, cancelled = true) }
sources.values.forEach { it.release() }
}
fun close() {
release()
sources.values.forEach { it.close() }
sources.clear()
}
}
@@ -972,9 +972,6 @@ 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,8 +111,6 @@ 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
@@ -278,7 +276,7 @@ class SessionService : Service() {
}
ACTION_XR_ACTIVITY_VISIBLE -> {
xrActivityVisible = true
resumeSession(panelVisible = false, restartRecovery = false)
resumeSession(panelVisible = false)
return START_NOT_STICKY
}
ACTION_XR_ACTIVITY_HIDDEN -> {
@@ -382,8 +380,6 @@ class SessionService : Service() {
suspendOperationPending = false
freezePending = false
suspendAttemptFailed = false
resumeRecovery.reset()
mainHandler.removeCallbacks(retryResume)
suspendController = null
SessionState.micAvailable = false
SessionState.micEnabled = false
@@ -981,7 +977,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 ->
@@ -994,27 +990,7 @@ 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)
))
}
},
)
@@ -1785,7 +1761,7 @@ class SessionService : Service() {
return
}
if (SessionState.suspended) {
resumeSession(restartRecovery = false)
resumeSession()
mainHandler.postDelayed(flushSteamGame, GAME_LAUNCH_RETRY_MS)
return
}
@@ -1954,10 +1930,8 @@ class SessionService : Service() {
private fun steamGameRunning(gameId: String): Boolean =
SteamGameProcess.running(gameId)
private fun resumeSession(panelVisible: Boolean = true, restartRecovery: Boolean = true) {
if (SessionState.suspended && (restartRecovery || resumeRecovery.due(SystemClock.elapsedRealtime()))) {
SessionState.resumeRequested = true
}
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
if (panelVisible) activityVisible = true
screenOn = readScreenOn()
manualPauseRequested = false
@@ -1968,7 +1942,6 @@ class SessionService : Service() {
completeNativeSleep()
completeSteamSleep()
suspendAttemptFailed = false
if (restartRecovery) resumeRecovery.reset()
updateSuspendPolicy()
}
@@ -2187,12 +2160,7 @@ class SessionService : Service() {
controller.cancelFreeze()
}
if (shouldSuspend && SessionState.suspended && !suspendOperationPending) SessionState.resumeRequested = false
// A session still held after a failed suspend or resume is released by paced resumes, whatever 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
if (suspendOperationPending || suspendAttemptFailed || shouldSuspend == SessionState.suspended) return
val gen = sessionGen
suspendOperationPending = true
SessionEvents.record(if (shouldSuspend) "session.suspend_requested" else "session.resume_requested", mapOf(
@@ -2207,9 +2175,9 @@ class SessionService : Service() {
freezeCancelled = false
val freezeSteamToken = steamSleepToken
val freezeNativeToken = nativeSleepToken
val pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn
controller.freeze(pageOut = pageOut, spill = pageOut && SessionPrefs.diskSpill(this)) { success ->
val rollbackPending = !success && controller.rollbackPending
controller.freeze(
pageOut = steamSleepToken != null || nativeSleepToken != null || !activityVisible || !screenOn,
) { success ->
mainHandler.post {
if (gen != sessionGen || !SessionState.running) return@post
SessionState.suspending = false
@@ -2218,7 +2186,6 @@ class SessionService : Service() {
if (success) {
SessionState.suspended = true
SessionState.resumeFailed = false
resumeRecovery.reset()
SessionEvents.transition(SessionPhase.SUSPENDED, "session.suspended")
releaseLocks()
refreshNotification()
@@ -2233,12 +2200,6 @@ 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()
}
@@ -2247,8 +2208,6 @@ 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
@@ -2257,28 +2216,13 @@ 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,8 +29,6 @@ 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 }
@@ -55,34 +53,10 @@ 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>()
// 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) {
fun freeze(pageOut: 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
@@ -100,7 +74,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, spill)
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) {
@@ -131,14 +105,9 @@ internal class SessionSuspendController(
frozen = records.values.toList()
if (complete && frozenSince == null) frozenSince = nowNanos()
if (!complete) {
// A spilled process is back only once its helper has read it back: until then a resume retries.
adopted = emptyList()
answeredLate = emptyList()
val running = startedAlive()
if (restoreSafely(frozen) && awaitRestored(running)) frozen = emptyList()
if (restoreSafely(frozen)) frozen = emptyList()
runAudio(resumeAudio)
}
rollbackPending = !complete && frozen.isNotEmpty()
if (interrupted) Thread.currentThread().interrupt()
}
completion(complete)
@@ -153,23 +122,12 @@ internal class SessionSuspendController(
fun resume(completion: (Boolean) -> Unit) {
submit({
val records = frozen
val advancedTo = advanceClock()
adopted = emptyList()
answeredLate = emptyList()
val running = startedAlive()
advanceClock()
runAudio(resumeAudio)
val resumed = restoreSafely(records)
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)
if (resumed) frozen = emptyList()
completion(resumed)
if (resumed) readBack()
}, { completion(false) })
}
@@ -177,10 +135,7 @@ 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)
@@ -194,25 +149,22 @@ internal class SessionSuspendController(
}
}
// 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
private fun advanceClock() {
val since = frozenSince ?: return
frozenSince = null
val now = nowNanos()
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return now
val control = clockControl?.takeIf { it.isFile && it.length() >= Long.SIZE_BYTES } ?: return
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) +
(now - since).coerceAtLeast(0L)
(nowNanos() - 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) {
@@ -323,15 +275,13 @@ internal class SessionSuspendController(
return tasks.takeIf { stopped && it.isNotEmpty() }
}
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>, spill: Boolean) {
private fun pageOut(records: MutableMap<Pair<Int, Long>, ProcessRecord>, root: Int, helpers: List<Int>) {
val control = zramControl?.takeIf { it.isFile } ?: return
val hold = holdFile(control)
try {
// 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)
hold.writeText(PAGE_OUT_REQUEST)
sleep(PAGE_OUT_POLL_MS)
if (spill) spill(control, records, root, helpers) else pageOut(control, records, root, helpers)
pageOut(control, records, root, helpers)
} catch (_: IOException) {
} finally {
hold.delete()
@@ -340,208 +290,15 @@ internal class SessionSuspendController(
private fun holdFile(control: File) = File(control.parentFile, "${control.name}.hold")
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)
// 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) {
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)
val targets = records.values.filter { record ->
try {
File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } }
} catch (_: IOException) {
false
}
}
if (targets.isEmpty()) return
pagedOutTargets = (pagedOutTargets + targets).distinct()
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
@@ -568,8 +325,7 @@ internal class SessionSuspendController(
false
}
private fun readBack(waitForRestore: Boolean = true) {
if (waitForRestore) awaitRestored()
private fun readBack() {
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
val control = zramControl?.takeIf { it.isFile } ?: return
@@ -655,12 +411,10 @@ 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' && !helperHeld) || state == 'Z' || state == 'X') continue
if (state == 'T' || state == 't' || state == 'Z' || state == 'X') continue
try {
threadSignal(record.pid, tid, SIGSTOP)
} catch (_: Throwable) {
@@ -677,10 +431,6 @@ 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 ->
@@ -692,15 +442,6 @@ 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) {
@@ -719,12 +460,10 @@ 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
val spilled = record in spilledTargets
if (current.state == 'T' || (current.state == 't' && !spilled)) return false
if (current.state == 'T' || current.state == 't') 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 }
@@ -738,11 +477,6 @@ 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
@@ -1,29 +0,0 @@
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
}
}
@@ -137,7 +137,7 @@ class InputSurfaceView(
val views = owners.values.distinct()
owners.clear()
for (view in views) {
if (view is HoldButton) { view.cancel(); continue }
if (view is HoldButton) { view.cancelTouches(); continue }
val cancel = MotionEvent.obtain(event.downTime, event.eventTime, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
try { view.dispatchTouchEvent(cancel) } finally { cancel.recycle() }
}
@@ -176,10 +176,23 @@ class InputSurfaceView(
val now = android.os.SystemClock.uptimeMillis()
val cancel = MotionEvent.obtain(now, now, MotionEvent.ACTION_CANCEL, 0f, 0f, 0)
try { cancelOwners(cancel) } finally { cancel.recycle() }
customCanvas?.let { canvas -> for (i in 0 until canvas.childCount) (canvas.getChildAt(i) as? HoldButton)?.cancel() }
forwardedPointers = 0
elementSources.forEach { it.release() }
}
/** Presses a button as a finger would, for input from outside the screen; [holder] tells holds apart. */
fun hold(elementId: String, holder: Int, held: Boolean, cancelled: Boolean = false): Boolean {
val canvas = customCanvas ?: return false
for (i in 0 until canvas.childCount) {
val button = canvas.getChildAt(i) as? HoldButton ?: continue
if ((button.tag as? InputSurfaceElement)?.id != elementId) continue
button.press(-1 - holder, held, cancelled)
return true
}
return false
}
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility != VISIBLE) releaseInputs()
@@ -487,6 +500,11 @@ class InputSurfaceView(
fun cancel() { pointers.clear(); set(false, cancelled = true); source?.release() }
fun cancelTouches() {
pointers.removeAll { it >= 0 }
if (pointers.isEmpty()) cancel()
}
override fun onDetachedFromWindow() { cancel(); super.onDetachedFromWindow() }
private fun set(pressed: Boolean, cancelled: Boolean = false) {
@@ -116,6 +116,7 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.HomeApp
import com.droiddeck.launcher.input.AirTrigger
import com.droiddeck.launcher.input.ControllerPrefs
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
@@ -238,6 +239,8 @@ private class DrawerFocus {
fun forget(page: SessionDrawerPage) { last.remove(page) }
}
data class AirTriggerMenu(val enabled: Boolean, val selected: Map<AirTrigger, String>, val buttons: List<Pair<String, String>>)
class DrawerActions(
val steam: Boolean,
val desktop: Boolean,
@@ -343,6 +346,9 @@ class DrawerActions(
val onControllerSize: (Int) -> Unit = {},
val onControllerOpacity: (Int) -> Unit = {},
val onRumble: (Boolean) -> Unit = {},
val airTriggers: AirTriggerMenu? = null,
val onAirTriggers: (Boolean) -> Unit = {},
val onAirTriggerButton: (AirTrigger, String) -> Unit = { _, _ -> },
val onSuspendPolicy: (String) -> Unit,
val onSteamDownloadsInBackground: (Boolean) -> Unit = {},
val onBackActionsInverted: (Boolean) -> Unit,
@@ -456,6 +462,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
remember { DrawerSectionState.load(drawerContext) }
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
var confirmStop by remember { mutableStateOf(false) }
var airTriggersShown by remember { mutableStateOf(false) }
var sheetCoords by remember { mutableStateOf<LayoutCoordinates?>(null) }
val widthContext = LocalContext.current
var savedWidth by remember { mutableStateOf(SessionPrefs.drawerWidthDp(widthContext)) }
@@ -467,15 +474,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
val focusManager = LocalFocusManager.current
// A page kept inside More is one step deeper than the strip: back returns to More before it closes the menu.
val insideMore = page in pages.inMore()
val airPanel = airTriggersShown && page == SessionDrawerPage.CONTROLLER && a.airTriggers != null
BackHandler(enabled = open) {
when {
host.open != null -> host.open = null
airPanel -> airTriggersShown = false
insideMore -> onPageChange(SessionDrawerPage.MORE)
else -> a.onClose()
}
}
BackHandler(enabled = open && confirmStop) { confirmStop = false }
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore)
val layerOpen = open && (host.open != null || appToChooseDisplay != null || confirmStop || insideMore || airPanel)
LaunchedEffect(layerOpen) { onLayerChange(layerOpen) }
var seenBackRequest by remember { mutableStateOf(backRequest) }
LaunchedEffect(backRequest) {
@@ -485,10 +494,23 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
confirmStop -> confirmStop = false
appToChooseDisplay != null -> appToChooseDisplay = null
host.open != null -> host.open = null
airPanel -> airTriggersShown = false
insideMore -> onPageChange(SessionDrawerPage.MORE)
}
}
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false }
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null; managing = false; airTriggersShown = false }
var airPanelFocused by remember { mutableStateOf(airPanel) }
LaunchedEffect(airPanel) {
val moved = airPanel != airPanelFocused
airPanelFocused = airPanel
if (!moved || !open || !controllerActive) return@LaunchedEffect
val target = if (airPanel) "air-triggers-toggle" else "air-triggers"
repeat(24) {
androidx.compose.runtime.withFrameNanos { }
focus.request(target)
if (focus.focused == target) return@LaunchedEffect
}
}
LaunchedEffect(host.open) {
if (host.open == "frame-generation") repeat(24) {
androidx.compose.runtime.withFrameNanos { }
@@ -574,6 +596,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
.controllerBack {
when {
host.open != null -> host.open = null
airPanel -> airTriggersShown = false
managing -> DrawerPages.heldFrom?.let { held ->
DrawerPages.rearrange(drawerContext, held)
releaseSignal++
@@ -650,7 +673,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
host.open = null; onPageChange(pages.strip().step(pages.tabFor(page), 1))
}
}
if (insideMore && !managing) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) }
if (insideMore && !managing && !airPanel) DrawerMoreBack(stringResource(page.title), focus.track(page, "more-back")) { host.open = null; onPageChange(SessionDrawerPage.MORE) }
if (airPanel && !managing) DrawerMoreBack(stringResource(R.string.air_triggers_title), focus.track(page, "air-triggers-back"),
parent = stringResource(page.title)) { host.open = null; airTriggersShown = false }
if (managing) ManageDrawerPages(
offeredDrawerPages(a.achievementsGame != null),
Modifier.weight(1f).fillMaxWidth().padding(top = 8.dp, start = 14.dp, end = 14.dp),
@@ -671,7 +696,11 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true, LocalDrawerSections provides sections) {
DrawerColumns(two = sheetWidth >= DRAWER_TWO_COLUMN_WIDTH && page.inColumns) {
when (page) {
SessionDrawerPage.CONTROLLER -> DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track)
SessionDrawerPage.CONTROLLER -> {
val airTriggers = a.airTriggers
if (airPanel && airTriggers != null) AirTriggersPanel(host, airTriggers, a, track)
else DrawerControllerPage(host, a, a.controllerConnected || controllerActive, track) { host.open = null; airTriggersShown = true }
}
SessionDrawerPage.HUD -> DrawerPerformancePage(host, a, track)
SessionDrawerPage.FRAMEGEN -> DrawerFrameGenPage(host, a, track)
SessionDrawerPage.DISPLAY -> DrawerDisplayPage(host, a, track)
@@ -731,7 +760,7 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
@Composable
private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: Boolean, track: (String) -> Modifier) {
private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected: Boolean, track: (String) -> Modifier, onAirTriggers: () -> Unit) {
val on = stringResource(R.string.widgets_on)
val off = stringResource(R.string.widgets_off)
val padTag = if (padConnected) stringResource(R.string.drawer_tag_controller) else null
@@ -746,9 +775,12 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected:
SessionPrefs.CONTROLLER_DUALSENSE to stringResource(R.string.mode_controller_dualsense),
SessionPrefs.CONTROLLER_XBOX360 to stringResource(R.string.mode_controller_x360))
val rumbleLabel = stringResource(R.string.ctrl_rumble)
if (a.padType != null || c != null) SettingsGroup(
val airTriggers = a.airTriggers
val airTriggersLabel = stringResource(R.string.air_triggers_title)
if (a.padType != null || c != null || airTriggers != null) SettingsGroup(
stringResource(R.string.input_device_settings), key = "controller-pad", tag = padTag,
detail = summary(a.padType?.let { padTypes.labelOf(it) }, c?.let { "$rumbleLabel ${if (it.rumble) on else off}" }),
detail = summary(a.padType?.let { padTypes.labelOf(it) }, c?.let { "$rumbleLabel ${if (it.rumble) on else off}" },
airTriggers?.let { "$airTriggersLabel ${if (it.enabled) on else off}" }),
) {
a.padType?.let { type ->
ChoiceRow(host, "pad-type", stringResource(R.string.input_virtual_controller), stringResource(R.string.input_virtual_controller_hint),
@@ -757,6 +789,10 @@ private fun DrawerControllerPage(host: MenuHost, a: DrawerActions, padConnected:
c?.let {
ToggleRow(host, "rumble", rumbleLabel, null, it.rumble, chipModifier = track("rumble"), onChange = a.onRumble)
}
airTriggers?.let {
ActionRow(airTriggersLabel, if (it.enabled) on else off, stringResource(R.string.air_triggers_open), onAirTriggers,
modifier = track("air-triggers"))
}
}
val oscChoices = if (a.steam) listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_STEAM_TOUCH to stringResource(R.string.osc_steam_touch), SessionPrefs.OSC_STEAM_QAM to stringResource(R.string.mode_osc_qam), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
else listOf(SessionPrefs.OSC_AUTO to stringResource(R.string.common_auto), SessionPrefs.OSC_ALWAYS to stringResource(R.string.common_always), SessionPrefs.OSC_NEVER to stringResource(R.string.common_never))
@@ -1322,15 +1358,15 @@ private fun DrawerPageTabs(page: SessionDrawerPage, pages: List<SessionDrawerPag
private const val LOOK_CUSTOM = "custom"
/** The row above a page kept inside More that goes back to the More list. */
/** The row above a page kept inside More, or a panel inside a page, that goes back to where it was opened from. */
@Composable
private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit) {
private fun DrawerMoreBack(title: String, modifier: Modifier, parent: String = stringResource(R.string.drawer_page_more), onBack: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val source = remember { MutableInteractionSource() }
val hot = source.collectIsFocusedAsState().value || source.collectIsHoveredAsState().value
val shape = RoundedCornerShape(12.dp)
val label = stringResource(R.string.drawer_more_back, stringResource(R.string.drawer_page_more))
val label = stringResource(R.string.drawer_more_back, parent)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = modifier.padding(top = 8.dp, start = 14.dp, end = 14.dp).fillMaxWidth().heightIn(min = 44.dp).clip(shape)
@@ -1344,12 +1380,26 @@ private fun DrawerMoreBack(title: String, modifier: Modifier, onBack: () -> Unit
.padding(horizontal = 8.dp),
) {
Icon(Icons.AutoMirrored.Outlined.ArrowBack, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(22.dp))
Text(stringResource(R.string.drawer_page_more), fontSize = 13.sp, color = colors.onSurfaceVariant)
Text(parent, fontSize = 13.sp, color = colors.onSurfaceVariant)
Text("·", fontSize = 13.sp, color = colors.onSurfaceVariant)
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
}
}
@Composable
private fun AirTriggersPanel(host: MenuHost, t: AirTriggerMenu, a: DrawerActions, track: (String) -> Modifier) {
CompositionLocalProvider(LocalDrawerSections provides null) { SettingsGroup(stringResource(R.string.air_triggers_title)) {
ToggleRow(host, "air-triggers-toggle", stringResource(R.string.air_triggers_use), stringResource(R.string.air_triggers_use_hint), t.enabled,
chipModifier = track("air-triggers-toggle"), onChange = a.onAirTriggers)
for (trigger in AirTrigger.entries) {
val key = "air-trigger-${trigger.name.lowercase()}"
val label = stringResource(if (trigger == AirTrigger.LEFT) R.string.air_trigger_left else R.string.air_trigger_right)
ChoiceRow(host, key, label, stringResource(R.string.air_trigger_button_hint), t.buttons, t.selected.getValue(trigger),
enabled = t.enabled, chipModifier = track(key)) { a.onAirTriggerButton(trigger, it) }
}
} }
}
/** The pages kept inside More, and the way into arranging which pages sit on the strip and which here. */
@Composable
private fun DrawerMorePage(host: MenuHost, pages: List<SessionDrawerPage>, a: DrawerActions, onOpen: (SessionDrawerPage) -> Unit, onEdit: () -> Unit, track: (String) -> Modifier) {
+7
View File
@@ -1337,6 +1337,13 @@
<string name="ctrl_size">حجم الأزرار</string>
<string name="ctrl_adaptive">عصي تكيّفية</string>
<string name="ctrl_rumble">اهتزاز اللعبة</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">فتح</string>
<string name="air_triggers_use">استخدام Air Triggers</string>
<string name="air_triggers_use_hint">يشغّل أزرار الكتف دون لوحة الأزرار أو العلامات من RedMagic، وتضغط بدلاً من ذلك أزرار تخطيط اللمس.</string>
<string name="air_trigger_left">Air Trigger الأيسر</string>
<string name="air_trigger_right">Air Trigger الأيمن</string>
<string name="air_trigger_button_hint">محفوظ لهذا التخطيط</string>
<string name="ctrl_dead_zone">المنطقة الميتة لعصا التحكم</string>
<string name="ctrl_steam_button">زر Steam</string>
<string name="ctrl_qam_button">زر QAM</string>
@@ -1343,6 +1343,13 @@
<string name="ctrl_size">Tamaño de botones</string>
<string name="ctrl_adaptive">Sticks adaptables</string>
<string name="ctrl_rumble">Vibración en juegos</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Abrir</string>
<string name="air_triggers_use">Usar los Air Triggers</string>
<string name="air_triggers_use_hint">Activa los gatillos de hombro sin el panel ni los marcadores de RedMagic. En su lugar, presionan botones de la disposición táctil.</string>
<string name="air_trigger_left">Air Trigger izquierdo</string>
<string name="air_trigger_right">Air Trigger derecho</string>
<string name="air_trigger_button_hint">Se guarda para esta disposición</string>
<string name="ctrl_dead_zone">Zona muerta de la palanca</string>
<string name="ctrl_steam_button">Botón Steam</string>
<string name="ctrl_qam_button">Botón QAM</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Размер на бутоните</string>
<string name="ctrl_adaptive">Адаптивни стикове</string>
<string name="ctrl_rumble">Вибрация от играта</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Отвори</string>
<string name="air_triggers_use">Използвай Air Triggers</string>
<string name="air_triggers_use_hint">Включва раменните спусъци без панела и маркерите на RedMagic. Вместо това те натискат бутони от сензорното разположение.</string>
<string name="air_trigger_left">Ляв Air Trigger</string>
<string name="air_trigger_right">Десен Air Trigger</string>
<string name="air_trigger_button_hint">Запазва се за това разположение</string>
<string name="ctrl_dead_zone">Мъртва зона на стика</string>
<string name="ctrl_steam_button">Бутон Steam</string>
<string name="ctrl_qam_button">Бутон QAM</string>
+7
View File
@@ -1323,6 +1323,13 @@
<string name="ctrl_size">Velikost tlačítek</string>
<string name="ctrl_adaptive">Adaptivní páčky</string>
<string name="ctrl_rumble">Vibrace ve hře</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Otevřít</string>
<string name="air_triggers_use">Používat Air Triggers</string>
<string name="air_triggers_use_hint">Zapne ramenní triggery bez panelu a značek RedMagic. Místo toho mačkají tlačítka dotykového rozložení.</string>
<string name="air_trigger_left">Levý Air Trigger</string>
<string name="air_trigger_right">Pravý Air Trigger</string>
<string name="air_trigger_button_hint">Uloženo pro toto rozložení</string>
<string name="ctrl_dead_zone">Mrtvá zóna páčky</string>
<string name="ctrl_steam_button">Tlačítko Steam</string>
<string name="ctrl_qam_button">Tlačítko QAM</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Knapstørrelse</string>
<string name="ctrl_adaptive">Adaptive styrepinde</string>
<string name="ctrl_rumble">Spilvibration</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Åbn</string>
<string name="air_triggers_use">Brug Air Triggers</string>
<string name="air_triggers_use_hint">Tænder skuldertriggerne uden RedMagics triggerpanel eller markører. De trykker i stedet på knapper i touch-layoutet.</string>
<string name="air_trigger_left">Venstre Air Trigger</string>
<string name="air_trigger_right">Højre Air Trigger</string>
<string name="air_trigger_button_hint">Gemt for dette layout</string>
<string name="ctrl_dead_zone">Dødzone for styrepind</string>
<string name="ctrl_steam_button">Steam-knap</string>
<string name="ctrl_qam_button">QAM-knap</string>
+7
View File
@@ -1301,6 +1301,13 @@
<string name="ctrl_size">Tastengröße</string>
<string name="ctrl_adaptive">Adaptive Sticks</string>
<string name="ctrl_rumble">Spielvibration</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Öffnen</string>
<string name="air_triggers_use">Air Triggers verwenden</string>
<string name="air_triggers_use_hint">Schaltet die Schultertrigger ohne das Trigger-Panel und die Markierungen von RedMagic ein. Sie drücken stattdessen Tasten des Touch-Layouts.</string>
<string name="air_trigger_left">Linker Air Trigger</string>
<string name="air_trigger_right">Rechter Air Trigger</string>
<string name="air_trigger_button_hint">Für dieses Layout gespeichert</string>
<string name="ctrl_dead_zone">Stick-Totzone</string>
<string name="ctrl_steam_button">Steam-Taste</string>
<string name="ctrl_qam_button">QAM-Taste</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Μέγεθος κουμπιών</string>
<string name="ctrl_adaptive">Προσαρμοστικοί μοχλοί</string>
<string name="ctrl_rumble">Κραδασμός παιχνιδιού</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Άνοιγμα</string>
<string name="air_triggers_use">Χρήση Air Triggers</string>
<string name="air_triggers_use_hint">Ενεργοποιεί τις σκανδάλες ώμου χωρίς τον πίνακα ή τους δείκτες του RedMagic. Αντί γι\' αυτό πατούν κουμπιά της διάταξης αφής.</string>
<string name="air_trigger_left">Αριστερό Air Trigger</string>
<string name="air_trigger_right">Δεξί Air Trigger</string>
<string name="air_trigger_button_hint">Αποθηκεύεται για αυτή τη διάταξη</string>
<string name="ctrl_dead_zone">Νεκρή ζώνη μοχλού</string>
<string name="ctrl_steam_button">Κουμπί Steam</string>
<string name="ctrl_qam_button">Κουμπί QAM</string>
+7
View File
@@ -1316,6 +1316,13 @@
<string name="ctrl_size">Tamaño de botones</string>
<string name="ctrl_adaptive">Sticks adaptables</string>
<string name="ctrl_rumble">Vibración en juegos</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Abrir</string>
<string name="air_triggers_use">Usar los Air Triggers</string>
<string name="air_triggers_use_hint">Activa los gatillos de hombro sin el panel ni los marcadores de RedMagic. En su lugar, pulsan botones de la disposición táctil.</string>
<string name="air_trigger_left">Air Trigger izquierdo</string>
<string name="air_trigger_right">Air Trigger derecho</string>
<string name="air_trigger_button_hint">Se guarda para esta disposición</string>
<string name="ctrl_dead_zone">Zona muerta de la palanca</string>
<string name="ctrl_steam_button">Botón Steam</string>
<string name="ctrl_qam_button">Botón QAM</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Painikkeiden koko</string>
<string name="ctrl_adaptive">Mukautuvat sauvat</string>
<string name="ctrl_rumble">Pelin tärinä</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Avaa</string>
<string name="air_triggers_use">Käytä Air Triggereitä</string>
<string name="air_triggers_use_hint">Ottaa olkaliipaisimet käyttöön ilman RedMagicin liipaisinpaneelia tai merkkejä. Ne painavat sen sijaan kosketusasettelun painikkeita.</string>
<string name="air_trigger_left">Vasen Air Trigger</string>
<string name="air_trigger_right">Oikea Air Trigger</string>
<string name="air_trigger_button_hint">Tallennetaan tälle asettelulle</string>
<string name="ctrl_dead_zone">Ohjaussauvan kuollut alue</string>
<string name="ctrl_steam_button">Steam-painike</string>
<string name="ctrl_qam_button">QAM-painike</string>
+7
View File
@@ -1315,6 +1315,13 @@
<string name="ctrl_size">Taille des boutons</string>
<string name="ctrl_adaptive">Joystick adaptatif</string>
<string name="ctrl_rumble">Vibration du jeu</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Ouvrir</string>
<string name="air_triggers_use">Utiliser les Air Triggers</string>
<string name="air_triggers_use_hint">Active les gâchettes d\'épaule sans le panneau ni les repères de RedMagic. Elles appuient à la place sur des boutons de la disposition tactile.</string>
<string name="air_trigger_left">Air Trigger gauche</string>
<string name="air_trigger_right">Air Trigger droit</string>
<string name="air_trigger_button_hint">Enregistré pour cette disposition</string>
<string name="ctrl_dead_zone">Zone morte du stick</string>
<string name="ctrl_steam_button">Bouton Steam</string>
<string name="ctrl_qam_button">Bouton QAM</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">बटन का आकार</string>
<string name="ctrl_adaptive">एडैप्टिव स्टिक</string>
<string name="ctrl_rumble">गेम वाइब्रेशन</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">खोलें</string>
<string name="air_triggers_use">Air Triggers इस्तेमाल करें</string>
<string name="air_triggers_use_hint">RedMagic के ट्रिगर पैनल या मार्कर के बिना शोल्डर ट्रिगर चालू करता है। इसके बजाय वे टच लेआउट के बटन दबाते हैं।</string>
<string name="air_trigger_left">लेफ़्ट Air Trigger</string>
<string name="air_trigger_right">राइट Air Trigger</string>
<string name="air_trigger_button_hint">इस लेआउट के लिए सहेजा गया</string>
<string name="ctrl_dead_zone">स्टिक का डेड ज़ोन</string>
<string name="ctrl_steam_button">Steam बटन</string>
<string name="ctrl_qam_button">QAM बटन</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Gombméret</string>
<string name="ctrl_adaptive">Adaptív karok</string>
<string name="ctrl_rumble">Játékvibráció</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Megnyitás</string>
<string name="air_triggers_use">Air Triggers használata</string>
<string name="air_triggers_use_hint">Bekapcsolja a vállravaszokat a RedMagic ravaszpanelje és jelölői nélkül. Helyettük az érintéses elrendezés gombjait nyomják meg.</string>
<string name="air_trigger_left">Bal Air Trigger</string>
<string name="air_trigger_right">Jobb Air Trigger</string>
<string name="air_trigger_button_hint">Ehhez az elrendezéshez mentve</string>
<string name="ctrl_dead_zone">Kar holtzónája</string>
<string name="ctrl_steam_button">Steam gomb</string>
<string name="ctrl_qam_button">QAM gomb</string>
+7
View File
@@ -1303,6 +1303,13 @@
<string name="ctrl_size">Ukuran tombol</string>
<string name="ctrl_adaptive">Stik adaptif</string>
<string name="ctrl_rumble">Getaran gim</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Buka</string>
<string name="air_triggers_use">Gunakan Air Triggers</string>
<string name="air_triggers_use_hint">Menyalakan trigger bahu tanpa panel atau penanda trigger RedMagic. Sebagai gantinya, trigger menekan tombol tata letak sentuh.</string>
<string name="air_trigger_left">Air Trigger kiri</string>
<string name="air_trigger_right">Air Trigger kanan</string>
<string name="air_trigger_button_hint">Disimpan untuk tata letak ini</string>
<string name="ctrl_dead_zone">Zona mati stik</string>
<string name="ctrl_steam_button">Tombol Steam</string>
<string name="ctrl_qam_button">Tombol QAM</string>
+7
View File
@@ -1307,6 +1307,13 @@
<string name="ctrl_size">Dimensione dei tasti</string>
<string name="ctrl_adaptive">Levette adattive</string>
<string name="ctrl_rumble">Vibrazione di gioco</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Apri</string>
<string name="air_triggers_use">Usa gli Air Triggers</string>
<string name="air_triggers_use_hint">Attiva i grilletti dorsali senza il pannello né gli indicatori di RedMagic. Premono invece i pulsanti del layout touch.</string>
<string name="air_trigger_left">Air Trigger sinistro</string>
<string name="air_trigger_right">Air Trigger destro</string>
<string name="air_trigger_button_hint">Salvato per questo layout</string>
<string name="ctrl_dead_zone">Zona morta dello stick</string>
<string name="ctrl_steam_button">Tasto Steam</string>
<string name="ctrl_qam_button">Tasto QAM</string>
+7
View File
@@ -1303,6 +1303,13 @@
<string name="ctrl_size">ボタンのサイズ</string>
<string name="ctrl_adaptive">アダプティブスティック</string>
<string name="ctrl_rumble">ゲームの振動</string>
<string name="air_triggers_title">Redmagic エアトリガー</string>
<string name="air_triggers_open">開く</string>
<string name="air_triggers_use">エアトリガーを使う</string>
<string name="air_triggers_use_hint">RedMagic のトリガーパネルやマーカーを出さずにショルダートリガーをオンにし、タッチレイアウトのボタンを押します。</string>
<string name="air_trigger_left">左エアトリガー</string>
<string name="air_trigger_right">右エアトリガー</string>
<string name="air_trigger_button_hint">このレイアウトに保存されます</string>
<string name="ctrl_dead_zone">スティックのデッドゾーン</string>
<string name="ctrl_steam_button">Steamボタン</string>
<string name="ctrl_qam_button">QAMボタン</string>
+7
View File
@@ -1303,6 +1303,13 @@
<string name="ctrl_size">버튼 크기</string>
<string name="ctrl_adaptive">적응형 스틱</string>
<string name="ctrl_rumble">게임 진동</string>
<string name="air_triggers_title">Redmagic 에어 트리거</string>
<string name="air_triggers_open">열기</string>
<string name="air_triggers_use">에어 트리거 사용</string>
<string name="air_triggers_use_hint">RedMagic 트리거 패널이나 표시 없이 숄더 트리거를 켜고, 대신 터치 레이아웃의 버튼을 누릅니다.</string>
<string name="air_trigger_left">왼쪽 에어 트리거</string>
<string name="air_trigger_right">오른쪽 에어 트리거</string>
<string name="air_trigger_button_hint">이 레이아웃에 저장됨</string>
<string name="ctrl_dead_zone">스틱 데드존</string>
<string name="ctrl_steam_button">Steam 버튼</string>
<string name="ctrl_qam_button">QAM 버튼</string>
+7
View File
@@ -1303,6 +1303,13 @@
<string name="ctrl_size">Saiz butang</string>
<string name="ctrl_adaptive">Stik adaptif</string>
<string name="ctrl_rumble">Getaran permainan</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Buka</string>
<string name="air_triggers_use">Guna Air Triggers</string>
<string name="air_triggers_use_hint">Menghidupkan pencetus bahu tanpa panel atau penanda pencetus RedMagic. Sebaliknya, ia menekan butang susun atur sentuh.</string>
<string name="air_trigger_left">Air Trigger kiri</string>
<string name="air_trigger_right">Air Trigger kanan</string>
<string name="air_trigger_button_hint">Disimpan untuk susun atur ini</string>
<string name="ctrl_dead_zone">Zon mati kayu bedik</string>
<string name="ctrl_steam_button">Butang Steam</string>
<string name="ctrl_qam_button">Butang QAM</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Knappestørrelse</string>
<string name="ctrl_adaptive">Adaptive stikker</string>
<string name="ctrl_rumble">Spillvibrasjon</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Åpne</string>
<string name="air_triggers_use">Bruk Air Triggers</string>
<string name="air_triggers_use_hint">Slår på skuldertriggerne uten RedMagics triggerpanel eller markører. De trykker i stedet på knapper i berøringsoppsettet.</string>
<string name="air_trigger_left">Venstre Air Trigger</string>
<string name="air_trigger_right">Høyre Air Trigger</string>
<string name="air_trigger_button_hint">Lagret for dette oppsettet</string>
<string name="ctrl_dead_zone">Dødsone for styrespak</string>
<string name="ctrl_steam_button">Steam-knapp</string>
<string name="ctrl_qam_button">QAM-knapp</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Knopgrootte</string>
<string name="ctrl_adaptive">Adaptieve sticks</string>
<string name="ctrl_rumble">Trillen in games</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Openen</string>
<string name="air_triggers_use">Air Triggers gebruiken</string>
<string name="air_triggers_use_hint">Zet de schoudertriggers aan zonder het triggerpaneel of de markeringen van RedMagic. Ze drukken in plaats daarvan knoppen van de aanraakindeling in.</string>
<string name="air_trigger_left">Linker Air Trigger</string>
<string name="air_trigger_right">Rechter Air Trigger</string>
<string name="air_trigger_button_hint">Opgeslagen voor deze indeling</string>
<string name="ctrl_dead_zone">Dode zone van stick</string>
<string name="ctrl_steam_button">Steam-knop</string>
<string name="ctrl_qam_button">QAM-knop</string>
+7
View File
@@ -1323,6 +1323,13 @@
<string name="ctrl_size">Rozmiar przycisków</string>
<string name="ctrl_adaptive">Adaptacyjne gałki</string>
<string name="ctrl_rumble">Wibracje gry</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Otwórz</string>
<string name="air_triggers_use">Używaj Air Triggers</string>
<string name="air_triggers_use_hint">Włącza spusty naramienne bez panelu i znaczników RedMagic. Zamiast tego naciskają przyciski układu dotykowego.</string>
<string name="air_trigger_left">Lewy Air Trigger</string>
<string name="air_trigger_right">Prawy Air Trigger</string>
<string name="air_trigger_button_hint">Zapisane dla tego układu</string>
<string name="ctrl_dead_zone">Martwa strefa drążka</string>
<string name="ctrl_steam_button">Przycisk Steam</string>
<string name="ctrl_qam_button">Przycisk QAM</string>
@@ -1307,6 +1307,13 @@
<string name="ctrl_size">Tamanho dos botões</string>
<string name="ctrl_adaptive">Analógicos adaptáveis</string>
<string name="ctrl_rumble">Vibração do jogo</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Abrir</string>
<string name="air_triggers_use">Utilizar os Air Triggers</string>
<string name="air_triggers_use_hint">Liga os gatilhos de ombro sem o painel nem os marcadores da RedMagic. Em vez disso, premem botões do esquema tátil.</string>
<string name="air_trigger_left">Air Trigger esquerdo</string>
<string name="air_trigger_right">Air Trigger direito</string>
<string name="air_trigger_button_hint">Guardado para este esquema</string>
<string name="ctrl_dead_zone">Zona morta do manípulo</string>
<string name="ctrl_steam_button">Botão Steam</string>
<string name="ctrl_qam_button">Botão QAM</string>
+7
View File
@@ -1315,6 +1315,13 @@
<string name="ctrl_size">Tamanho dos botões</string>
<string name="ctrl_adaptive">Analógicos adaptáveis</string>
<string name="ctrl_rumble">Vibração do jogo</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Abrir</string>
<string name="air_triggers_use">Usar os Air Triggers</string>
<string name="air_triggers_use_hint">Liga os gatilhos de ombro sem o painel nem os marcadores da RedMagic. Em vez disso, eles apertam botões do layout de toque.</string>
<string name="air_trigger_left">Air Trigger esquerdo</string>
<string name="air_trigger_right">Air Trigger direito</string>
<string name="air_trigger_button_hint">Salvo para este layout</string>
<string name="ctrl_dead_zone">Zona morta do analógico</string>
<string name="ctrl_steam_button">Botão Steam</string>
<string name="ctrl_qam_button">Botão QAM</string>
+7
View File
@@ -1316,6 +1316,13 @@
<string name="ctrl_size">Dimensiunea butoanelor</string>
<string name="ctrl_adaptive">Manșe adaptive</string>
<string name="ctrl_rumble">Vibrații de joc</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Deschide</string>
<string name="air_triggers_use">Folosește Air Triggers</string>
<string name="air_triggers_use_hint">Pornește triggerele de umăr fără panoul sau marcajele RedMagic. În schimb, ele apasă butoane din aranjamentul tactil.</string>
<string name="air_trigger_left">Air Trigger stâng</string>
<string name="air_trigger_right">Air Trigger drept</string>
<string name="air_trigger_button_hint">Salvat pentru acest aranjament</string>
<string name="ctrl_dead_zone">Zonă moartă a manetei</string>
<string name="ctrl_steam_button">Butonul Steam</string>
<string name="ctrl_qam_button">Butonul QAM</string>
+7
View File
@@ -1323,6 +1323,13 @@
<string name="ctrl_size">Размер кнопок</string>
<string name="ctrl_adaptive">Адаптивные стики</string>
<string name="ctrl_rumble">Вибрация в играх</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Открыть</string>
<string name="air_triggers_use">Использовать Air Triggers</string>
<string name="air_triggers_use_hint">Включает плечевые триггеры без панели и меток RedMagic. Вместо этого они нажимают кнопки сенсорной раскладки.</string>
<string name="air_trigger_left">Левый Air Trigger</string>
<string name="air_trigger_right">Правый Air Trigger</string>
<string name="air_trigger_button_hint">Сохраняется для этой раскладки</string>
<string name="ctrl_dead_zone">Мёртвая зона стика</string>
<string name="ctrl_steam_button">Кнопка Steam</string>
<string name="ctrl_qam_button">Кнопка QAM</string>
+7
View File
@@ -1309,6 +1309,13 @@
<string name="ctrl_size">Knappstorlek</string>
<string name="ctrl_adaptive">Adaptiva spakar</string>
<string name="ctrl_rumble">Spelvibration</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Öppna</string>
<string name="air_triggers_use">Använd Air Triggers</string>
<string name="air_triggers_use_hint">Slår på axelavtryckarna utan RedMagics avtryckarpanel eller markeringar. De trycker i stället på knappar i pekskärmslayouten.</string>
<string name="air_trigger_left">Vänster Air Trigger</string>
<string name="air_trigger_right">Höger Air Trigger</string>
<string name="air_trigger_button_hint">Sparas för den här layouten</string>
<string name="ctrl_dead_zone">Styrspakens dödzon</string>
<string name="ctrl_steam_button">Steam-knappen</string>
<string name="ctrl_qam_button">QAM-knappen</string>
+7
View File
@@ -1303,6 +1303,13 @@
<string name="ctrl_size">ขนาดปุ่ม</string>
<string name="ctrl_adaptive">สติ๊กแบบปรับอัตโนมัติ</string>
<string name="ctrl_rumble">การสั่นของเกม</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">เปิด</string>
<string name="air_triggers_use">ใช้ Air Triggers</string>
<string name="air_triggers_use_hint">เปิดทริกเกอร์ไหล่โดยไม่แสดงแผงทริกเกอร์หรือเครื่องหมายของ RedMagic และให้กดปุ่มในการจัดวางแบบสัมผัสแทน</string>
<string name="air_trigger_left">Air Trigger ซ้าย</string>
<string name="air_trigger_right">Air Trigger ขวา</string>
<string name="air_trigger_button_hint">บันทึกไว้สำหรับการจัดวางนี้</string>
<string name="ctrl_dead_zone">เดดโซนของแอนะล็อกสติ๊ก</string>
<string name="ctrl_steam_button">ปุ่ม Steam</string>
<string name="ctrl_qam_button">ปุ่ม QAM</string>
+7
View File
@@ -1301,6 +1301,13 @@
<string name="ctrl_size">Düğme boyutu</string>
<string name="ctrl_adaptive">Uyarlanabilir çubuklar</string>
<string name="ctrl_rumble">Oyun titreşimi</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Aç</string>
<string name="air_triggers_use">Air Triggers kullan</string>
<string name="air_triggers_use_hint">Omuz tetiklerini RedMagic tetik paneli veya işaretleri olmadan açar. Bunun yerine dokunmatik düzenin düğmelerine basarlar.</string>
<string name="air_trigger_left">Sol Air Trigger</string>
<string name="air_trigger_right">Sağ Air Trigger</string>
<string name="air_trigger_button_hint">Bu düzen için kaydedilir</string>
<string name="ctrl_dead_zone">Çubuk ölü bölgesi</string>
<string name="ctrl_steam_button">Steam düğmesi</string>
<string name="ctrl_qam_button">QAM düğmesi</string>
+7
View File
@@ -1323,6 +1323,13 @@
<string name="ctrl_size">Розмір кнопок</string>
<string name="ctrl_adaptive">Адаптивні стики</string>
<string name="ctrl_rumble">Вібрація гри</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Відкрити</string>
<string name="air_triggers_use">Використовувати Air Triggers</string>
<string name="air_triggers_use_hint">Вмикає плечові тригери без панелі та міток RedMagic. Натомість вони натискають кнопки сенсорної розкладки.</string>
<string name="air_trigger_left">Лівий Air Trigger</string>
<string name="air_trigger_right">Правий Air Trigger</string>
<string name="air_trigger_button_hint">Зберігається для цієї розкладки</string>
<string name="ctrl_dead_zone">Мертва зона стіка</string>
<string name="ctrl_steam_button">Кнопка Steam</string>
<string name="ctrl_qam_button">Кнопка QAM</string>
+7
View File
@@ -1303,6 +1303,13 @@
<string name="ctrl_size">Kích thước nút</string>
<string name="ctrl_adaptive">Cần thích ứng</string>
<string name="ctrl_rumble">Rung khi chơi game</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Mở</string>
<string name="air_triggers_use">Dùng Air Triggers</string>
<string name="air_triggers_use_hint">Bật trigger vai mà không hiện bảng trigger hay điểm đánh dấu của RedMagic. Thay vào đó, chúng nhấn các nút của bố cục cảm ứng.</string>
<string name="air_trigger_left">Air Trigger trái</string>
<string name="air_trigger_right">Air Trigger phải</string>
<string name="air_trigger_button_hint">Được lưu cho bố cục này</string>
<string name="ctrl_dead_zone">Vùng chết của cần điều khiển</string>
<string name="ctrl_steam_button">Nút Steam</string>
<string name="ctrl_qam_button">Nút QAM</string>
@@ -1386,6 +1386,13 @@
<string name="ctrl_size">按钮大小</string>
<string name="ctrl_adaptive">自适应摇杆</string>
<string name="ctrl_rumble">游戏震动</string>
<string name="air_triggers_title">红魔肩键</string>
<string name="air_triggers_open">打开</string>
<string name="air_triggers_use">使用肩键</string>
<string name="air_triggers_use_hint">开启肩键,但不显示红魔的肩键面板和屏幕标记。肩键改为按下触控布局中的按钮。</string>
<string name="air_trigger_left">左肩键</string>
<string name="air_trigger_right">右肩键</string>
<string name="air_trigger_button_hint">按此布局保存</string>
<string name="ctrl_dead_zone">摇杆死区</string>
<string name="ctrl_steam_button">Steam 按钮</string>
<string name="ctrl_qam_button">QAM 按钮</string>
@@ -1302,6 +1302,13 @@
<string name="ctrl_size">按鍵大小</string>
<string name="ctrl_adaptive">自動調整搖桿</string>
<string name="ctrl_rumble">遊戲震動</string>
<string name="air_triggers_title">紅魔肩鍵</string>
<string name="air_triggers_open">開啟</string>
<string name="air_triggers_use">使用肩鍵</string>
<string name="air_triggers_use_hint">開啟肩鍵,但不顯示紅魔的肩鍵面板和螢幕標記。肩鍵改為按下觸控佈局中的按鈕。</string>
<string name="air_trigger_left">左肩鍵</string>
<string name="air_trigger_right">右肩鍵</string>
<string name="air_trigger_button_hint">按此佈局儲存</string>
<string name="ctrl_dead_zone">搖桿死區</string>
<string name="ctrl_steam_button">Steam 按鈕</string>
<string name="ctrl_qam_button">QAM 按鈕</string>
@@ -1302,6 +1302,13 @@
<string name="ctrl_size">按鍵大小</string>
<string name="ctrl_adaptive">自適應搖桿</string>
<string name="ctrl_rumble">遊戲震動</string>
<string name="air_triggers_title">紅魔肩鍵</string>
<string name="air_triggers_open">開啟</string>
<string name="air_triggers_use">使用肩鍵</string>
<string name="air_triggers_use_hint">開啟肩鍵,但不顯示紅魔的肩鍵面板和螢幕標記。肩鍵改為按下觸控版面配置中的按鈕。</string>
<string name="air_trigger_left">左肩鍵</string>
<string name="air_trigger_right">右肩鍵</string>
<string name="air_trigger_button_hint">依此版面配置儲存</string>
<string name="ctrl_dead_zone">搖桿死區</string>
<string name="ctrl_steam_button">Steam 按鈕</string>
<string name="ctrl_qam_button">QAM 按鈕</string>
+7
View File
@@ -1499,6 +1499,13 @@
<string name="ctrl_size">Button size</string>
<string name="ctrl_adaptive">Adaptive sticks</string>
<string name="ctrl_rumble">Game vibration</string>
<string name="air_triggers_title">Redmagic Air Triggers</string>
<string name="air_triggers_open">Open</string>
<string name="air_triggers_use">Use Air Triggers</string>
<string name="air_triggers_use_hint">Turns on the shoulder triggers without RedMagic\'s trigger panel or markers. They press buttons of the touch layout instead.</string>
<string name="air_trigger_left">Left Air Trigger</string>
<string name="air_trigger_right">Right Air Trigger</string>
<string name="air_trigger_button_hint">Saved for this layout</string>
<string name="ctrl_dead_zone">Stick dead zone</string>
<string name="ctrl_steam_button">Steam button</string>
<string name="ctrl_qam_button">QAM button</string>
@@ -0,0 +1,178 @@
package com.droiddeck.launcher.input
import android.view.KeyEvent
import java.io.File
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], manifest = Config.NONE, shadows = [JoyConPadTest.RecordingWriter::class])
class RedMagicAirTriggersTest {
private val events = mutableListOf<String>()
private val router = InputRouter(object : InputOutput {
override fun key(code: Int, down: Boolean) { events += "key:$code:$down" }
override fun button(code: Int, down: Boolean) { events += "button:$code:$down" }
override fun pointer(dx: Float, dy: Float) {}
override fun scroll(steps: Int) {}
override fun command(command: InputCommand) { events += command.name }
override fun command(command: InputCommand, role: InputRole) { events += "${command.name}:$role" }
override fun requestMotion() {}
})
private val context = RuntimeEnvironment.getApplication()
private val bridge = PadBridge(File(context.cacheDir, "air-trigger-input"))
private val input = AirTriggerInput(bridge)
private val lt = InputSurfaceElement(InputControl.LT, .1f, .1f, .1f, .1f)
private val rt = InputSurfaceElement(InputControl.RT, .8f, .1f, .1f, .1f)
private val jump = InputSurfaceElement(InputControl.A, .8f, .8f, .1f, .1f, id = "custom:jump", name = "Jump")
private val stick = InputSurfaceElement(InputControl.LS, .1f, .7f, .2f, .2f)
private val layout = SavedInputLayout("pad", "Pad", listOf(lt, rt, jump, stick))
@Before fun setup() { bridge.setInputRouter(router); DeckControls.setRouter(router) }
@After fun close() { input.close(); bridge.stop(); DeckControls.setRouter(null); DeckControls.releaseAll() }
private fun bind(vararg actions: Pair<String, InputAction>) {
bridge.setInputProfile(InputProfile("test", elements = mapOf(InputRole.PRIMARY to mapOf(*actions))))
}
private fun down(trigger: AirTrigger, enabled: Boolean = true, repeat: Int = 0) = input.onKey(trigger, KeyEvent.ACTION_DOWN, repeat, enabled)
private fun up(trigger: AirTrigger) = input.onKey(trigger, KeyEvent.ACTION_UP, 0, true)
@Test fun onlyTheTriggerDeviceKeysAreAirTriggers() {
assertEquals(AirTrigger.LEFT, AirTrigger.of(KeyEvent.KEYCODE_F7, "nubia_tgk_aw_sar0_ch0"))
assertEquals(AirTrigger.RIGHT, AirTrigger.of(KeyEvent.KEYCODE_F8, "nubia_tgk_aw_sar0_ch0"))
assertNull(AirTrigger.of(KeyEvent.KEYCODE_F7, "Keychron K2"))
assertNull(AirTrigger.of(KeyEvent.KEYCODE_F8, null))
assertNull(AirTrigger.of(KeyEvent.KEYCODE_VOLUME_DOWN, "nubia_tgk_aw_sar0_ch0"))
}
@Test fun theTriggerLightUsesTheEffectPickedInRedMagicsSettings() {
val settings = """{"version":1,"left_up":{"enable":true,"id":"107"},"shoulder_effects":{"close":"02000000","steady":"02101000"},"selection":"02101000"}"""
assertEquals("02101000", RedMagicAirTriggers.shoulderEffect(settings))
assertNull(RedMagicAirTriggers.shoulderEffect(null))
assertNull(RedMagicAirTriggers.shoulderEffect("not json"))
assertNull(RedMagicAirTriggers.shoulderEffect("""{"version":1}"""))
assertNull(RedMagicAirTriggers.shoulderEffect("""{"selection":"021"}"""))
}
@Test fun triggersDefaultToTheLayoutTriggersAndFollowAChoiceThatStillExists() {
assertEquals(lt, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, null))
assertEquals(rt, AirTriggerButtons.resolve(layout, AirTrigger.RIGHT, null))
assertEquals(jump, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, "custom:jump"))
assertEquals(lt, AirTriggerButtons.resolve(layout, AirTrigger.LEFT, "custom:removed"))
assertEquals(listOf(lt, rt, jump), AirTriggerButtons.options(layout))
}
@Test fun aLayoutWithoutTriggersStillOffersTheControllerTriggers() {
val buttons = SavedInputLayout("buttons", "Buttons", listOf(jump))
assertEquals(listOf("custom:jump", "legacy:lt", "legacy:rt"), AirTriggerButtons.options(buttons).map { it.id })
assertEquals("legacy:rt", AirTriggerButtons.resolve(buttons, AirTrigger.RIGHT, null).id)
assertEquals("legacy:lt", AirTriggerButtons.resolve(null, AirTrigger.LEFT, null).id)
}
@Test fun choicesAreSavedPerLayoutAndTheToggleStartsOff() {
assertFalse(AirTriggerPrefs.enabled(context))
AirTriggerPrefs.setEnabled(context, true)
AirTriggerPrefs.setButton(context, "pad", AirTrigger.LEFT, "custom:jump")
assertTrue(AirTriggerPrefs.enabled(context))
assertEquals("custom:jump", AirTriggerPrefs.button(context, "pad", AirTrigger.LEFT))
assertNull(AirTriggerPrefs.button(context, "pad", AirTrigger.RIGHT))
assertNull(AirTriggerPrefs.button(context, "other", AirTrigger.LEFT))
}
@Test fun aTriggerPressesTheChosenLayoutButton() {
bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57)))
input.configure(mapOf(AirTrigger.LEFT to lt, AirTrigger.RIGHT to jump))
assertTrue(down(AirTrigger.LEFT)); assertTrue(down(AirTrigger.RIGHT))
assertTrue(up(AirTrigger.RIGHT)); assertTrue(up(AirTrigger.LEFT))
assertEquals(listOf("key:42:true", "key:57:true", "key:57:false", "key:42:false"), events)
}
@Test fun keyRepeatsAndPressesWhileInputIsBlockedAreSwallowed() {
bind("legacy:lt" to InputAction.Keys(listOf(42)))
input.configure(mapOf(AirTrigger.LEFT to lt))
assertTrue(down(AirTrigger.LEFT, enabled = false))
assertTrue(up(AirTrigger.LEFT))
assertTrue(down(AirTrigger.LEFT)); assertTrue(down(AirTrigger.LEFT, repeat = 1))
assertTrue(up(AirTrigger.LEFT))
assertEquals(listOf("key:42:true", "key:42:false"), events)
}
@Test fun switchingOffReleasesAHeldButtonAndLetsTheKeysThrough() {
bind("legacy:lt" to InputAction.Keys(listOf(42)))
input.configure(mapOf(AirTrigger.LEFT to lt))
assertFalse(down(AirTrigger.RIGHT))
down(AirTrigger.LEFT)
input.configure(emptyMap())
assertEquals(listOf("key:42:true", "key:42:false"), events)
assertTrue(up(AirTrigger.LEFT))
assertFalse(down(AirTrigger.LEFT))
assertEquals(2, events.size)
}
@Test fun aButtonShownOnScreenTakesThePressAndTheTriggersLight() {
val screen = mutableListOf<String>()
val lights = mutableListOf<Int>()
val onScreen = AirTriggerInput(bridge, { id, trigger, held, cancelled -> screen += "$id:$trigger:$held:$cancelled"; id == "custom:jump" }, { lights += it })
bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57)))
onScreen.configure(mapOf(AirTrigger.LEFT to lt, AirTrigger.RIGHT to jump))
onScreen.onKey(AirTrigger.RIGHT, KeyEvent.ACTION_DOWN, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true)
onScreen.onKey(AirTrigger.RIGHT, KeyEvent.ACTION_UP, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true)
onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, false); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true)
onScreen.close()
assertEquals(listOf("custom:jump:RIGHT:true:false", "legacy:lt:LEFT:true:false", "custom:jump:RIGHT:false:false"), screen)
assertEquals(listOf("key:42:true", "key:42:false"), events)
assertEquals(listOf(108, 106, 109, 107), lights)
}
@Test fun switchingOffLetsGoOfTheOnScreenButton() {
val screen = mutableListOf<String>()
val onScreen = AirTriggerInput(bridge, { id, trigger, held, cancelled -> screen += "$id:$trigger:$held:$cancelled"; true })
onScreen.configure(mapOf(AirTrigger.LEFT to jump))
onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true)
onScreen.configure(emptyMap())
assertTrue(onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true))
assertEquals(listOf("custom:jump:LEFT:true:false", "custom:jump:LEFT:false:true"), screen)
}
@Test fun aForcedReleaseDoesNotRunACommandButtonButAKeyUpDoes() {
bind("custom:jump" to InputAction.Command(InputCommand.KEYBOARD))
input.configure(mapOf(AirTrigger.LEFT to jump))
down(AirTrigger.LEFT)
input.release()
up(AirTrigger.LEFT)
assertEquals(emptyList<String>(), events)
down(AirTrigger.LEFT); up(AirTrigger.LEFT)
assertEquals(listOf("KEYBOARD:PRIMARY"), events)
}
@Test fun aToggleLatchedWhileItsButtonWasHiddenIsHandedToTheShownButton() {
var shown = false
val screen = mutableListOf<String>()
val onScreen = AirTriggerInput(bridge, { id, _, held, _ -> screen += "$id:$held"; shown })
bind("custom:jump" to InputAction.Keys(listOf(57)))
onScreen.configure(mapOf(AirTrigger.LEFT to jump.copy(toggle = true)))
onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true); onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true)
assertEquals(listOf("key:57:true"), events)
shown = true
onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_DOWN, 0, true)
assertEquals(listOf("key:57:true", "key:57:false"), events)
onScreen.onKey(AirTrigger.LEFT, KeyEvent.ACTION_UP, 0, true)
onScreen.close()
assertEquals(listOf("custom:jump:true", "custom:jump:true", "custom:jump:false"), screen)
}
@Test fun choosingAnotherButtonMovesTheTriggerWithoutLeavingTheOldOneHeld() {
bind("legacy:lt" to InputAction.Keys(listOf(42)), "custom:jump" to InputAction.Keys(listOf(57)))
input.configure(mapOf(AirTrigger.LEFT to lt))
down(AirTrigger.LEFT)
input.configure(mapOf(AirTrigger.LEFT to jump))
up(AirTrigger.LEFT)
down(AirTrigger.LEFT); up(AirTrigger.LEFT)
assertEquals(listOf("key:42:true", "key:42:false", "key:57:true", "key:57:false"), events)
}
}
@@ -124,450 +124,6 @@ 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")
@@ -929,7 +485,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, var tracer: Int? = null)
private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0)
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)
@@ -937,20 +493,6 @@ 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?>()
@@ -965,7 +507,6 @@ 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
@@ -981,32 +522,9 @@ 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++; onAudioResume?.invoke() },
{ rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ },
proc, ::signal, ::threadSignal, ::sleep, { now }, executor,
zramControl = control,
clockControl = clock,
@@ -1017,15 +535,12 @@ 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 }
@@ -1035,34 +550,14 @@ class SessionSuspendControllerTest {
else group.threads.firstOrNull {
it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last())
}?.state = 't'
} else if (signal == URG && pid == OTHER) {
// a second guest that spills at once and whose helper reads back only when the test lets it
if (request?.startsWith("4") == true) {
File(control.parentFile, "${control.name}.ack.$OTHER").writeText("1000")
otherHeld = true
other.threads.forEach { it.state = 't' }
}
} else if (signal == URG) {
if (request?.startsWith("4") == true) {
if (!handlerReplaced) {
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
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) 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' }
}
if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' }
}
sync()
}
@@ -1070,88 +565,14 @@ 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("") }
}
@@ -1170,7 +591,7 @@ class SessionSuspendControllerTest {
gameResidentKb += moved
if (gameSwapKb == 0L) pagingIn = false
}
if (root.threads.first().state != 'T' && !continuing && !parked) game.threads.forEach {
if (root.threads.first().state != 'T' && !continuing) game.threads.forEach {
if (it.state != 'Z') { it.state = 'S'; it.cpu++ }
}
afterSleep?.invoke()
@@ -1190,7 +611,7 @@ class SessionSuspendControllerTest {
"TracerPid: ${group.tracer}\n" +
if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb kB\n" else "",
)
if (group == game || group == other) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n")
if (group == game) 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()
@@ -1198,7 +619,6 @@ 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")
}
}
}
@@ -1241,8 +661,5 @@ 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
}
}
@@ -1,95 +0,0 @@
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))
}
}
@@ -77,6 +77,59 @@ class InputSurfaceTouchTest {
assertFalse(state().isDown(PadState.A))
}
@Test fun anOutsideHoldPressesAndLightsTheButtonAlongsideAFinger() {
val surface = view.inputSurface
val button = (surface.javaClass.getDeclaredField("customCanvas").also { it.isAccessible = true }.get(surface) as ViewGroup).getChildAt(0)
fun lit() = button.javaClass.getDeclaredMethod("getHighlighted").also { it.isAccessible = true }.invoke(button) as Boolean
assertTrue(surface.hold(a.id, 0, true))
assertTrue(state().isDown(PadState.A))
assertTrue(lit())
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f))
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f))
assertTrue(state().isDown(PadState.A))
assertTrue(surface.hold(a.id, 0, false))
assertFalse(state().isDown(PadState.A))
assertFalse(lit())
assertFalse(surface.hold("custom:missing", 0, true))
}
@Test fun aCancelledTouchLeavesAnOutsideHoldOnTheButton() {
val surface = view.inputSurface
assertTrue(surface.hold(a.id, 0, true))
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f))
touch(MotionEvent.ACTION_CANCEL, 1 to (800f to 240f))
assertTrue(state().isDown(PadState.A))
assertTrue(surface.hold(a.id, 0, false))
assertFalse(state().isDown(PadState.A))
}
@Test fun releasingAllInputLetsGoOfAnOutsideHold() {
val surface = view.inputSurface
val button = (surface.javaClass.getDeclaredField("customCanvas").also { it.isAccessible = true }.get(surface) as ViewGroup).getChildAt(0)
fun lit() = button.javaClass.getDeclaredMethod("getHighlighted").also { it.isAccessible = true }.invoke(button) as Boolean
assertTrue(surface.hold(a.id, 0, true))
view.releaseAll()
assertFalse(state().isDown(PadState.A))
assertFalse(lit())
touch(MotionEvent.ACTION_DOWN, 1 to (800f to 240f))
assertTrue(state().isDown(PadState.A))
touch(MotionEvent.ACTION_UP, 1 to (800f to 240f))
assertTrue(surface.hold(a.id, 0, false))
assertFalse(state().isDown(PadState.A))
}
@Test fun aCancelledOutsideHoldDoesNotRunTheButtonsCommand() {
val surface = view.inputSurface
assertTrue(surface.hold(keyboard.id, 0, true))
assertTrue(surface.hold(keyboard.id, 0, false, cancelled = true))
assertEquals(emptyList<String>(), events)
assertTrue(surface.hold(keyboard.id, 0, true))
assertTrue(surface.hold(keyboard.id, 0, false))
assertEquals(listOf("KEYBOARD:PRIMARY"), events)
}
@Test fun steamDeckStylingKeepsTheHeldButtonAndItsHitArea() {
val button = a.copy(buttonShape = InputButtonShape.CIRCLE)
show(button)
+4 -1
View File
@@ -69,7 +69,10 @@ screen under gamescope. Under gamescope it passes `--nosocket=wayland --socket=x
`XDG_SESSION_TYPE=x11`. Otherwise Flatpak finds the app compositor's `wayland-0` and the window
opens behind gamescope. gamescope's own Wayland socket is no alternative: Chromium on Wayland
asks the render node it names for a DRM version, which KGSL cannot give, and aborts. The
launcher also starts a session bus when there is none. On the Linux desktop, the apps' exported
launcher also starts a session bus when there is none. Flatpak's `host` permission skips `/root`,
since a desktop's homes live under `/home`, but the session's home is `/root`. An app granted `host`
and not `home` is therefore also given `home` in the same mode, which brings in the session's mounts
there, such as `/root/ROMs`. On the Linux desktop, the apps' exported
menu entries appear in Plasma's launcher. Games are wrapped through `droiddeck-gpu` like the
rootfs's own, since the desktop composites in software.
-16
View File
@@ -97,22 +97,6 @@ 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
@@ -6,11 +6,11 @@ case ":${XDG_DATA_DIRS:-}:" in
*"/flatpak/exports/share:"*) ;;
*) export XDG_DATA_DIRS=$HOME/.local/share/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share} ;;
esac
socket=()
options=()
if [ -n "${DD_INSIDE:-}" ] || [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
unset WAYLAND_DISPLAY
export XDG_SESSION_TYPE=x11
socket=(--nosocket=wayland --socket=x11)
options=(--nosocket=wayland --socket=x11)
fi
app=
for arg in "$@"; do
@@ -20,8 +20,15 @@ gpu=("${BASH_SOURCE[0]%/*}/droiddeck-game-gpu")
location=
[ -n "$app" ] && location=$(flatpak info --show-location "$app" 2>/dev/null)
[ -n "$location" ] && gpu+=(--for "$location/files")
echo "== flatpak run ${socket[*]} $*"
filesystems=
[ -n "$location" ] && filesystems=$(flatpak info --show-permissions "$app" 2>/dev/null | sed -n 's/^filesystems=//p')
case ";$filesystems" in
*";home;"*|*";home:"*) ;;
*";host:ro;"*) options+=(--filesystem=home:ro) ;;
*";host;"*|*";host:"*) options+=(--filesystem=home) ;;
esac
echo "== flatpak run ${options[*]} $*"
if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && command -v dbus-run-session >/dev/null 2>&1; then
exec "${gpu[@]}" -- dbus-run-session -- flatpak run "${socket[@]}" "$@"
exec "${gpu[@]}" -- dbus-run-session -- flatpak run "${options[@]}" "$@"
fi
exec "${gpu[@]}" -- flatpak run "${socket[@]}" "$@"
exec "${gpu[@]}" -- flatpak run "${options[@]}" "$@"
+10 -464
View File
@@ -13,8 +13,6 @@
#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
@@ -42,18 +40,7 @@
#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)
@@ -219,23 +206,6 @@ 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)
@@ -243,11 +213,6 @@ 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;
@@ -256,15 +221,11 @@ 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;
@@ -279,13 +240,12 @@ 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] > '4') return -1;
if (n < 1 || text[0] < '0' || text[0] > '3') 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' || text[0] == '3') && *want == 0) return -1;
if (text[0] >= '2' && *want == 0) return -1;
return text[0] - '0';
}
@@ -460,445 +420,42 @@ static unsigned long zr_walk(int mode, unsigned long want, unsigned long lo, uns
return done;
}
static void zr_ack(long value, const char *suffix) {
char path[sizeof(zr_ctl) + sizeof(".restored.") + 20];
static void zr_ack(long value, int trim) {
const char *suffix = trim ? ".trim." : ".ack.";
char path[sizeof(zr_ctl) + sizeof(".trim.") + 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 = __atomic_load_n(&zr_owner, __ATOMIC_ACQUIRE);
if (pid == 0) pid = zr_sys(SYS_getpid);
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_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);
while (d > 0) path[n++] = digits[--d];
for (n = 0; 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 ? ".trim." : ".ack.");
if (mode > 0) zr_ack(-1, mode > 1);
if (mode < 2) {
zr_walk(mode, 1, 0, 0);
zr_gen++;
if (mode == 1) zr_ack(1, ".ack.");
if (mode == 1) zr_ack(1, 0);
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)), ".trim.");
zr_ack((long)(done * (zr_page / 1024)), 1);
}
static void zr_drain(int worker) {
@@ -910,13 +467,6 @@ 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);
}
@@ -974,7 +524,6 @@ 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++)
@@ -1030,7 +579,6 @@ 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);
}
@@ -1047,8 +595,6 @@ 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) {
+31 -2
View File
@@ -30,9 +30,16 @@ class GameGpuLaunchersTest(unittest.TestCase):
% (" ".join(KEYS), self.out))
self.report.chmod(0o755)
flatpak = self.tools / "flatpak"
self.permissions = self.tmp / "permissions"
self.args = self.tmp / "args"
flatpak.write_text("#!/bin/sh\n"
"if [ \"$1\" = info ]; then [ \"$3\" = org.example.App ] && echo %s; exit 0; fi\n"
"exec %s\n" % (self.app, self.report))
"if [ \"$1\" = info ]; then\n"
" [ \"$3\" = org.example.App ] || exit 0\n"
" if [ \"$2\" = --show-permissions ]; then cat %s 2>/dev/null; else echo %s; fi\n"
" exit 0\n"
"fi\n"
"printf '%%s\\n' \"$@\" > %s\n"
"exec %s\n" % (self.permissions, self.app, self.args, self.report))
flatpak.chmod(0o755)
def chromium(self):
@@ -100,6 +107,28 @@ class GameGpuLaunchersTest(unittest.TestCase):
def test_a_flatpak_without_the_game_setting_is_unchanged(self):
self.assertEqual("sysmem", self.flatpak({"TU_DEBUG": "sysmem"})["TU_DEBUG"])
def flatpak_filesystems(self, granted):
self.permissions.write_text("[Context]\nshared=network;ipc;\nfilesystems=%s\n" % granted)
self.flatpak()
return [a for a in self.args.read_text().splitlines() if a.startswith("--filesystem=")]
def test_host_access_reaches_the_home_folder_and_its_mounts(self):
self.assertEqual(["--filesystem=home:ro"],
self.flatpak_filesystems("host:ro;xdg-run/gamescope-0:ro;xdg-desktop:create;"))
self.assertEqual(["--filesystem=home"], self.flatpak_filesystems("xdg-desktop;host;"))
self.assertEqual(["--filesystem=home"], self.flatpak_filesystems("host:create;"))
def test_apps_without_host_access_or_with_their_own_home_grant_are_unchanged(self):
self.assertEqual([], self.flatpak_filesystems("home:ro;host;"))
self.assertEqual([], self.flatpak_filesystems("host;home;"))
self.assertEqual([], self.flatpak_filesystems("host-os:ro;host-etc;xdg-download;"))
self.assertEqual([], self.flatpak_filesystems(""))
self.permissions.unlink()
self.flatpak()
args = self.args.read_text().splitlines()
self.assertEqual(["--command=app", "org.example.App"], args[-2:])
self.assertFalse([a for a in args if a.startswith("--filesystem=")])
def test_a_snap_gets_the_game_setting_unless_it_is_chromium(self):
try:
snap_run = runpy.run_path(str(BIN / "droiddeck-snap-run"))
-462
View File
@@ -1,462 +0,0 @@
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()