diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 8b2509a68c..63f0eed8a5 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -541,6 +541,13 @@ static void cursor_publish_shm(struct wl_shm_buffer *shm, int hx, int hy) { wl_shm_buffer_end_access(shm); } +/* The serial alone, without the lock: the app asks on every pointer move, and the snapshot below + * copies up to 256 KB of pixels across JNI and holds the lock the compositor thread takes to + * change the cursor. A torn read is only a missed or an extra snapshot. */ +int banner_cursor_serial(void) { + return __atomic_load_n(&g_cursor_serial, __ATOMIC_RELAXED); +} + /* Read by the app (UI thread). out = [serial, hidden, w, h, hotspotX, hotspotY, pixels...]. * Returns the number of ints written, or 0 if out is too small. */ int banner_cursor_snapshot(int *out, int cap) { diff --git a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c index 10283f570b..414ca45b9d 100644 --- a/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c +++ b/app/src/main/cpp/waylandcomp/src/waylandcomp_jni.c @@ -6,6 +6,7 @@ */ #include #include +#include #include #include #include @@ -25,6 +26,7 @@ extern int banner_wayland_run(void); extern void banner_wayland_send_pointer(int action, int x, int y); extern void banner_wayland_send_touch(int action, int pointer_id, int x, int y); extern int banner_cursor_snapshot(int *out, int cap); +extern int banner_cursor_serial(void); extern void banner_wayland_send_key(int evdev, int state); extern void banner_wayland_send_scene_input(int type, int a, int b); extern void banner_wayland_vsync(int64_t frame_time_ns); @@ -294,6 +296,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot( return n; } +/* The serial nativeCursorSnapshot would return, without copying anything. */ +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) { + (void)env; (void)clazz; + return banner_cursor_serial(); +} + /* Inject a key event. evdev = Linux input keycode (KEY_A=30…); state 1=down 0=up. */ JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey( @@ -670,3 +679,29 @@ JNIEXPORT void JNICALL Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIEnv *env, jclass clazz, jint before, jint after) { banner_host_text_delete(before, after); } + +/* KGSL's power control, off (the GPU held at its top clock) or back on. The property is the + * device's, not this process's: it outlives the fd and the app, so the caller clears it at stop + * and again at every app start. No root; the kernel's thermal limits still apply. */ +extern void adrenotools_set_turbo(bool turbo); +JNIEXPORT void JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetGpuTurbo(JNIEnv *env, jclass clazz, jboolean on) { + (void)env; (void)clazz; + adrenotools_set_turbo(on == JNI_TRUE); +} + +/* Raises one of our own processes or threads to `nice` with a bare setpriority(), never lowering + * it. android.os.Process.setThreadPriority is not used for this: it also moves the thread between + * scheduling groups by priority, and a guest process must stay where Android put the app. Returns + * the nice value it is left at, or 100 when it could not be read. */ +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeRaisePriority(JNIEnv *env, jclass clazz, jint tid, jint nice) { + (void)env; (void)clazz; + errno = 0; + int before = getpriority(PRIO_PROCESS, (id_t)tid); + if (before == -1 && errno != 0) return 100; + if (before > nice) setpriority(PRIO_PROCESS, (id_t)tid, nice); + errno = 0; + int after = getpriority(PRIO_PROCESS, (id_t)tid); + return after == -1 && errno != 0 ? 100 : after; +} diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 19e13cc881..0a563ed036 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -3,10 +3,12 @@ package com.droiddeck.launcher import android.app.Application import com.droiddeck.launcher.runtime.BwrapSpawner import com.droiddeck.launcher.session.CrashHandler +import com.droiddeck.launcher.session.GpuClockPin /** * Process-wide setup: the crash handler, so a session's folder is finished even when we die, and - * the socket Flatpak's sandboxes are started through (BwrapSpawner). + * the GPU clock pin cleared in case a killed process left it set, and the socket Flatpak's + * sandboxes are started through (BwrapSpawner). */ class App : Application() { override fun onCreate() { @@ -14,6 +16,7 @@ class App : Application() { CrashHandler.install(this) // Before anything else touches the session prefs: a new install's first read decides it. com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this) + GpuClockPin.clearLeftover(this) BwrapSpawner.start(this) } } diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index a26d2097b2..c93a2b3888 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -135,6 +135,7 @@ class MainActivity : ComponentActivity() { private var zinkLazy by mutableStateOf(false) private var noXalia by mutableStateOf(true) private var gamescopeRealtime by mutableStateOf(false) + private var gpuClockPin by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false) private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME) private var phantomWarning by mutableStateOf(null) @@ -260,6 +261,7 @@ class MainActivity : ComponentActivity() { private var theme by mutableStateOf("graphite") private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO) private var hdrOn by mutableStateOf(false) + private var fpsLimit by mutableStateOf(0) private var hdrReason by mutableStateOf(null) private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) @@ -913,7 +915,7 @@ class MainActivity : ComponentActivity() { ModeSettingsPage( ModeSettings( mode = mode, resolutionCap = resolutionCap, customResolution = customResolution, shapeMode = shapeMode, - hdr = hdrOn, hdrReason = hdrReason, + hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, linuxRows = drivers.linuxRows, linuxSelected = if (mode == SessionService.MODE_STEAM) drivers.linuxSteam else drivers.linuxDesktop, androidRows = drivers.androidRows, androidSelected = drivers.androidSelected, @@ -949,6 +951,7 @@ class MainActivity : ComponentActivity() { onCustomResolution = { size -> SessionPrefs.setCustomResolution(this, mode, size); customResolution = size }, onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape }, onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, + onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps }, onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); drivers.refreshDrivers() }, onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) }, onRemoveLinux = { id -> drivers.deleteDriver(id, linux = true) }, @@ -1023,6 +1026,7 @@ class MainActivity : ComponentActivity() { clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, tuSysmem = tuSysmem, zinkLazy = zinkLazy, glThread = glThread, noGlError = noGlError, noXalia = noXalia, gamescopeRealtime = gamescopeRealtime, + gpuClockPin = gpuClockPin, prootNoSeccomp = prootNoSeccomp, guestHostname = guestHostname, phantomWarning = phantomWarning, onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on }, onTuSysmem = { on -> SessionPrefs.setTuSysmem(this, on); tuSysmem = on }, @@ -1031,6 +1035,7 @@ class MainActivity : ComponentActivity() { onNoGlError = { on -> SessionPrefs.setNoGlError(this, on); noGlError = on }, onNoXalia = { on -> SessionPrefs.setNoXalia(this, on); noXalia = on }, onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on }, + onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on }, onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on }, onGuestHostname = { name -> SessionPrefs.setGuestHostname(this, name) }, onClientCore = { core, on -> @@ -1083,6 +1088,7 @@ class MainActivity : ComponentActivity() { refreshAddedGames() shapeMode = SessionPrefs.shapeMode(this) hdrOn = SessionPrefs.hdr(this, mode) + fpsLimit = SessionPrefs.fpsLimit(this, mode) hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason touchMode = SessionPrefs.touchMode(this) suspendPolicy = SessionPrefs.suspendPolicy(this, mode) @@ -1128,6 +1134,7 @@ class MainActivity : ComponentActivity() { zinkLazy = SessionPrefs.zinkLazy(this) noXalia = SessionPrefs.noXalia(this) gamescopeRealtime = SessionPrefs.gamescopeRealtime(this) + gpuClockPin = SessionPrefs.gpuClockPin(this) prootNoSeccomp = SessionPrefs.prootNoSeccomp(this) guestHostname = SessionPrefs.guestHostname(this) refreshPhantomStatus() diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 9db297df2a..49160f70c4 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -191,7 +191,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private val displayListener = object : DisplayManager.DisplayListener { override fun onDisplayAdded(displayId: Int) = refreshSecondScreenDisplays() override fun onDisplayRemoved(displayId: Int) = refreshSecondScreenDisplays() - override fun onDisplayChanged(displayId: Int) = refreshSecondScreenDisplays() + override fun onDisplayChanged(displayId: Int) { + followPanelRefresh(displayId) + refreshSecondScreenDisplays() + } + } + + /** + * The panel's rate, followed for the rest of the session. It is read once at start, and a + * panel that drops from 120 to 60 Hz later (battery saver, heat, a vendor overriding the mode + * asked for) left the compositor telling gamescope every frame took 8.3 ms, so the client and + * its games paced against a vblank that no longer came. (WinNative 53836ca9.) + */ + private fun followPanelRefresh(displayId: Int) { + if (!CompositorHost.isStarted) return + val display = (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay) ?: return + if (display.displayId != displayId) return + val hz = display.refreshRate + if (hz > 1f) WaylandCompositor.nativeSetOutputRefreshRate(hz) } private var isHomeApp by mutableStateOf(false) private var androidApps by mutableStateOf>(emptyList()) @@ -220,9 +237,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { SessionEvents.record("agent.start_requested", mapOf("mode" to SessionState.mode)) } window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) - // Game-tier power policy for the whole session: the panel's fastest mode, and the OS told - // it is in gameplay. Logged so a slow device says why. - Log.i(TAG, "perf: " + PerfMode.apply(this)) + // Game-tier power policy for the whole session: the panel's fastest mode (one the frame cap + // divides, when there is a cap), and the OS told it is in gameplay. Logged so a slow device + // says why. The cap is the session's: an activity re-created mid-session keeps it. + if (!SessionState.running) { + SessionState.fpsLimit = SessionPrefs.fpsLimit( + this, SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM), + ) + } + Log.i(TAG, "perf: " + PerfMode.apply(this, SessionState.fpsLimit)) goFullscreen() // The device's volume keys change the stream the session plays on (the relay and // PulseAudio are media playback); they are never forwarded to the guest. @@ -785,7 +808,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { CompositorHost.startOrAttach( holder.surface, runtimeDir.path, driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, - applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), + applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(), SessionState.fpsLimit, ) if (!SessionState.running) SessionEvents.record("compositor.started") // The service owns everything below the compositor. It is started whenever no session is @@ -1291,6 +1314,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { */ private fun syncClientCursor(): Boolean { if (!CompositorHost.isStarted) return false + // Asked on every pointer move; the image is copied only when the client has changed it. + if (WaylandCompositor.nativeCursorSerial() == cursorSerial) return false val n = WaylandCompositor.nativeCursorSnapshot(cursorBuf) if (n < 6) return false val serial = cursorBuf[0] diff --git a/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt b/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt new file mode 100644 index 0000000000..8e0c7c8a02 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/GpuClockPin.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.wayland.WaylandCompositor +import java.io.File + +/** + * The GPU held at its top clock for a session, without root: KGSL's power-control property turned + * off on /dev/kgsl-3d0, the node the driver already opens (adrenotools' "turbo"). Left to itself the + * governor lets the GPU sit low between bursts, and a frame that lands on a low clock is a hitch; + * Bannerlator measured the clock going from 231 to 1000 MHz with this set. It costs power and heat, + * so it is opt-in, and the kernel's thermal limits still apply on top of it. + * + * The property belongs to the device, not to this process, and a killed app cannot unwind it: it + * is cleared when a session stops, and at the next app start when a marker file says this app set + * it and never cleared it - only then, so another app's own setting is not undone. + * (Bannerlator, PerfGpuTurbo.) + */ +object GpuClockPin { + private const val TAG = "GpuClockPin" + private const val KGSL_NODE = "/dev/kgsl-3d0" + + private const val MARKER = "gpu-clock-pinned" + + @Volatile + private var pinned = false + + private val supported: Boolean by lazy { File(KGSL_NODE).exists() } + + /** At a session's start: pins the clock when the user asked for it. The line is for the log. */ + @Synchronized + fun start(context: Context): String { + if (!SessionPrefs.gpuClockPin(context)) return "gpu clock: governed" + if (!supported) return "gpu clock: no $KGSL_NODE, left governed" + return try { + File(context.filesDir, MARKER).createNewFile() + WaylandCompositor.nativeSetGpuTurbo(true) + pinned = true + "gpu clock: held at its top" + } catch (t: Throwable) { + Log.w(TAG, "pin", t) + "gpu clock: pin failed" + } + } + + /** At a session's end. */ + @Synchronized + fun stop(context: Context) { + if (pinned) clear(context) + } + + /** At the app's start: a process killed with the clock pinned left only the marker behind. */ + @Synchronized + fun clearLeftover(context: Context) { + if (File(context.filesDir, MARKER).exists()) clear(context) + } + + private fun clear(context: Context) { + if (supported) { + try { + WaylandCompositor.nativeSetGpuTurbo(false) + } catch (t: Throwable) { + Log.w(TAG, "clear", t) + } + } + pinned = false + File(context.filesDir, MARKER).delete() + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt index 7e99840d5c..7a44423a00 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/PerfMode.kt @@ -17,7 +17,8 @@ import android.util.Log * Big Picture their peak clocks. WinNative never asks for it; the thermal budget is left to * the game; * - the panel's fastest mode at its current size (Android 6+): a 120 Hz phone is switched to - * 120 Hz for the menu, not only when a game votes for it; + * 120 Hz for the menu, not only when a game votes for it. With a frame cap, the fastest mode + * the cap divides evenly, so every capped frame is shown for the same number of refreshes; * - GameManager's game state (Android 13+): "in gameplay", so an OEM framework that releases * its boost on loading screens or menus keeps it up. * @@ -27,7 +28,7 @@ import android.util.Log object PerfMode { private const val TAG = "PerfMode" - fun apply(a: Activity): String { + fun apply(a: Activity, fpsLimit: Int = 0): String { val parts = ArrayList(2) // The fastest display mode at the panel's current size. @@ -35,10 +36,12 @@ object PerfMode { val display = if (Build.VERSION.SDK_INT >= 30) a.display else @Suppress("DEPRECATION") a.windowManager.defaultDisplay if (display == null || Build.VERSION.SDK_INT < 23) "display mode unchanged" else { val cur = display.mode - val best = display.supportedModes + val sameSize = display.supportedModes .filter { it.physicalWidth == cur.physicalWidth && it.physicalHeight == cur.physicalHeight } - .maxByOrNull { it.refreshRate } - if (best != null && best.modeId != cur.modeId && best.refreshRate > cur.refreshRate + 0.5f) { + val best = sameSize.filter { cadenceFits(it.refreshRate, fpsLimit) }.maxByOrNull { it.refreshRate } + ?: sameSize.maxByOrNull { it.refreshRate } + if (best != null && best.modeId != cur.modeId && + (best.refreshRate > cur.refreshRate + 0.5f || !cadenceFits(cur.refreshRate, fpsLimit))) { a.window.attributes = a.window.attributes.apply { preferredDisplayModeId = best.modeId } "display ${cur.refreshRate.toInt()} → ${best.refreshRate.toInt()} Hz (mode ${best.modeId})" } else "display ${cur.refreshRate.toInt()} Hz" @@ -64,4 +67,11 @@ object PerfMode { return parts.joinToString(" · ") } + + /** A panel rate that shows every capped frame for a whole number of refreshes (no cap: any). */ + fun cadenceFits(hz: Float, fpsLimit: Int): Boolean { + if (fpsLimit <= 0) return true + val ratio = hz / fpsLimit + return ratio >= 0.98f && Math.abs(ratio - Math.round(ratio)) < 0.02f + } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 4a0312cad0..5de5ede5aa 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -246,6 +246,13 @@ object SessionPrefs { * plainly exist is the signature - and the fallback is to trace everything instead: slower, * but correct. Max's advice for devices whose kernels "don't work well with it". */ + /** Hold the GPU at its top clock during a session (GpuClockPin). Off by default: power and heat. */ + fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false) + + fun setGpuClockPin(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("gpuClockPin", on).apply() + } + fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false) fun setProotNoSeccomp(context: Context, on: Boolean) { @@ -519,6 +526,22 @@ object SessionPrefs { prefs(context).edit().putBoolean("hdr.$mode", on).apply() } + /** + * The session's frame cap, 0 for none. One number used everywhere a frame is paced: gamescope's + * -r (what the client and its games see as the display's rate), the compositor's buffer release + * pacer, the rate the display layer votes for, and the panel mode picked, which is the fastest + * one the cap divides evenly (40 on a 120 Hz panel, not on a 144 Hz one). A 60 fps cap on a + * 144 Hz panel with nothing else changed judders; this is what WinNative's per-shortcut limit + * does. Applies next session. + */ + fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0) + + fun setFpsLimit(context: Context, mode: String, fps: Int) { + prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply() + } + + val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120") + /** * The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a * fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices. diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 9a5465bd63..88ea6e93e8 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -36,6 +36,7 @@ import com.droiddeck.launcher.core.HostProcess import com.droiddeck.launcher.input.FakeInputWriter import com.droiddeck.launcher.runtime.LinuxNetworkLinkComponent import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.wayland.WaylandCompositor import java.io.File import java.text.SimpleDateFormat import java.util.Date @@ -269,6 +270,8 @@ class SessionService : Service() { val sessionDir = openSessionFolder() val sessionLog = File(sessionDir, "session.log") + Log.i(TAG, GpuClockPin.start(this)) + val size = SessionState.outputSize val guest = ArrayList() // The desktop's Steam launchers start the client there (bannerlator-steam-launch), through the @@ -287,7 +290,7 @@ class SessionService : Service() { guest.add("DXVK_HDR=1") Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1") } - guest.add("BL_FPS=0") + guest.add("BL_FPS=" + SessionState.fpsLimit) guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz)) guest.add("BL_LOG=" + sessionLog.path) guest.add("BL_DEBUG_DIR=" + sessionDir.path) @@ -436,6 +439,7 @@ class SessionService : Service() { } sessionPid = pid if (pid > 1) { + raiseTracer(pid, gen) SessionEvents.guestStarted(pid) } else { SessionEvents.record("guest.start_failed", mapOf("pid" to pid)) @@ -528,6 +532,12 @@ class SessionService : Service() { // BL_STEAMDECK; it is the one that builds the command line). if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true") if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1") + // Mesa's shader cache as one database instead of a file per entry. Every lookup in the + // file cache is an open and every store an open and a rename, each a proot stop (a rename + // two), for every pipeline DXVK, vkd3d-proton and Zink compile or find; the database is + // opened once and read and written with pread/pwrite, which proot never sees. Mesa removes + // the old folder itself once it has gone a week untouched. + guest.add("MESA_DISK_CACHE_DATABASE=1") if (SessionState.mode == MODE_STEAM) guest.add("BL_STEAMDECK=" + (if (SessionPrefs.steamDeckMode(this)) "1" else "0")) if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0")) if (steamHere) guest.add("BL_STEAM_CHANNEL=" + SessionPrefs.steamChannel(this)) @@ -968,6 +978,31 @@ class SessionService : Service() { } } + /** + * proot is one thread, and every syscall it traps anywhere in the session - a path lookup in + * Proton's python, Wine's file opens, the Steam client's /proc scans - waits for that thread to + * be scheduled, at nice 0 beside a game that keeps the big cores busy. It is raised to nice -6, + * under the compositor's -8. After a moment, not at once: the first guest process is forked by + * proot itself and would inherit the value, and with it everything the session starts. + */ + private fun raiseTracer(pid: Int, gen: Int) { + Thread({ + try { + Thread.sleep(2000) + } catch (e: InterruptedException) { + return@Thread + } + if (gen != sessionGen || sessionPid != pid) return@Thread + val nice = try { + WaylandCompositor.nativeRaisePriority(pid, TRACER_NICE) + } catch (t: Throwable) { + Log.w(TAG, "tracer priority", t) + return@Thread + } + Log.i(TAG, "proot tracer $pid: nice $nice (asked for $TRACER_NICE)") + }, "tracer-priority").start() + } + private fun stopSession(status: Int) { synchronized(stopLock) { if (!SessionState.running) return @@ -976,6 +1011,7 @@ class SessionService : Service() { val stoppedGen = sessionGen SessionState.stopRequested = false SessionEvents.record("guest.exited", mapOf("status" to status)) + GpuClockPin.stop(this) SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status)) suspendOperationPending = false launchWatcher?.stopWatching() @@ -1152,6 +1188,8 @@ class SessionService : Service() { companion object { private const val TAG = "SessionService" + /** proot's tracer: above everything in the guest, under the compositor thread's -8. */ + private const val TRACER_NICE = -6 /** Downloads file whose contents become TU_DEBUG inside the session, e.g. "sysmem". */ private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug" /** Downloads file of KEY=VALUE lines added to the session environment verbatim. */ diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 71245d3fc0..e197a6f8bd 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -95,6 +95,10 @@ object SessionState { @Volatile var refreshHz: Float = 60f + /** The session's frame cap (SessionPrefs.fpsLimit), fixed when it starts; 0 = none. */ + @Volatile + var fpsLimit: Int = 0 + /** The compositor has presented a frame, so the loading panel is behind us for this session. */ @Volatile var firstFrameSeen = false diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index fc41cd81e9..3036b11fa7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -47,6 +47,8 @@ class ModeSettings( val shapeMode: String, val hdr: Boolean, val hdrReason: String?, + /** Frames per second the session is capped at; 0 = none. */ + val fpsLimit: Int = 0, val linuxRows: List, val linuxSelected: String, val androidRows: List, @@ -106,6 +108,7 @@ class ModeSettingsActions( val onCustomResolution: (Pair?) -> Unit = {}, val onShape: (String) -> Unit, val onHdr: (Boolean) -> Unit, + val onFpsLimit: (Int) -> Unit = {}, val onSelectLinux: (String) -> Unit, val onImportLinux: () -> Unit, val onRemoveLinux: (String) -> Unit, @@ -220,6 +223,12 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { if (custom != null) "Set by the custom resolution." else "Auto uses at least 16:9.", com.droiddeck.launcher.session.SessionPrefs.shapeChoices, s.shapeMode, enabled = custom == null, onPick = a.onShape, ) + ChoiceRow( + host, "fps", "Frame limit", "Applies next session.", + com.droiddeck.launcher.session.SessionPrefs.fpsLimitChoices, s.fpsLimit, + note = "Caps the whole session. The screen switches to a rate the cap divides evenly.", + onPick = a.onFpsLimit, + ) if (editCustom) CustomResolutionDialog( initial = custom, onSave = { size -> editCustom = false; a.onCustomResolution(size) }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt index 1083babe2f..fb441ef06d 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt @@ -38,6 +38,7 @@ fun PerformancePage( noGlError: Boolean, noXalia: Boolean, gamescopeRealtime: Boolean, + gpuClockPin: Boolean, prootNoSeccomp: Boolean, guestHostname: String, phantomWarning: String?, @@ -48,6 +49,7 @@ fun PerformancePage( onNoGlError: (Boolean) -> Unit, onNoXalia: (Boolean) -> Unit, onGamescopeRealtime: (Boolean) -> Unit, + onGpuClockPin: (Boolean) -> Unit, onProotNoSeccomp: (Boolean) -> Unit, onGuestHostname: (String) -> Unit, onClientCore: (Int, Boolean) -> Unit, @@ -102,6 +104,13 @@ fun PerformancePage( gamescopeRealtime, onChange = onGamescopeRealtime, ) } + SettingsGroup("GPU") { + ToggleRow( + host, "gpuclock", "Hold the GPU at its top clock", + "Adreno only. Fewer hitches from the clock ramping up, at the cost of battery and heat. Released when the session ends.", + gpuClockPin, onChange = onGpuClockPin, + ) + } SettingsGroup("Session fixes") { ToggleRow( host, "sysmem", "Turnip: sysmem rendering", diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index 8e9fd35c71..a19bd858a6 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -32,7 +32,9 @@ object CompositorHost { outputWidth: Int, outputHeight: Int, refreshHz: Float, + fpsLimit: Int, ): Boolean { + pace(refreshHz, fpsLimit) if (started) { attached = surface WaylandCompositor.nativeSetSurface(surface) @@ -41,10 +43,6 @@ object CompositorHost { } WaylandCompositor.nativeSetOutputSize(outputWidth, outputHeight) WaylandCompositor.nativeSetOutputRefreshRate(refreshHz) - // The cadence the zero-copy layer votes for. Left at 0 the system infers it from the rate - // already being achieved, and on a phone whose vendor picks clocks from that a session - // that has been slowed reads as one that wants to be. (WinNative, WaylandSession.) - WaylandCompositor.nativeSetLayerFrameRate(refreshHz) WaylandCompositor.nativeStartWithSurface( surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir, ) @@ -54,6 +52,19 @@ object CompositorHost { return true } + /** + * The session's frame cap, on every attach: the compositor outlives sessions, and the next one + * may have a different cap. The release pacer hands a game one buffer back per capped frame + * (per refresh without a cap), and the zero-copy layer votes for the same cadence. Left at 0 + * the vote is inferred from the rate already being achieved, and on a phone whose vendor picks + * clocks from that a session that has been slowed reads as one that wants to be. (WinNative, + * WaylandSession.) + */ + private fun pace(refreshHz: Float, fpsLimit: Int) { + WaylandCompositor.nativeSetFpsLimit(fpsLimit) + WaylandCompositor.nativeSetLayerFrameRate(if (fpsLimit > 0) fpsLimit.toFloat() else refreshHz) + } + /** * The Surface changed size under the compositor (a foldable opening or closing). Android does * not always recreate the Surface for that, and a swapchain built for the old size keeps diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java index 9b7fda7311..71c7172a0a 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java +++ b/app/src/main/java/com/droiddeck/launcher/wayland/WaylandCompositor.java @@ -207,6 +207,9 @@ public final class WaylandCompositor { */ public static native int nativeCursorSnapshot(int[] out); + /** The serial {@link #nativeCursorSnapshot} would report, without copying the image. */ + public static native int nativeCursorSerial(); + /** Enough for the header plus a 256x256 cursor, the largest the compositor snapshots. */ public static final int CURSOR_BUF_INTS = 6 + 256 * 256; @@ -434,6 +437,14 @@ public final class WaylandCompositor { * back to the game, like the X11 IdleNotify pacer, so the game itself slows to the cap. */ public static native void nativeSetFpsLimit(int fps); + /** KGSL power control off (true: the GPU held at its top clock) or back on. Device-wide and + * outlives the process; see {@code GpuClockPin}. A no-op without /dev/kgsl-3d0. */ + public static native void nativeSetGpuTurbo(boolean on); + + /** setpriority() on one of our own processes or threads, only ever raising it (no cgroup move, + * unlike android.os.Process.setThreadPriority). Returns the nice it is left at; 100 = unknown. */ + public static native int nativeRaisePriority(int tid, int nice); + /** Inject the app's X-server input in scene (virtual desktop) pixels. type 2 = move to a,b; * 3 = evdev button a (BTN_LEFT=0x110…) pressed (b=1) or released (b=0); 4 = a wheel steps, * negative = up. */ diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists b/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists index 9d2d60fa72..61c8d35a62 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-seed-redists @@ -1,5 +1,6 @@ #!/bin/bash -# Marks Steam's shared redistributables as already run in every Proton prefix. +# Marks Steam's shared redistributables as already run in every Proton prefix, and in the +# template Proton makes new prefixes from. # # A game whose depot lists _CommonRedist makes the client run the real installer inside the # prefix on first launch. Those are x86 bundles, so they run under FEX, and the 2019 one leaves @@ -14,27 +15,15 @@ set -u steam_root=${1:?steam root} redist="$steam_root/steamapps/common/Steamworks Shared/_CommonRedist" -[ -d "$redist" ] || exit 0 -# Every process an install script would run becomes the registry value the client writes once it -# has run it. Names sit one level inside "Run Process", the key they share a level further in. -block=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | xargs -0 -r awk -v now="$(date +%s)" ' - function emit(key, name, path) { - path = key - sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path) - if (path == key) - return - printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, name - # The client writes these from 32-bit steam.exe, so its own copy lands under Wow6432Node; - # both spellings are seeded because the reader picks by its own word size. - sub(/^Software\\\\/, "Software\\\\\\\\Wow6432Node\\\\\\\\", path) - printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, name - } +# Every process an install script would run, as the registry key and value the client writes once +# it has run it. Names sit one level inside "Run Process", the key they share a level further in. +pairs=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | xargs -0 -r awk ' FNR == 1 { depth = 0; name = ""; key = "" } /^[[:space:]]*\{/ { depth++; next } /^[[:space:]]*\}/ { if (depth == 3 && name != "" && key != "") - emit(key, name) + printf "%s\t%s\n", key, name depth-- next } @@ -44,15 +33,62 @@ block=$(find "$redist" -name installscript.vdf -print0 2>/dev/null | sort -z | x if (n >= 3 && depth == 2) { name = part[2]; key = "" } } ') -[ -n "$block" ] || exit 0 -stamp=$(printf '%s' "$block" | cksum) +# The client downloads the scripts with the first game that wants them, which is too late for that +# game; until then the set they held when this was written stands in. (WinNative's list.) +[ -n "$pairs" ] || pairs=$(sed 's/^\([^ ]*\) /HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\\1\t/' <<'KNOWN' +DirectX\\Jun2010 dxsetup +.NET\\4.8 4.8 +vcredist\\2008 x86 SP1 +vcredist\\2008 x64 SP1 +vcredist\\2010 x86 +vcredist\\2010 x64 +vcredist\\2013 x86 12.0.30501 +vcredist\\2013 x64 12.0.30501 +vcredist\\2015 x86 Update 3 14.0.24215.0 +vcredist\\2015 x64 Update 3 14.0.24215.0 +vcredist\\2017 x86 14.10.25008.0 +vcredist\\2017 x64 14.10.25008.0 +vcredist\\2019 x86 14.28.29334.0 +vcredist\\2019 x64 14.28.29334.0 +vcredist\\2022 x86 14.51.36247.0 +vcredist\\2022 x64 14.51.36247.0 +KNOWN +) +# The stamp is the set of names, taken before the block below dates its keys: stamped from the +# dated block it never matched, and every prefix had the whole block appended again on every beat. +stamp=$(printf '%s' "$pairs" | cksum) -for reg in "$steam_root"/steamapps/compatdata/*/pfx/system.reg \ +block=$(printf '%s\n' "$pairs" | awk -F'\t' -v now="$(date +%s)" ' + { + path = $1 + sub(/^HKEY_LOCAL_MACHINE\\\\/, "", path) + if (path == $1) + next + printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2 + # The client writes these from 32-bit steam.exe, so its own copy lands under Wow6432Node; + # both spellings are seeded because the reader picks by its own word size. + sub(/^Software\\\\/, "Software\\\\\\\\Wow6432Node\\\\\\\\", path) + printf "\n[%s] %d\n\"%s\"=dword:00000001\n", path, now, $2 + } +') +[ -n "$block" ] || exit 0 + +# Proton builds a new prefix from its template, and the client runs the install scripts in that +# prefix moments later, so the template carries the markers too. Its date is kept: Proton reads a +# changed one as a new template and upgrades every prefix made from the old. +for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \ + "$steam_root"/compatibilitytools.d/*/files/share/default_pfx*/system.reg \ + "$steam_root"/steamapps/compatdata/*/pfx/system.reg \ /mnt/bannerlator-sd/steamapps/compatdata/*/pfx/system.reg; do [ -f "$reg" ] || continue seeded=$(dirname "$reg")/.bannerlator-redists [ "$(cat "$seeded" 2>/dev/null)" = "$stamp" ] && continue - printf '%s\n' "$block" >>"$reg" || continue - printf '%s\n' "$stamp" >"$seeded" - echo "== seeded redist markers into $reg" + dated=$(mktemp) || continue + touch -r "$reg" "$dated" + if printf '%s\n' "$block" >>"$reg"; then + printf '%s\n' "$stamp" >"$seeded" + echo "== seeded redist markers into $reg" + fi + touch -r "$dated" "$reg" + rm -f "$dated" done diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session index 39370ce73e..f3b40af88f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session @@ -273,13 +273,24 @@ case $mode in # device it took 5 of 8, leaving out both little cores and the fastest one - which is a # reasonable thing to do while a game is running and the wrong thing when the client is all # there is. BL_CLIENT_CPUS overrides it. Re-applied on a beat because steamwebhelper spawns - # children continuously and each one inherits Steam's choice, not ours. + # children continuously and each one inherits Steam's choice, not ours. The beat reads /proc + # itself instead of running pgrep, and only runs taskset for a process that is new or has + # grown threads since it was last pinned: every fork is a round of traced syscalls, and a + # beat that forked a taskset per process every 5 s did that for an hour. taskset -a, because + # without it only a process's main thread moves and the renderer's workers stay where they were. if [ -n "${BL_CLIENT_CPUS:-}" ]; then step "client cores: $BL_CLIENT_CPUS" ( - for _ in $(seq 1 720); do - for _p in $(pgrep -f 'steamwebhelper|steamrtarm64/steam|gamescope' 2>/dev/null); do - taskset -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true + declare -A _bl_pinned=() + for ((_i = 0; _i < 720; _i++)); do + for _d in /proc/[0-9]*; do + IFS= read -r -d '' _c < "$_d/cmdline" 2>/dev/null || continue + case $_c in *steamwebhelper*|*steamrtarm64/steam|*gamescope*) ;; *) continue ;; esac + _t=("$_d"/task/*) + _p=${_d#/proc/} + [ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && continue + taskset -a -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true + _bl_pinned[$_p]=${#_t[@]} done nap 5 done @@ -420,13 +431,33 @@ case $mode in prev=$app done ) & + # The library beat. Both helpers are whole programs under proot (the compat one a python + # start and a parse of the client's config), and nearly every beat has nothing new for them. + # The seeder marks Proton's prefix template as well as the prefixes, so a new prefix is born + # marked and every 15 s is soon enough for the rest. The compat pass runs when a directory it + # reads from has changed since its last run - a new manifest, a new depot or tool, the client + # rewriting config.vdf - which [ -nt ] answers without starting anything, and once a minute + # regardless. ( beat=0 - for _ in $(seq 1 720); do + compat_stamp=$HOME/.bl-compat-beat + rm -f "$compat_stamp" + compat_due() { + local d + [ -e "$compat_stamp" ] && [ "$((beat % 12))" -ne 0 ] || return 0 + for d in "$steam_root/steamapps" "$steam_root/steamapps/common" "$steam_root/config" \ + "$steam_root/compatibilitytools.d" /mnt/bannerlator-sd/steamapps; do + [ "$d" -nt "$compat_stamp" ] && return 0 + done + return 1 + } + for ((_i = 0; _i < 720; _i++)); do nap 5 - bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true beat=$((beat + 1)) - if [ "$((beat % 3))" -eq 0 ]; then + [ "$((beat % 3))" -eq 0 ] || continue + bannerlator-seed-redists "$steam_root" >/dev/null 2>&1 || true + if compat_due; then + : > "$compat_stamp" bannerlator-steam-compat "$steam_root" >/dev/null 2>&1 || true fi done diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat index 28bb1f89d3..fb70b40e23 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-compat @@ -152,6 +152,9 @@ bl_game_cpus() { # container that path never reaches Proton either. (WinNative's winnative-proton-launch.) BL_LIBPATH_SETUP = """ bl_libpath() { + # A Proton built to prefer PipeWire (CachyOS's among the adopted ones) hung its audio thread + # here, where only PulseAudio answers. (WinNative, winnative-proton-launch.) + export PROTON_USE_PIPEWIRE=${PROTON_USE_PIPEWIRE:-0} [ -n "${LD_LIBRARY_PATH:-}" ] || return 0 local kept= dir old_ifs=$IFS IFS=: @@ -246,17 +249,29 @@ if [ -f "$fake" ]; then *) LD_PRELOAD="$fake${LD_PRELOAD:+:$LD_PRELOAD}"; export LD_PRELOAD ;; esac fi +# The newest of the ARM64 depots the client has, by the build number that opens each one's version +# file: taking the first one found ran a stale Experimental over a newer 11.0. (WinNative.) +depot= +best=0 for name in %s; do - depot="$steam_root/steamapps/common/$name" - if [ -d "$depot/files/bin-arm64" ] && [ -x "$depot/proton" ]; then - bl_components "$depot" - bl_directaudio "$depot" - bl_game_cpus - bl_idtech3 "$@" - bl_libpath - exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" + candidate="$steam_root/steamapps/common/$name" + [ -d "$candidate/files/bin-arm64" ] && [ -x "$candidate/proton" ] || continue + build=0 + read -r build _ 2>/dev/null < "$candidate/version" + case $build in "" | *[!0-9]*) build=0 ;; esac + if [ -z "$depot" ] || [ "$build" -gt "$best" ]; then + depot=$candidate + best=$build fi done +if [ -n "$depot" ]; then + bl_components "$depot" + bl_directaudio "$depot" + bl_game_cpus + bl_idtech3 "$@" + bl_libpath + exec ${BL_TASKSET:-} /usr/local/bin/bannerlator-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" +fi echo "bannerlator-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2 exit 1 """ % " ".join('"%s"' % n for n in SOURCES) @@ -568,15 +583,23 @@ def register_default(config_path, apps=(), name=None, protect=()): write_changed(config_path, text) +def depot_build(depot): + """The build number a depot's version file starts with; 0 when there is none.""" + try: + with open(os.path.join(depot, "version"), encoding="utf-8", errors="replace") as f: + first = f.read().split(None, 1) + except OSError: + return 0 + return int(first[0]) if first and first[0].isdigit() else 0 + + def find_source(steam_root): - """The ARM64 Proton depot the client has downloaded, or None.""" + """The newest ARM64 Proton depot the client has downloaded (the one the launcher runs), or None.""" common = os.path.join(steam_root, "steamapps", "common") - for name in SOURCES: - depot = os.path.join(common, name) - # bin-arm64 is what makes it the native build rather than the x86_64 one. - if os.path.isdir(os.path.join(depot, "files", "bin-arm64")): - return depot - return None + # bin-arm64 is what makes it the native build rather than the x86_64 one. + found = [os.path.join(common, name) for name in SOURCES + if os.path.isdir(os.path.join(common, name, "files", "bin-arm64"))] + return max(found, key=depot_build) if found else None def build_tool(tool_dir): diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games index 3ab3e98444..1c2add014a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-games @@ -128,6 +128,22 @@ def probe(steam_root, ids): method(client, 1, C.c_bool, C.c_int)(client, pipe) +def game_running(): + """Whether a Proton game is up: a wineserver is there for as long as any prefix is in use.""" + try: + pids = [p for p in os.listdir("/proc") if p.isdigit()] + except OSError: + return False + for pid in pids: + try: + with open("/proc/%s/comm" % pid) as f: + if f.read().strip() == "wineserver": + return True + except OSError: + pass + return False + + def watch(steam_root, listing): games = read_json(listing, []) if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games: @@ -138,7 +154,10 @@ def watch(steam_root, listing): # The probe is a fresh python that loads steamclient.so, seconds of CPU under proot. Ownership # only moves with a purchase or a new match, so it runs when the matches or their sources # change, after a failed probe, and otherwise every five minutes - not on every 30 s beat. - probed, next_probe = None, 0 + # A failed probe is retried on a doubling delay up to those five minutes rather than on every + # beat (a client that is not logged on fails it for as long as it stays that way), and none + # starts while a game is running: the answer can wait, the game's cores cannot. + probed, next_probe, failures = None, 0, 0 while True: now = time.monotonic() for game in games: @@ -155,7 +174,9 @@ def watch(steam_root, listing): next_lookup = now + 300 status = "waiting for a matching Steam title" key = (dict(candidates), dict(sources)) - if candidates and (key != probed or now >= next_probe): + if candidates and (key != probed or now >= next_probe) and game_running(): + status = last_status + elif candidates and (key != probed or now >= next_probe): probed, next_probe = key, now + 300 try: result = subprocess.run([sys.executable, __file__, "probe", steam_root, @@ -163,8 +184,10 @@ def watch(steam_root, listing): capture_output=True, text=True, timeout=15) if result.returncode != 0: status = "ownership probe failed: " + (result.stderr.strip()[-300:] or str(result.returncode)) - probed = None + failures += 1 + next_probe = now + min(300, 30 * 2 ** failures) else: + failures = 0 line = next(line for line in result.stdout.splitlines() if line.startswith("DROIDDECK_OWNERSHIP=")) snapshot = json.loads(line.removeprefix("DROIDDECK_OWNERSHIP=")) if not snapshot["account"].isdigit() or int(snapshot["account"]) <= 0: @@ -175,7 +198,8 @@ def watch(steam_root, listing): status = "matched %d/%d games; %d owned" % (len(candidates), len(games), sum(snapshot["owned"].values())) except (OSError, ValueError, KeyError, StopIteration, subprocess.TimeoutExpired) as error: status = "ownership check unavailable: " + str(error) - probed = None + failures += 1 + next_probe = now + min(300, 30 * 2 ** failures) elif candidates: status = last_status if status != last_status: diff --git a/tools/linuxfs/preload/kgslpoll.c b/tools/linuxfs/preload/kgslpoll.c new file mode 100644 index 0000000000..00eb8f01f3 --- /dev/null +++ b/tools/linuxfs/preload/kgslpoll.c @@ -0,0 +1,79 @@ +/* + * A zero-timeout KGSL timestamp wait answered as the poll it was meant to be. + * + * Turnip's KGSL backend emulates timeline semaphores with timestamps, and asks "has this one + * retired yet?" by waiting on it with IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID and a timeout of 0. + * KGSL reads a timeout of 0 as no timeout at all, so the poll blocks until the GPU gets there. + * Mesa's timeline bookkeeping polls like that under a lock on every signalling submit, which put + * vkd3d-proton, DXVK, gamescope and Zink in lock-step with the GPU: one frame queued, never two. + * Found and measured by Bannerlator (PROGRESS_LOG 2026-09-29: a D3D12 demo went from 614 to + * 4335 fps with the same answer given in its Vulkan adapter); the driver-side fix is on + * Banners-Turnip, and this covers the drivers that do not carry it yet. + * + * The answer comes from the context's retired timestamp, compared the way KGSL compares them + * (with wrap-around). Anything the read does not answer - an unknown context, a device that is not + * KGSL - goes to the kernel as before. BL_NO_KGSL_POLL_FIX=1 turns it off. + */ +#define _GNU_SOURCE +#include +#include +#include +#include + +#define KGSL_IOC_TYPE 0x09 +#define KGSL_TIMESTAMP_RETIRED 0x00000002 + +struct kgsl_device_waittimestamp_ctxtid { + unsigned int context_id; + unsigned int timestamp; + unsigned int timeout; +}; + +struct kgsl_cmdstream_readtimestamp_ctxtid { + unsigned int context_id; + unsigned int type; + unsigned int timestamp; +}; + +#define IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID \ + _IOW(KGSL_IOC_TYPE, 0x7, struct kgsl_device_waittimestamp_ctxtid) +#define IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID \ + _IOWR(KGSL_IOC_TYPE, 0x16, struct kgsl_cmdstream_readtimestamp_ctxtid) + +static int enabled(void) { + static int cached = -1; + const char *off; + + if (cached >= 0) return cached; + off = getenv("BL_NO_KGSL_POLL_FIX"); + cached = !(off != NULL && off[0] == '1'); + return cached; +} + +/* True when the call was answered here, with its result in *rc (and errno set on failure). */ +__attribute__((visibility("hidden"))) int bl_kgsl_poll(int (*real)(int, unsigned long, void *), + int fd, unsigned long request, void *arg, + int *rc) { + const struct kgsl_device_waittimestamp_ctxtid *wait = arg; + struct kgsl_cmdstream_readtimestamp_ctxtid read; + int saved = errno; + + if (request != IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID || arg == NULL || wait->timeout != 0 || + !enabled()) + return 0; + read.context_id = wait->context_id; + read.type = KGSL_TIMESTAMP_RETIRED; + read.timestamp = 0; + if (real(fd, IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &read) != 0) { + errno = saved; + return 0; + } + if ((int32_t)(read.timestamp - wait->timestamp) >= 0) { + errno = saved; + *rc = 0; + } else { + errno = ETIMEDOUT; + *rc = -1; + } + return 1; +} diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index 4b79c3f3f9..a835c6cddb 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -349,6 +349,9 @@ static int is_link_query(unsigned long request) { || request == SIOCGIFBRDADDR; } +int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request, + void *arg, int *rc) __attribute__((visibility("hidden"))); + /* Every DRM and evdev call comes through here, so the lookup is done once. Two threads racing * to store it store the same pointer. */ int ioctl(int fd, unsigned long request, ...) { @@ -360,7 +363,9 @@ int ioctl(int fd, unsigned long request, ...) { va_end(ap); if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl"); - int rc = real(fd, request, arg); + int rc; + if (bl_kgsl_poll(real, fd, request, arg, &rc)) return rc; + rc = real(fd, request, arg); if (arg == NULL || !is_link_query(request)) return rc; int saved = errno; if (answer_ifreq(request, (struct ifreq *) arg, rc)) return 0;