feat: feed the overlay's fan, GPU memory and Valve msm reader paths

This commit is contained in:
xXJsonDeruloXx committed 2026-10-01 13:28:26 -04:00
1 parent e4a5bf45b9
commit a3fafcb10e
9 files changed
+467 -40

No files matched your search

@@ -239,9 +239,8 @@ public final class LinuxRuntime {
}
}
bindGpuNode(context, cmd);
bindAdrenoStats(cmd);
bindAdrenoStats(cmd, extraBinds);
bindCpuTemps(cmd, root);
bindCpuHwmon(context.getCacheDir(), cmd);
if (extraBinds != null) {
for (String spec : extraBinds) bind(cmd, spec);
}
@@ -333,36 +332,13 @@ public final class LinuxRuntime {
}
}
/**
* MangoHud's CPU temperature: it looks first in {@code /sys/class/hwmon} for a sensor named
* {@code cpuN_thermal} (a mainline Arm kernel's), then at thermal zones of a type it knows; an
* Android kernel has neither - its hwmon holds the PMIC's sensors and its zones are named by
* the vendor (cpu-1-0-usr) - so the overlay showed no CPU temperature, and where the app may
* not list hwmon the overlay logged an error twice a second. The session's hwmon is one sensor
* named so, reading a CPU zone the app can read. Nothing else in a phone's hwmon is read by it.
*/
private static void bindCpuHwmon(File cacheDir, List<String> cmd) {
String zone = null;
/** The temperature of a CPU zone the app may read (the first by name), or null. */
public static String cpuTempSource() {
for (java.util.Map.Entry<String, File> e : new java.util.TreeMap<>(thermalZones()).entrySet()) {
File temp = new File(e.getValue(), "temp");
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) {
zone = temp.getPath();
break;
}
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath();
}
if (zone == null) return;
File sensor = new File(cacheDir, "hwmon/hwmon0");
try {
if (!sensor.isDirectory() && !sensor.mkdirs()) return;
Files.write(new File(sensor, "name").toPath(), "cpu0_thermal\n".getBytes(StandardCharsets.US_ASCII));
File input = new File(sensor, "temp1_input");
Files.deleteIfExists(input.toPath());
Os.symlink(zone, input.getPath());
} catch (IOException | ErrnoException e) {
return;
}
bind(cmd, sensor.getParent() + ":/sys/class/hwmon");
android.util.Log.i("LinuxRuntime", "hud: cpu temp from " + zone);
return null;
}
/** The file the GPU's temperature reads from, or null where the app may read none. */
@@ -384,7 +360,7 @@ public final class LinuxRuntime {
* Android PC emulators (GameNative, Winlator forks) read them in. A value found nowhere is left
* alone.
*/
private static void bindAdrenoStats(List<String> cmd) {
private static void bindAdrenoStats(List<String> cmd, List<String> extraBinds) {
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
String gpuTemp = gpuTempSource();
String[][] stats = {
@@ -396,7 +372,10 @@ public final class LinuxRuntime {
{thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
};
for (String[] stat : stats) {
if (stat[0] != null) bind(cmd, stat[0] + ":" + stat[1]);
// A value the session feeds itself (GpuStatsComponent, where KGSL is refused) wins.
boolean fed = false;
if (extraBinds != null) for (String spec : extraBinds) fed |= spec.endsWith(":" + stat[1]);
if (stat[0] != null && !fed) bind(cmd, stat[0] + ":" + stat[1]);
}
// Which of the overlay's GPU values this device lets the app read: a phone under an
// enforcing policy refuses some of them, and the overlay then has no line for that value.
@@ -0,0 +1,115 @@
package com.droiddeck.launcher.session
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import java.io.File
/**
* The GPU memory in use, for the performance overlay's VRAM and PVRAM lines.
*
* Valve's mangoapp reads it from the kernel's gpu_mem_total tracepoint, which no Android app may
* reach, so both lines read 0. Our libtracefs for mangoapp (tools/mangoapp/libtracefs-shim.c) hands
* it what this writes to [file] - `/run/droiddeck-hud/gpu-mem` in the guest - every few seconds, in
* bytes, from the best of what KGSL lets the app read:
*
* - `/sys/class/kgsl/kgsl/page_alloc`, every GPU page on the device - what the tracepoint's total
* counts, where the policy allows it;
* - else KGSL's own accounting of each of the session's processes
* (`/sys/class/kgsl/kgsl/proc/<pid>/gpumem_mapped` and `gpumem_unmapped`);
* - else the size of the KGSL mappings in each of the session's processes' `smaps` - only the
* buffers the CPU has mapped, so less than the GPU holds (about 40 % of KGSL's own count in a
* game on an AYN Thor), but always readable: every process the app can see in `/proc` is one of
* its own.
*/
class GpuMemComponent(private val file: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private var source = ""
/** True when there is a source to write from. */
fun prepare(): Boolean {
val bytes = sample() ?: return false
write(bytes)
Log.i(TAG, "hud: gpu memory from $source (${bytes / (1024 * 1024)} MiB now)")
return true
}
override fun start() {
running = true
thread = Thread({
while (running) {
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
if (running) sample()?.let { write(it) }
}
}, "gpu-mem").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
file.delete()
}
private fun sample(): Long? {
readLong("$KGSL_ROOT/page_alloc")?.let { source = "$KGSL_ROOT/page_alloc"; return it }
val pids = sessionPids()
var perProcess = 0L
var anyProcess = false
for (pid in pids) {
val mapped = readLong("$KGSL_ROOT/proc/$pid/gpumem_mapped") ?: continue
perProcess += mapped + (readLong("$KGSL_ROOT/proc/$pid/gpumem_unmapped") ?: 0L)
anyProcess = true
}
if (anyProcess) { source = "$KGSL_ROOT/proc/<pid>/gpumem_*"; return perProcess }
var mappedKb = 0L
var anyMap = false
for (pid in pids) {
val kb = kgslMappedKb(pid) ?: continue
mappedKb += kb
anyMap = true
}
if (anyMap) { source = "/proc/<pid>/smaps (KGSL mappings)"; return mappedKb * 1024 }
return null
}
/** The processes this app may see in /proc: Android hides every other uid's. */
private fun sessionPids(): List<String> =
File("/proc").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) }.orEmpty()
/** Size of a process's mappings of the KGSL device, in kB; null where its smaps cannot be read. */
private fun kgslMappedKb(pid: String): Long? = runCatching {
var total = 0L
var inKgsl = false
File("/proc/$pid/smaps").forEachLine { line ->
if (MAPPING.containsMatchIn(line)) {
inKgsl = line.contains("kgsl-3d0") || line.contains("/dev/dri/renderD")
} else if (inKgsl && line.startsWith("Size:")) {
total += line.substring(5).trim().removeSuffix("kB").trim().toLongOrNull() ?: 0L
}
}
total
}.getOrNull()
/** Whole, renamed into place: the reader opens either the last value or this one. */
private fun write(bytes: Long) {
try {
file.parentFile?.mkdirs()
val tmp = File(file.parentFile, file.name + ".tmp")
tmp.writeText("$bytes\n")
if (!tmp.renameTo(file)) tmp.delete()
} catch (e: Exception) {
}
}
companion object {
private const val TAG = "SessionService"
private const val KGSL_ROOT = "/sys/class/kgsl/kgsl"
private const val PERIOD_MS = 2_000L
/** A mapping's header in smaps: its address range first, then its fields and path. */
private val MAPPING = Regex("^[0-9a-f]+-[0-9a-f]+ ")
private fun readLong(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()
}
}
@@ -19,6 +19,11 @@ import java.io.RandomAccessFile
* Adreno's numbers from, across Snapdragon generations and vendor kernels. A value with no
* readable source is left out, and the overlay shows no line for it. Where all three are
* readable, nothing is done.
*
* Valve's build also reads load and clock where a mainline msm kernel has them (debugfs
* `perf_now`, the GPU's devfreq `cur_freq` in Hz) - the paths LinuxRuntime.bindAdrenoStats points
* at KGSL's own files when it may - so the same values are fed there too, in the same formats
* ([binds]).
*/
class GpuStatsComponent(val dir: File) : SessionPart() {
@Volatile private var running = false
@@ -26,7 +31,17 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
private val feeds = ArrayList<Feed>()
/** One of MangoHud's files and where its value comes from. */
private class Feed(val file: File, val source: String, val read: () -> Long?, val format: String)
private class Feed(
val file: File, val source: String, val read: () -> Long?, val format: String, val percent: Boolean = false,
)
/** Where Valve's msm reader looks, and the feed for it, as host:guest binds. */
fun binds(): List<String> {
val list = mutableListOf(dir.path + ":" + KGSL)
if (File(dir, "perf_now").exists()) list.add(File(dir, "perf_now").path + ":" + MSM_LOAD)
if (File(dir, "cur_freq").exists()) list.add(File(dir, "cur_freq").path + ":" + MSM_CLOCK)
return list
}
/** Writes the directory; true when it should be bound over [KGSL]. */
fun prepare(): Boolean {
@@ -35,8 +50,16 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
dir.mkdirs()
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
feeds.clear()
loadFeed()?.let { feeds.add(it) }
pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { feeds.add(it) }
loadFeed()?.let { load ->
feeds.add(load)
// KGSL's gpu_busy_percentage reads "37 %"; padded after, so a shorter value
// written over a longer one leaves no digits behind.
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
}
pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { clock ->
feeds.add(clock)
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
}
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
feeds.forEach { feed -> feed.read()?.let { write(feed, it) } }
Log.i(TAG, "hud: kgsl stats from the session's own: " + MANGOHUD_FILES.joinToString { name ->
@@ -93,7 +116,8 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
private fun write(feed: Feed, value: Long) {
try {
RandomAccessFile(feed.file, "rw").use { it.seek(0); it.write(String.format(feed.format, value).toByteArray()) }
val text = if (feed.percent) String.format(feed.format, "$value %") else String.format(feed.format, value)
RandomAccessFile(feed.file, "rw").use { it.seek(0); it.write(text.toByteArray()) }
} catch (e: Exception) {
}
}
@@ -101,6 +125,9 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
companion object {
private const val TAG = "SessionService"
const val KGSL = "/sys/class/kgsl/kgsl-3d0"
/** Must match LinuxRuntime.bindAdrenoStats. */
const val MSM_LOAD = "/sys/kernel/debug/dri/0/perf_now"
const val MSM_CLOCK = "/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"
private const val PERIOD_MS = 500L
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
/** Qualcomm's own GPU summary, beside KGSL in vendor kernels, under the plain sysfs label. */
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.session
import android.os.SystemClock
import android.system.Os
import android.util.Log
import com.droiddeck.launcher.core.SessionPart
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
/**
* The session's `/sys/class/hwmon`, as mangoapp (Deck mode's performance overlay) looks there.
*
* MangoHud finds a CPU's temperature by an hwmon sensor named `cpuN_thermal`, and an Adreno's
* temperature, fan and power by one whose name has `gpuss` in it - a mainline Arm kernel's names.
* An Android kernel has neither (its hwmon holds the PMIC's sensors, or nothing), and where the
* app may not list hwmon at all the overlay logged an error twice a second. So the overlay showed
* no CPU temperature and no fan. This is two sensors named so:
*
* - `hwmon0` (`cpu0_thermal`): `temp1_input` linked to a CPU thermal zone the app can read;
* - `hwmon1` (`gpuss0_thermal`): `temp1_input` linked to the GPU's zone, and `fan1_input` with
* the device's fan speed where it has a fan the app can read - an AYN handheld's tachometer
* (`/sys/class/gpio5_pwm2/speed`), or a `fan*_input` in the device's own hwmon;
* - `hwmon2` (`slg4ax46073v`): the same fan, for Valve's own Qualcomm reader (msm.cpp), which
* looks for its fan controller by that name and halves what it reads - that part reports twice
* the real speed - so this one holds twice it.
*
* Nothing in a phone's own hwmon is read by the overlay, so standing in for it loses nothing.
*/
class HwmonComponent(val dir: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private var fanSource: String? = null
private val fanFile = File(dir, "hwmon1/fan1_input")
private val valveFanFile = File(dir, "hwmon2/fan1_input")
private var lastRpm = 0L
private var lastRpmAt = 0L
/** Writes the sensors; true when the directory should be bound over `/sys/class/hwmon`. */
fun prepare(): Boolean = try {
dir.mkdirs()
clear(dir)
val cpu = LinuxRuntime.cpuTempSource()
if (cpu != null) sensor("hwmon0", "cpu0_thermal").also { link(cpu, File(it, "temp1_input")) }
val gpu = LinuxRuntime.gpuTempSource()
fanSource = FAN_SOURCES().firstOrNull { readNumber(it) != null }
if (gpu != null || fanSource != null) {
val sensor = sensor("hwmon1", "gpuss0_thermal")
if (gpu != null) link(gpu, File(sensor, "temp1_input"))
if (fanSource != null) {
sensor("hwmon2", "slg4ax46073v")
writeFan(sampleFan())
}
}
Log.i(TAG, "hud: hwmon cpu temp ${cpu ?: "none"}, gpu temp ${gpu ?: "none"}, fan ${fanSource ?: "none"}")
cpu != null || gpu != null || fanSource != null
} catch (e: Exception) {
Log.w(TAG, "hud: could not write the session's hwmon: $e")
false
}
override fun start() {
if (fanSource == null) return
running = true
thread = Thread({
while (running) {
try { Thread.sleep(FAN_PERIOD_MS) } catch (e: InterruptedException) { break }
if (running) writeFan(sampleFan())
}
}, "hwmon-fan").apply { isDaemon = true; start() }
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
}
/**
* The fan's speed in RPM. An AYN tachometer counts pulses over a short window per read and
* often catches none, reading 0 while the fan turns; a reading is held until a newer one
* comes or [FAN_HOLD_MS] passes with only zeros, when the fan is taken to have stopped.
*/
private fun sampleFan(): Long {
val now = SystemClock.elapsedRealtime()
val rpm = fanSource?.let { readNumber(it) } ?: 0L
if (rpm > 0) {
lastRpm = rpm
lastRpmAt = now
} else if (now - lastRpmAt > FAN_HOLD_MS) {
lastRpm = 0
}
return lastRpm
}
/** In place and at one length, so a reader that keeps the file open sees each value whole. */
private fun writeFan(rpm: Long) {
for ((file, value) in listOf(fanFile to rpm, valveFanFile to rpm * 2)) {
try {
RandomAccessFile(file, "rw").use { it.seek(0); it.write(String.format("%6d\n", value).toByteArray()) }
} catch (e: Exception) {
}
}
}
private fun sensor(name: String, label: String): File =
File(dir, name).apply { mkdirs(); File(this, "name").writeText("$label\n") }
private fun link(target: String, link: File) {
java.nio.file.Files.deleteIfExists(link.toPath())
Os.symlink(target, link.path)
}
/** Only files and links are made here; deleting a link must not follow it into sysfs. */
private fun clear(root: File) {
root.listFiles()?.forEach { f ->
if (!java.nio.file.Files.isSymbolicLink(f.toPath()) && f.isDirectory) clear(f)
java.nio.file.Files.deleteIfExists(f.toPath())
}
}
companion object {
private const val TAG = "SessionService"
/** The AYN tachometer reads 0 if read again within a couple of seconds. */
private const val FAN_PERIOD_MS = 3_000L
private const val FAN_HOLD_MS = 10_000L
private val FAN_SOURCES = {
val sources = mutableListOf("/sys/class/gpio5_pwm2/speed", "/sys/class/gpio5_pwm/speed")
File("/sys/class/hwmon").listFiles()?.sortedBy { it.name }?.forEach { hwmon ->
hwmon.listFiles { f -> f.name.matches(Regex("fan\\d+_input")) }?.sortedBy { it.name }
?.forEach { sources.add(it.path) }
}
sources
}
private fun readNumber(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()?.takeIf { it >= 0 }
}
}
@@ -688,6 +688,13 @@ class SessionService : Service() {
battery.attach(this)
components.add(battery)
binds.add(battery.dir.path + ":/sys/class/power_supply")
// The overlay's CPU and GPU temperatures and the fan, as hwmon sensors it knows by name.
val hwmon = HwmonComponent(File(filesDir, "session/sys/hwmon"))
if (hwmon.prepare()) {
hwmon.attach(this)
components.add(hwmon)
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
}
// CPU load for everything in the session that reads /proc/stat, the overlay among them.
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
if (cpuStat.prepare()) {
@@ -695,12 +702,18 @@ class SessionService : Service() {
components.add(cpuStat)
binds.add(cpuStat.file.path + ":/proc/stat")
}
// The GPU memory in use for the overlay's VRAM lines, which it would read from tracefs.
val gpuMem = GpuMemComponent(File(LinuxRuntime.rootDir(this), "run/droiddeck-hud/gpu-mem"))
if (gpuMem.prepare()) {
gpuMem.attach(this)
components.add(gpuMem)
}
// The GPU's load and temperature for the performance overlay, where KGSL's sysfs is refused.
val gpuStats = GpuStatsComponent(File(filesDir, "session/sys/kgsl-3d0"))
if (gpuStats.prepare()) {
gpuStats.attach(this)
components.add(gpuStats)
binds.add(gpuStats.dir.path + ":" + GpuStatsComponent.KGSL)
binds.addAll(gpuStats.binds())
}
// Rumble for the on-screen pad: the fake evdev layer sends force-feedback effects to this
// listener, which drives the phone's vibrator (see RumbleComponent).