From b2bde1c14d1264196a2b1710a3c45a3b5072bc40 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Sun, 4 Oct 2026 08:19:48 -0400 Subject: [PATCH] Add opt-in Steam storage diagnostics (#158) --- .../com/droiddeck/launcher/MainActivity.kt | 7 + .../launcher/session/SessionPrefs.kt | 8 + .../launcher/session/SessionService.kt | 31 +- .../launcher/session/StorageDiagnostics.kt | 69 ++++ .../launcher/ui/ModeSettingsDialog.kt | 8 + app/src/main/res/values/strings.xml | 2 + tools/linuxfs/preload/storage.c | 317 ++++++++++++++++++ 7 files changed, 440 insertions(+), 2 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/session/StorageDiagnostics.kt create mode 100644 tools/linuxfs/preload/storage.c diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index acf259563f..673d41ab45 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -316,6 +316,7 @@ class MainActivity : ComponentActivity() { private var backActionsInverted by mutableStateOf(false) private var renderer by mutableStateOf("vulkan") private var gameStorage by mutableStateOf("") + private var storageDiagnostics by mutableStateOf(false) private var storageOptions by mutableStateOf>>(emptyList()) private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) } @@ -1127,6 +1128,7 @@ class MainActivity : ComponentActivity() { renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, storageOptions = storageOptions, + storageDiagnostics = mode == SessionService.MODE_STEAM && storageDiagnostics, fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null, steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null, steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode, @@ -1196,6 +1198,10 @@ class MainActivity : ComponentActivity() { onPickGameStorageFolder = { pickGameStorage.launch(InAppFilePicker.buildDirIntent(this, "Choose the game storage folder", gameStorage.ifEmpty { null })) }, + onStorageDiagnostics = { on -> + SessionPrefs.setStorageDiagnosticsEnabled(this, on) + storageDiagnostics = on + }, onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id }, onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id }, onSteamDeckMode = { on -> @@ -1327,6 +1333,7 @@ class MainActivity : ComponentActivity() { refreshWifiDiscovery() renderer = SessionPrefs.desktopRenderer(this) gameStorage = SessionPrefs.gameStorage(this) + storageDiagnostics = SessionPrefs.storageDiagnosticsEnabled(this) settingsMode = mode // The page opens at once, on what was last read; the slow part (driver files, a walk of the // added-games folders, the storage volumes) lands while it animates in. 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 26e234e284..1f698d6fe6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -448,6 +448,14 @@ object SessionPrefs { prefs(context).edit().putBoolean("logs", on).apply() } + /** Steam storage-call diagnostics are opt-in because they add timing work to file operations. */ + fun storageDiagnosticsEnabled(context: Context): Boolean = + prefs(context).getBoolean("storageDiagnostics", false) + + fun setStorageDiagnosticsEnabled(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("storageDiagnostics", on).apply() + } + // ── Per-mode display ──────────────────────────────────────────────────────────────────── /** 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 139db9fae1..4e837efc23 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -390,7 +390,7 @@ class SessionService : Service() { // whatever a session leaves behind. The client abandons tens of megabytes of streams a run. FileUtils.clear(File(cacheDir, "shm")) - val binds = sessionBinds(controllersOn, fakeInputDir) + val binds = sessionBinds(controllersOn, fakeInputDir, sessionDir, guest) // The fast path is told exactly the rootfs and binds proot is given (ProotFastPath). val fastPathKey = if (ProotFastPath.enabled(this)) { val prootBinds = LinuxRuntime.binds( @@ -720,7 +720,12 @@ class SessionService : Service() { } /** What proot binds into the guest: the pads, the battery, storage, the game library, added games and ROMs. */ - private fun sessionBinds(controllersOn: Boolean, fakeInputDir: File): ArrayList { + private fun sessionBinds( + controllersOn: Boolean, + fakeInputDir: File, + sessionDir: File, + guest: MutableList, + ): ArrayList { val binds = ArrayList() if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input") if (controllersOn) binds.addAll(deckBinds) @@ -779,6 +784,7 @@ class SessionService : Service() { // bannerlator-steam-library registers with the client. Nothing bound = the script removes // the entry, so the client never offers a place that is not there. val library = GameStorage.effective(this) + var storageDiagnosticLibrary: File? = null if (library != null) { val problem = GameStorage.prepare(library.path) if (problem == null) { @@ -787,6 +793,7 @@ class SessionService : Service() { File(LinuxRuntime.rootDir(this), "mnt/bannerlator-sd").mkdirs() try { binds.addAll(SecondaryLibrary.binds(filesDir, File(library.path))) + storageDiagnosticLibrary = File(library.path) Log.i(TAG, "game storage: ${library.path} -> /mnt/droiddeck-sd (\"${library.label}\"); prefixes and native tools private") } catch (e: Exception) { Log.w(TAG, "game storage: private directories could not be prepared; internal only this session", e) @@ -797,6 +804,26 @@ class SessionService : Service() { } else { Log.i(TAG, "game storage: internal only") } + if (SessionState.mode == MODE_STEAM && SessionPrefs.storageDiagnosticsEnabled(this)) { + val target = storageDiagnosticLibrary ?: File(LinuxRuntime.rootDir(this), "root/.local/share/Steam") + val device = StorageDiagnostics.writeSnapshot( + sessionDir, target, + selectedLibrary = if (storageDiagnosticLibrary != null) "secondary" else "internal", + removable = storageDiagnosticLibrary?.let { + runCatching { Environment.isExternalStorageRemovable(it) }.getOrDefault(false) + } ?: false, + ) + if (device != null) { + // guest already has the session command at this point. Put these with the `env -i` + // assignments so they reach the Steam process instead of becoming script args. + val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size + guest.add(envAt, "BL_STORAGE_DIAGNOSTICS=1") + guest.add(envAt + 1, "BL_STORAGE_DEVICE=$device") + guest.add(envAt + 2, "BL_STORAGE_LOG=${File(sessionDir, "storage.log").absolutePath}") + } else { + Log.w(TAG, "storage diagnostics: selected library could not be identified; metadata snapshot only") + } + } // The user's own games folder (the Steam cog's "Added games"), bound at a fixed place so // the shortcuts the app writes point somewhere whatever storage the folder is on. for (root in com.droiddeck.launcher.frontend.AddedGames.roots(this)) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/StorageDiagnostics.kt b/app/src/main/java/com/droiddeck/launcher/session/StorageDiagnostics.kt new file mode 100644 index 0000000000..73b64fb445 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/StorageDiagnostics.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.session + +import android.os.StatFs +import android.system.Os +import android.util.Log +import java.io.File + +/** The opt-in snapshot written beside a session's other logs. */ +object StorageDiagnostics { + private const val TAG = "StorageDiagnostics" + + /** + * Records facts about the library actually selected for this session and returns its device + * number for the preload shim. The path and volume ID stay out of the shared log. + */ + fun writeSnapshot( + sessionDir: File, + library: File, + selectedLibrary: String, + removable: Boolean, + ): Long? { + val device = runCatching { Os.stat(library.absolutePath).st_dev }.getOrNull() + val text = buildString { + appendLine("DroidDeck storage diagnostics v1") + appendLine("selected_library=$selectedLibrary") + appendLine("volume_removable=$removable") + appendLine("filesystem=${filesystemType(library) ?: "unknown"}") + runCatching { StatFs(library.path) }.onSuccess { fs -> + appendLine("block_size_bytes=${fs.blockSizeLong}") + appendLine("total_bytes=${fs.totalBytes}") + appendLine("available_bytes=${fs.availableBytes}") + }.onFailure { appendLine("capacity_error=${it.javaClass.simpleName}") } + appendLine("native_observation=${if (device != null) "enabled" else "unavailable"}") + appendLine("public_symbol_interposition=${if (device != null) "enabled" else "unavailable"}") + appendLine("direct_syscalls_and_libc_internal_calls=not_observed") + appendLine("pwrite_timing=sampled_1_in_32") + appendLine("per_process_allocation_detail_limit=64") + appendLine("storage_log_limit_bytes=524288") + } + return try { + File(sessionDir, "storage.log").writeText(text) + device + } catch (e: Exception) { + Log.w(TAG, "could not write storage diagnostic snapshot", e) + null + } + } + + /** The longest matching mount entry determines the filesystem for nested bindable folders. */ + private fun filesystemType(path: File): String? = runCatching { + val canonical = path.canonicalPath + File("/proc/mounts").useLines { lines -> + lines.mapNotNull { line -> + val fields = line.split(Regex("\\s+")) + if (fields.size < 3) null else { + val mount = unescapeMount(fields[1]).trimEnd('/').ifEmpty { "/" } + val matches = canonical == mount || + (mount == "/" && canonical.startsWith('/')) || canonical.startsWith("$mount/") + if (matches) mount.length to fields[2] else null + } + }.maxByOrNull { it.first }?.second?.takeIf { it.matches(Regex("[A-Za-z0-9._-]+")) } + } + }.getOrNull() + + private fun unescapeMount(value: String): String = value + .replace("\\040", " ") + .replace("\\011", "\t") + .replace("\\134", "\\") +} 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 ff6a32d59b..d260c069fb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -70,6 +70,8 @@ class ModeSettings( val renderer: String?, val gameStorage: String? = null, val storageOptions: List> = emptyList(), + /** Steam only: record allocation and sampled storage timings in the next session's Share logs. */ + val storageDiagnostics: Boolean = false, val fexPreset: String? = null, /** Steam only: games are stretched to fill the screen (null = not a Steam page). */ val forceFullscreen: Boolean? = null, @@ -130,6 +132,7 @@ class ModeSettingsActions( val onRenderer: (String) -> Unit, val onGameStorage: (path: String, label: String) -> Unit = { _, _ -> }, val onPickGameStorageFolder: () -> Unit = {}, + val onStorageDiagnostics: (Boolean) -> Unit = {}, val onFexPreset: (String) -> Unit = {}, val onForceFullscreen: (Boolean) -> Unit = {}, val onStretch16x9: (Boolean) -> Unit = {}, @@ -457,6 +460,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { } } } + ToggleRow( + host, "storageDiagnostics", stringResource(R.string.mode_storage_diagnostics), + stringResource(R.string.mode_storage_diagnostics_hint), s.storageDiagnostics, + onChange = a.onStorageDiagnostics, + ) } if (!steam && s.renderer != null) SettingsGroup(stringResource(R.string.mode_renderer)) { ChoiceRow( diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 81d0b87d8e..273eaac326 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -308,6 +308,8 @@ Folder: %1$s Second library Games that stream assets from SD or shared storage may stutter. + Storage diagnostics + Record allocation results and sampled storage timings in Share logs. May slow installs while enabled. Applies next session. Choose a folder… Renderer Desktop renderer diff --git a/tools/linuxfs/preload/storage.c b/tools/linuxfs/preload/storage.c new file mode 100644 index 0000000000..d31ee0d0fe --- /dev/null +++ b/tools/linuxfs/preload/storage.c @@ -0,0 +1,317 @@ +/* + * Opt-in observations for file allocation and writes to the selected Steam library. + * + * Steam's allocation failure and any later fallback are left entirely to the caller. These + * wrappers only forward the same arguments, record the result and restore errno after logging. + * The session enables them only when storage diagnostics are turned on. Counters are local to + * each process, allocation details are capped, writes are sampled, and storage.log has a global + * size limit because every Steam child shares it. + * + * LD_PRELOAD cannot see direct syscalls or libc-internal calls that bypass public symbols. A + * missing entry therefore does not prove the operation did not happen. + */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int (*next_fstat)(int, struct stat *); +static int (*next_fallocate)(int, int, off_t, off_t); +static int (*next_posix_fallocate)(int, off_t, off_t); +static ssize_t (*next_pwrite)(int, const void *, size_t, off_t); +static int (*next_ftruncate)(int, off_t); +static int (*next_fsync)(int); + +struct counters { + volatile uint64_t alloc_calls, alloc_failures, alloc_elapsed_ns; + volatile uint64_t pwrite_samples, pwrite_bytes, pwrite_failures, pwrite_elapsed_ns, pwrite_max_ns; + volatile uint64_t ftruncate_calls, ftruncate_failures, ftruncate_elapsed_ns, ftruncate_max_ns; + volatile uint64_t fstat_calls, fstat_elapsed_ns, fstat_max_ns; + volatile uint64_t fsync_calls, fsync_failures, fsync_elapsed_ns, fsync_max_ns; +}; + +static struct counters stats; +static volatile uint64_t pwrite_seen; +static volatile unsigned int alloc_details; +static long long selected_device; +static int init_state; +static int enabled; + +static uint64_t add(volatile uint64_t *slot, uint64_t value) { + return __atomic_add_fetch(slot, value, __ATOMIC_RELAXED); +} + +static uint64_t get(const volatile uint64_t *slot) { + return __atomic_load_n(slot, __ATOMIC_RELAXED); +} + +static void update_max(volatile uint64_t *slot, uint64_t value) { + uint64_t old = get(slot); + while (old < value && !__atomic_compare_exchange_n(slot, &old, value, 0, + __ATOMIC_RELAXED, __ATOMIC_RELAXED)) { + } +} + +static void initialize(void) { + int state = __atomic_load_n(&init_state, __ATOMIC_ACQUIRE); + if (state == 2) return; + int expected = 0; + if (!__atomic_compare_exchange_n(&init_state, &expected, 1, 0, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) { + while (__atomic_load_n(&init_state, __ATOMIC_ACQUIRE) != 2) { } + return; + } + const char *on = getenv("BL_STORAGE_DIAGNOSTICS"); + const char *device = getenv("BL_STORAGE_DEVICE"); + if (on != NULL && strcmp(on, "1") == 0 && device != NULL && *device != '\0') { + char *end = NULL; + errno = 0; + long long parsed = strtoll(device, &end, 10); + if (errno == 0 && end != device && *end == '\0') { + selected_device = parsed; + enabled = 1; + } + } + __atomic_store_n(&init_state, 2, __ATOMIC_RELEASE); +} + +static uint64_t now_ns(void) { + struct timespec ts; + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; + return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec; +} + +static int on_selected_device(int fd, const struct stat *known) { + struct stat local; + initialize(); + if (!enabled) return 0; + if (known == NULL) { + if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat"); + if (next_fstat == NULL || next_fstat(fd, &local) != 0) return 0; + known = &local; + } + return (long long)known->st_dev == selected_device; +} + +static void comm_name(char *out, size_t size) { + const char *name = program_invocation_short_name; + size_t i = 0; + if (name == NULL || *name == '\0') name = "unknown"; + while (name[i] && i + 1 < size && i < 40) { + unsigned char c = (unsigned char)name[i]; + out[i] = ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.') ? (char)c : '_'; + i++; + } + out[i] = '\0'; +} + +static void append_line(const char *line, size_t length) { + const char *path = getenv("BL_STORAGE_LOG"); + struct stat st; + int saved = errno; + if (path == NULL || *path == '\0' || length == 0 || length > 2048) goto done; + int fd = (int)syscall(SYS_openat, (long)AT_FDCWD, (long)path, + (long)(O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC), 0600L, 0L, 0L); + if (fd < 0) goto done; + if (syscall(SYS_fstat, (long)fd, (long)&st, 0L, 0L, 0L, 0L) != 0 || st.st_size < 0 || + (uint64_t)st.st_size + length > 524288ULL) { + syscall(SYS_close, (long)fd, 0L, 0L, 0L, 0L, 0L); + goto done; + } + /* One small append write per complete line; no per-write log flood. */ + (void)syscall(SYS_write, (long)fd, (long)line, (long)length, 0L, 0L, 0L); + syscall(SYS_close, (long)fd, 0L, 0L, 0L, 0L, 0L); +done: + errno = saved; +} + +static void allocation_line(const char *api, int result, int error, int flags, + off_t offset, off_t length, uint64_t elapsed) { + char line[512], comm[48]; + int api_error = api[0] == 'f' ? (result < 0 ? error : 0) : result; + unsigned int detail = __atomic_add_fetch(&alloc_details, 1, __ATOMIC_RELAXED); + add(&stats.alloc_calls, 1); + add(&stats.alloc_elapsed_ns, elapsed); + if ((api[0] == 'f' && result < 0) || (api[0] == 'p' && result != 0)) + add(&stats.alloc_failures, 1); + if (detail > 64) return; + comm_name(comm, sizeof(comm)); + int n = snprintf(line, sizeof(line), + "allocation pid=%ld comm=%s api=%s result=%d api_error=%d errno_after=%d flags=0x%x offset=%lld length=%lld elapsed_us=%llu\n", + (long)getpid(), comm, api, result, api_error, error, flags, + (long long)offset, (long long)length, + (unsigned long long)(elapsed / 1000ULL)); + if (n > 0 && (size_t)n < sizeof(line)) append_line(line, (size_t)n); +} + +int fallocate(int fd, int mode, off_t offset, off_t length) { + int entry_errno = errno; + if (next_fallocate == NULL) next_fallocate = dlsym(RTLD_NEXT, "fallocate"); + if (next_fallocate == NULL) { errno = ENOSYS; return -1; } + int selected = on_selected_device(fd, NULL); + errno = entry_errno; + if (!selected) return next_fallocate(fd, mode, offset, length); + uint64_t start = now_ns(); + errno = entry_errno; + int result = next_fallocate(fd, mode, offset, length); + int call_errno = errno; + uint64_t elapsed = now_ns() - start; + allocation_line("fallocate", result, call_errno, mode, offset, length, elapsed); + errno = call_errno; + return result; +} + +int posix_fallocate(int fd, off_t offset, off_t length) { + int entry_errno = errno; + if (next_posix_fallocate == NULL) next_posix_fallocate = dlsym(RTLD_NEXT, "posix_fallocate"); + if (next_posix_fallocate == NULL) { errno = entry_errno; return ENOSYS; } + int selected = on_selected_device(fd, NULL); + errno = entry_errno; + if (!selected) { + int result = next_posix_fallocate(fd, offset, length); + errno = entry_errno; + return result; + } + uint64_t start = now_ns(); + errno = entry_errno; + int result = next_posix_fallocate(fd, offset, length); + int call_errno = errno; + uint64_t elapsed = now_ns() - start; + allocation_line("posix_fallocate", result, call_errno, 0, offset, length, elapsed); + errno = entry_errno; /* POSIX requires the error to be returned, leaving errno unchanged. */ + return result; +} + +ssize_t pwrite(int fd, const void *buffer, size_t count, off_t offset) { + int entry_errno = errno; + if (next_pwrite == NULL) next_pwrite = dlsym(RTLD_NEXT, "pwrite"); + if (next_pwrite == NULL) { errno = ENOSYS; return -1; } + initialize(); + uint64_t sequence = enabled ? add(&pwrite_seen, 1) : 1; + int sample = enabled && (sequence % 32ULL) == 0; + int selected = sample && on_selected_device(fd, NULL); + errno = entry_errno; + if (!selected) + return next_pwrite(fd, buffer, count, offset); + uint64_t start = now_ns(); + errno = entry_errno; + ssize_t result = next_pwrite(fd, buffer, count, offset); + int call_errno = errno; + uint64_t elapsed = now_ns() - start; + add(&stats.pwrite_samples, 1); + add(&stats.pwrite_bytes, result > 0 ? (uint64_t)result : 0); + add(&stats.pwrite_elapsed_ns, elapsed); + if (result < 0) add(&stats.pwrite_failures, 1); + update_max(&stats.pwrite_max_ns, elapsed); + errno = call_errno; + return result; +} + +int ftruncate(int fd, off_t length) { + int entry_errno = errno; + if (next_ftruncate == NULL) next_ftruncate = dlsym(RTLD_NEXT, "ftruncate"); + if (next_ftruncate == NULL) { errno = ENOSYS; return -1; } + int selected = on_selected_device(fd, NULL); + errno = entry_errno; + if (!selected) return next_ftruncate(fd, length); + uint64_t start = now_ns(); + errno = entry_errno; + int result = next_ftruncate(fd, length); + int call_errno = errno; + uint64_t elapsed = now_ns() - start; + add(&stats.ftruncate_calls, 1); + if (result != 0) add(&stats.ftruncate_failures, 1); + add(&stats.ftruncate_elapsed_ns, elapsed); + update_max(&stats.ftruncate_max_ns, elapsed); + errno = call_errno; + return result; +} + +int fstat(int fd, struct stat *out) { + int entry_errno = errno; + if (next_fstat == NULL) next_fstat = dlsym(RTLD_NEXT, "fstat"); + if (next_fstat == NULL) { errno = ENOSYS; return -1; } + initialize(); + errno = entry_errno; + if (!enabled) return next_fstat(fd, out); + uint64_t start = now_ns(); + errno = entry_errno; + int result = next_fstat(fd, out); + int call_errno = errno; + uint64_t elapsed = now_ns() - start; + if (result == 0 && on_selected_device(fd, out)) { + add(&stats.fstat_calls, 1); + add(&stats.fstat_elapsed_ns, elapsed); + update_max(&stats.fstat_max_ns, elapsed); + } + errno = call_errno; + return result; +} + +int fsync(int fd) { + int entry_errno = errno; + if (next_fsync == NULL) next_fsync = dlsym(RTLD_NEXT, "fsync"); + if (next_fsync == NULL) { errno = ENOSYS; return -1; } + int selected = on_selected_device(fd, NULL); + errno = entry_errno; + if (!selected) return next_fsync(fd); + uint64_t start = now_ns(); + errno = entry_errno; + int result = next_fsync(fd); + int call_errno = errno; + uint64_t elapsed = now_ns() - start; + add(&stats.fsync_calls, 1); + if (result != 0) add(&stats.fsync_failures, 1); + add(&stats.fsync_elapsed_ns, elapsed); + update_max(&stats.fsync_max_ns, elapsed); + errno = call_errno; + return result; +} + +static void flush_summary(void) __attribute__((destructor)); +static void flush_summary(void) { + char line[1024], comm[48]; + initialize(); + if (!enabled) return; + uint64_t alloc = get(&stats.alloc_calls), pwrite_samples = get(&stats.pwrite_samples); + uint64_t truncates = get(&stats.ftruncate_calls), fstats = get(&stats.fstat_calls), syncs = get(&stats.fsync_calls); + if (alloc == 0 && pwrite_samples == 0 && truncates == 0 && fstats == 0 && syncs == 0) return; + comm_name(comm, sizeof(comm)); + int n = snprintf(line, sizeof(line), + "summary pid=%ld comm=%s allocation_calls=%llu allocation_failures=%llu allocation_total_us=%llu pwrite_sample_every=32 pwrite_samples=%llu pwrite_bytes=%llu pwrite_failures=%llu pwrite_sample_total_us=%llu pwrite_sample_max_us=%llu ftruncate_calls=%llu ftruncate_failures=%llu ftruncate_total_us=%llu ftruncate_max_us=%llu fstat_calls=%llu fstat_total_us=%llu fstat_max_us=%llu fsync_calls=%llu fsync_failures=%llu fsync_total_us=%llu fsync_max_us=%llu\n", + (long)getpid(), comm, + (unsigned long long)alloc, (unsigned long long)get(&stats.alloc_failures), + (unsigned long long)(get(&stats.alloc_elapsed_ns) / 1000ULL), + (unsigned long long)pwrite_samples, (unsigned long long)get(&stats.pwrite_bytes), + (unsigned long long)get(&stats.pwrite_failures), + (unsigned long long)(get(&stats.pwrite_elapsed_ns) / 1000ULL), + (unsigned long long)(get(&stats.pwrite_max_ns) / 1000ULL), + (unsigned long long)truncates, (unsigned long long)get(&stats.ftruncate_failures), + (unsigned long long)(get(&stats.ftruncate_elapsed_ns) / 1000ULL), + (unsigned long long)(get(&stats.ftruncate_max_ns) / 1000ULL), + (unsigned long long)fstats, + (unsigned long long)(get(&stats.fstat_elapsed_ns) / 1000ULL), + (unsigned long long)(get(&stats.fstat_max_ns) / 1000ULL), + (unsigned long long)syncs, (unsigned long long)get(&stats.fsync_failures), + (unsigned long long)(get(&stats.fsync_elapsed_ns) / 1000ULL), + (unsigned long long)(get(&stats.fsync_max_ns) / 1000ULL)); + if (n > 0 && (size_t)n < sizeof(line)) append_line(line, (size_t)n); +} + +#if defined(__USE_LARGEFILE64) +int fallocate64(int fd, int mode, off64_t offset, off64_t length) __attribute__((alias("fallocate"))); +int posix_fallocate64(int fd, off64_t offset, off64_t length) __attribute__((alias("posix_fallocate"))); +ssize_t pwrite64(int fd, const void *buffer, size_t count, off64_t offset) __attribute__((alias("pwrite"))); +int ftruncate64(int fd, off64_t length) __attribute__((alias("ftruncate"))); +int fstat64(int fd, struct stat64 *out) __attribute__((alias("fstat"))); +#endif