Compare commits

..
Author SHA1 Message Date
maxjivi05 d3d91acc09 Fail the read-ahead probe when its readers do not finish in time 2026-11-26 04:26:30 -05:00
maxjivi05 ff7a2579d2 Look up read-ahead scans by key without touching another stream's scan
Each stream's scan is now found through a separate key table, so a
thread listing one folder never reads a scan another thread is freeing.
The read-ahead tests wait for the readers to finish instead of sleeping,
and check the thread count to prove nothing started.
2026-11-26 00:55:33 -05:00
maxjivi05 b78b19497d Read subfolders ahead after slow listings on removable storage
Wine lists each folder with opendir(".") after fchdir, so the Steam
client's listing cache never applied to programs on the card, and the
cost there is the first cold read of each folder rather than repeats.

dircache.c now times readdir in every program. A call of 20 ms or more
on FUSE, exFAT, FAT, NTFS3 or sdcardfs, in a program that already runs
more than one thread, queues that listing's subfolders for three
background readers, and a program listing a folder that was read ahead
queues its subfolders in turn. The readers only read directories, so
nothing a program sees can be stale. DD_NO_DIR_PREFETCH=1 turns it off.
2026-11-25 23:04:46 -05:00
44 changed files with 456 additions and 157 deletions

No files matched your search

@@ -620,8 +620,7 @@ static void cursor_publish_shown(void) {
static void cursor_publish_hidden(void) {
pthread_mutex_lock(&g_cursor_lock);
// A client that hides the cursor before ever showing one (gamescope drawing its own) must still be reported.
if (!g_cursor_hidden || g_cursor_serial == 0) { g_cursor_hidden = 1; g_cursor_serial++; }
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
pthread_mutex_unlock(&g_cursor_lock);
}
@@ -403,18 +403,6 @@ object AddedGames {
Log.i(TAG, "games: bound $dir at $guest")
}
fun unmountedShortcuts(context: Context, listed: List<Library.SteamGame>): Set<String> {
val gone = roots(context).filter { it.host.listFiles() == null }.map { it.host.path }
if (gone.isEmpty()) return emptySet()
val removed = SessionPrefs.removedAddedGames(context).toSet()
val present = listed.filter { it.library == Library.ADDED }.mapNotNull { it.gameFiles?.name?.lowercase() }.toSet()
return AddedExes.list(context).map { File(it.folder) }
.filter { f -> f.path !in removed && gone.any { f.path == it || inside(f.path, it) } && !f.isDirectory && f.name.lowercase() !in present }
.mapNotNull { SessionPrefs.addedGameStoredAppId(context, it.path) }
.map(com.droiddeck.launcher.stores.epic.EpicClient::gameId)
.toSet()
}
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
val out = ArrayList<String>()
val entries = entryFolders(context)
@@ -46,8 +46,8 @@ object GameFileSync {
check(libraryReadable(File(previousStorage))) { context.getString(R.string.game_sync_err_previous_sd) }
}
storage?.let { check(libraryReadable(File(it.path))) { context.getString(R.string.game_sync_err_game_storage) } }
val games = Library.launchableGames(context, strictRead = true)
GameFiles.sync(context, folder, games, keep = AddedGames.unmountedShortcuts(context, games))
AddedGames.roots(context).forEach { check(it.host.listFiles() != null) { context.getString(R.string.game_sync_err_added_games) } }
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true))
prefs(context).edit().putString("storageSetting", storageSetting).putString("storagePath", storage?.path).apply()
}
@@ -144,7 +144,7 @@ object GameFiles {
if (!target.exists()) AtomicFile(target).writeBytes(art.readBytes())
}
@Synchronized fun sync(context: Context, folder: File, games: List<Library.SteamGame>, keep: Set<String> = emptySet()) {
@Synchronized fun sync(context: Context, folder: File, games: List<Library.SteamGame>) {
require(folder.isDirectory) { context.getString(R.string.gfiles_folder_unavailable) }
val inventory = child(context, folder, INVENTORY)
val previous = if (inventory.exists()) {
@@ -168,15 +168,13 @@ object GameFiles {
if (!existed || owned) next.put(file.name, game.gameIdString)
file
}
val kept = keep - unique.map { it.gameIdString }.toSet()
for (name in previous.keys()) {
val id = previous.getString(name)
if (!next.has(name) && ours(name) && GameLaunchLink.validId(id)) {
val file = child(context, folder, name)
if (matches(file, contents(id))) {
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
if (!retained && id in kept) next.put(name, id)
else if (!retained) check(file.delete()) { context.getString(R.string.gfiles_remove_failed, name) }
if (!retained) check(file.delete()) { context.getString(R.string.gfiles_remove_failed, name) }
}
}
}
+1
View File
@@ -1890,6 +1890,7 @@
<string name="game_sync_err_steam_library">مكتبة Steam غير متاحة</string>
<string name="game_sync_err_previous_sd">مكتبة SD السابقة غير متاحة</string>
<string name="game_sync_err_game_storage">مساحة تخزين الألعاب غير متاحة</string>
<string name="game_sync_err_added_games">مجلد الألعاب المضافة غير متاح</string>
<string name="game_sync_err_manifests">ملفات البيان في Steam غير متاحة</string>
<string name="content_system_many">أنظمة متعددة</string>
<string name="fm_drive_internal">التخزين الداخلي</string>
@@ -1903,6 +1903,7 @@
<string name="game_sync_err_steam_library">La biblioteca de Steam no está disponible</string>
<string name="game_sync_err_previous_sd">La biblioteca anterior de la SD no está disponible</string>
<string name="game_sync_err_game_storage">El almacenamiento de juegos no está disponible</string>
<string name="game_sync_err_added_games">La carpeta de juegos agregados no está disponible</string>
<string name="game_sync_err_manifests">Los manifiestos de Steam no están disponibles</string>
<string name="content_system_many">Varios sistemas</string>
<string name="fm_drive_internal">Interno</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Библиотеката на Steam не е достъпна</string>
<string name="game_sync_err_previous_sd">Предишната SD библиотека не е достъпна</string>
<string name="game_sync_err_game_storage">Хранилището за игри не е достъпно</string>
<string name="game_sync_err_added_games">Папката с добавени игри не е достъпна</string>
<string name="game_sync_err_manifests">Манифестите на Steam не са достъпни</string>
<string name="content_system_many">Много системи</string>
<string name="fm_drive_internal">Вътрешна</string>
+1
View File
@@ -1852,6 +1852,7 @@
<string name="game_sync_err_steam_library">Knihovna Steamu není dostupná</string>
<string name="game_sync_err_previous_sd">Předchozí knihovna na SD kartě není dostupná</string>
<string name="game_sync_err_game_storage">Úložiště her není dostupné</string>
<string name="game_sync_err_added_games">Složka přidaných her není dostupná</string>
<string name="game_sync_err_manifests">Manifesty Steamu nejsou dostupné</string>
<string name="content_system_many">Mnoho systémů</string>
<string name="fm_drive_internal">Interní</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Steam-biblioteket er ikke tilgængeligt</string>
<string name="game_sync_err_previous_sd">Det tidligere SD-bibliotek er ikke tilgængeligt</string>
<string name="game_sync_err_game_storage">Spillagring er ikke tilgængelig</string>
<string name="game_sync_err_added_games">Mappen med tilføjede spil er ikke tilgængelig</string>
<string name="game_sync_err_manifests">Steam-manifester er ikke tilgængelige</string>
<string name="content_system_many">Mange systemer</string>
<string name="fm_drive_internal">Intern</string>
+1
View File
@@ -1806,6 +1806,7 @@
<string name="game_sync_err_steam_library">Steam-Bibliothek ist nicht verfügbar</string>
<string name="game_sync_err_previous_sd">Vorherige SD-Bibliothek ist nicht verfügbar</string>
<string name="game_sync_err_game_storage">Spielspeicher ist nicht verfügbar</string>
<string name="game_sync_err_added_games">Ordner für hinzugefügte Spiele ist nicht verfügbar</string>
<string name="game_sync_err_manifests">Steam-Manifeste sind nicht verfügbar</string>
<string name="content_system_many">Viele Systeme</string>
<string name="fm_drive_internal">Intern</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Η βιβλιοθήκη Steam δεν είναι διαθέσιμη</string>
<string name="game_sync_err_previous_sd">Η προηγούμενη βιβλιοθήκη SD δεν είναι διαθέσιμη</string>
<string name="game_sync_err_game_storage">Ο χώρος αποθήκευσης παιχνιδιών δεν είναι διαθέσιμος</string>
<string name="game_sync_err_added_games">Ο φάκελος προστιθέμενων παιχνιδιών δεν είναι διαθέσιμος</string>
<string name="game_sync_err_manifests">Τα manifest του Steam δεν είναι διαθέσιμα</string>
<string name="content_system_many">Πολλά συστήματα</string>
<string name="fm_drive_internal">Εσωτερική</string>
+1
View File
@@ -1833,6 +1833,7 @@
<string name="game_sync_err_steam_library">La biblioteca de Steam no está disponible</string>
<string name="game_sync_err_previous_sd">La biblioteca anterior de la SD no está disponible</string>
<string name="game_sync_err_game_storage">El almacenamiento de juegos no está disponible</string>
<string name="game_sync_err_added_games">La carpeta de juegos añadidos no está disponible</string>
<string name="game_sync_err_manifests">Los manifiestos de Steam no están disponibles</string>
<string name="content_system_many">Varios sistemas</string>
<string name="fm_drive_internal">Interno</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Steam-kirjasto ei ole käytettävissä</string>
<string name="game_sync_err_previous_sd">Aiempi SD-kirjasto ei ole käytettävissä</string>
<string name="game_sync_err_game_storage">Pelien tallennustila ei ole käytettävissä</string>
<string name="game_sync_err_added_games">Lisättyjen pelien kansio ei ole käytettävissä</string>
<string name="game_sync_err_manifests">Steam-manifestit eivät ole käytettävissä</string>
<string name="content_system_many">Useita järjestelmiä</string>
<string name="fm_drive_internal">Sisäinen</string>
+1
View File
@@ -1832,6 +1832,7 @@
<string name="game_sync_err_steam_library">La bibliothèque Steam n\'est pas disponible</string>
<string name="game_sync_err_previous_sd">L\'ancienne bibliothèque SD n\'est pas disponible</string>
<string name="game_sync_err_game_storage">Le stockage des jeux n\'est pas disponible</string>
<string name="game_sync_err_added_games">Le dossier des jeux ajoutés n\'est pas disponible</string>
<string name="game_sync_err_manifests">Les manifestes Steam ne sont pas disponibles</string>
<string name="content_system_many">Nombreux systèmes</string>
<string name="fm_drive_internal">Interne</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Steam लाइब्रेरी उपलब्ध नहीं है</string>
<string name="game_sync_err_previous_sd">पिछली SD लाइब्रेरी उपलब्ध नहीं है</string>
<string name="game_sync_err_game_storage">गेम स्टोरेज उपलब्ध नहीं है</string>
<string name="game_sync_err_added_games">जोड़े गए गेम का फ़ोल्डर उपलब्ध नहीं है</string>
<string name="game_sync_err_manifests">Steam मेनिफ़ेस्ट उपलब्ध नहीं हैं</string>
<string name="content_system_many">कई सिस्टम</string>
<string name="fm_drive_internal">इंटरनल</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">A Steam-könyvtár nem elérhető</string>
<string name="game_sync_err_previous_sd">A korábbi SD-könyvtár nem elérhető</string>
<string name="game_sync_err_game_storage">A játéktárhely nem elérhető</string>
<string name="game_sync_err_added_games">A hozzáadott játékok mappája nem elérhető</string>
<string name="game_sync_err_manifests">A Steam-manifesztek nem elérhetők</string>
<string name="content_system_many">Sok rendszer</string>
<string name="fm_drive_internal">Belső</string>
+1
View File
@@ -1796,6 +1796,7 @@
<string name="game_sync_err_steam_library">Pustaka Steam tidak tersedia</string>
<string name="game_sync_err_previous_sd">Pustaka SD sebelumnya tidak tersedia</string>
<string name="game_sync_err_game_storage">Penyimpanan gim tidak tersedia</string>
<string name="game_sync_err_added_games">Folder gim yang ditambahkan tidak tersedia</string>
<string name="game_sync_err_manifests">Manifes Steam tidak tersedia</string>
<string name="content_system_many">Banyak sistem</string>
<string name="fm_drive_internal">Internal</string>
+1
View File
@@ -1824,6 +1824,7 @@
<string name="game_sync_err_steam_library">La libreria di Steam non è disponibile</string>
<string name="game_sync_err_previous_sd">La libreria SD precedente non è disponibile</string>
<string name="game_sync_err_game_storage">L\'archivio dei giochi non è disponibile</string>
<string name="game_sync_err_added_games">La cartella dei giochi aggiunti non è disponibile</string>
<string name="game_sync_err_manifests">I manifest di Steam non sono disponibili</string>
<string name="content_system_many">Molti sistemi</string>
<string name="fm_drive_internal">Interna</string>
+1
View File
@@ -1796,6 +1796,7 @@
<string name="game_sync_err_steam_library">Steamライブラリを利用できません</string>
<string name="game_sync_err_previous_sd">以前のSDライブラリを利用できません</string>
<string name="game_sync_err_game_storage">ゲームストレージを利用できません</string>
<string name="game_sync_err_added_games">追加したゲームのフォルダを利用できません</string>
<string name="game_sync_err_manifests">Steamのマニフェストを利用できません</string>
<string name="content_system_many">多数のシステム</string>
<string name="fm_drive_internal">内部</string>
+1
View File
@@ -1796,6 +1796,7 @@
<string name="game_sync_err_steam_library">Steam 라이브러리를 사용할 수 없습니다</string>
<string name="game_sync_err_previous_sd">이전 SD 라이브러리를 사용할 수 없습니다</string>
<string name="game_sync_err_game_storage">게임 저장 공간을 사용할 수 없습니다</string>
<string name="game_sync_err_added_games">추가된 게임 폴더를 사용할 수 없습니다</string>
<string name="game_sync_err_manifests">Steam 매니페스트를 사용할 수 없습니다</string>
<string name="content_system_many">다양한 기종</string>
<string name="fm_drive_internal">내부</string>
+1
View File
@@ -1796,6 +1796,7 @@
<string name="game_sync_err_steam_library">Pustaka Steam tidak tersedia</string>
<string name="game_sync_err_previous_sd">Pustaka SD terdahulu tidak tersedia</string>
<string name="game_sync_err_game_storage">Storan permainan tidak tersedia</string>
<string name="game_sync_err_added_games">Folder permainan yang ditambah tidak tersedia</string>
<string name="game_sync_err_manifests">Manifest Steam tidak tersedia</string>
<string name="content_system_many">Banyak sistem</string>
<string name="fm_drive_internal">Dalaman</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Steam-biblioteket er ikke tilgjengelig</string>
<string name="game_sync_err_previous_sd">Det forrige SD-biblioteket er ikke tilgjengelig</string>
<string name="game_sync_err_game_storage">Spillagringen er ikke tilgjengelig</string>
<string name="game_sync_err_added_games">Mappen for tillagte spill er ikke tilgjengelig</string>
<string name="game_sync_err_manifests">Steam-manifestene er ikke tilgjengelige</string>
<string name="content_system_many">Mange systemer</string>
<string name="fm_drive_internal">Intern</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Steam-bibliotheek is niet beschikbaar</string>
<string name="game_sync_err_previous_sd">Vorige SD-bibliotheek is niet beschikbaar</string>
<string name="game_sync_err_game_storage">Gameopslag is niet beschikbaar</string>
<string name="game_sync_err_added_games">Map met toegevoegde games is niet beschikbaar</string>
<string name="game_sync_err_manifests">Steam-manifesten zijn niet beschikbaar</string>
<string name="content_system_many">Veel systemen</string>
<string name="fm_drive_internal">Intern</string>
+1
View File
@@ -1852,6 +1852,7 @@
<string name="game_sync_err_steam_library">Biblioteka Steam jest niedostępna</string>
<string name="game_sync_err_previous_sd">Poprzednia biblioteka na karcie SD jest niedostępna</string>
<string name="game_sync_err_game_storage">Miejsce na gry jest niedostępne</string>
<string name="game_sync_err_added_games">Folder dodanych gier jest niedostępny</string>
<string name="game_sync_err_manifests">Manifesty Steam są niedostępne</string>
<string name="content_system_many">Wiele systemów</string>
<string name="fm_drive_internal">Wewnętrzna</string>
@@ -1838,6 +1838,7 @@
<string name="game_sync_err_steam_library">A biblioteca do Steam não está disponível</string>
<string name="game_sync_err_previous_sd">A biblioteca anterior do cartão SD não está disponível</string>
<string name="game_sync_err_game_storage">O armazenamento de jogos não está disponível</string>
<string name="game_sync_err_added_games">A pasta de jogos adicionados não está disponível</string>
<string name="game_sync_err_manifests">Os manifestos do Steam não estão disponíveis</string>
<string name="content_system_many">Vários sistemas</string>
<string name="fm_drive_internal">Interno</string>
+1
View File
@@ -1846,6 +1846,7 @@
<string name="game_sync_err_steam_library">A biblioteca do Steam não está disponível</string>
<string name="game_sync_err_previous_sd">A biblioteca anterior no cartão SD não está disponível</string>
<string name="game_sync_err_game_storage">O armazenamento de jogos não está disponível</string>
<string name="game_sync_err_added_games">A pasta de jogos adicionados não está disponível</string>
<string name="game_sync_err_manifests">Os manifestos do Steam não estão disponíveis</string>
<string name="content_system_many">Vários sistemas</string>
<string name="fm_drive_internal">Interno</string>
+1
View File
@@ -1833,6 +1833,7 @@
<string name="game_sync_err_steam_library">Biblioteca Steam nu este disponibilă</string>
<string name="game_sync_err_previous_sd">Biblioteca SD anterioară nu este disponibilă</string>
<string name="game_sync_err_game_storage">Stocarea jocurilor nu este disponibilă</string>
<string name="game_sync_err_added_games">Folderul de jocuri adăugate nu este disponibil</string>
<string name="game_sync_err_manifests">Manifestele Steam nu sunt disponibile</string>
<string name="content_system_many">Multe sisteme</string>
<string name="fm_drive_internal">Internă</string>
+1
View File
@@ -1853,6 +1853,7 @@
<string name="game_sync_err_steam_library">Библиотека Steam недоступна</string>
<string name="game_sync_err_previous_sd">Предыдущая библиотека на SD-карте недоступна</string>
<string name="game_sync_err_game_storage">Хранилище игр недоступно</string>
<string name="game_sync_err_added_games">Папка добавленных игр недоступна</string>
<string name="game_sync_err_manifests">Манифесты Steam недоступны</string>
<string name="content_system_many">Множество систем</string>
<string name="fm_drive_internal">Внутреннее хранилище</string>
+1
View File
@@ -1814,6 +1814,7 @@
<string name="game_sync_err_steam_library">Steam-biblioteket är inte tillgängligt</string>
<string name="game_sync_err_previous_sd">Det tidigare SD-biblioteket är inte tillgängligt</string>
<string name="game_sync_err_game_storage">Spellagringen är inte tillgänglig</string>
<string name="game_sync_err_added_games">Mappen för tillagda spel är inte tillgänglig</string>
<string name="game_sync_err_manifests">Steam-manifesten är inte tillgängliga</string>
<string name="content_system_many">Många system</string>
<string name="fm_drive_internal">Internt</string>
+1
View File
@@ -1796,6 +1796,7 @@
<string name="game_sync_err_steam_library">ไลบรารี Steam ไม่พร้อมใช้งาน</string>
<string name="game_sync_err_previous_sd">ไลบรารี SD ก่อนหน้าไม่พร้อมใช้งาน</string>
<string name="game_sync_err_game_storage">พื้นที่จัดเก็บเกมไม่พร้อมใช้งาน</string>
<string name="game_sync_err_added_games">โฟลเดอร์เกมที่เพิ่มไม่พร้อมใช้งาน</string>
<string name="game_sync_err_manifests">ไฟล์ manifest ของ Steam ไม่พร้อมใช้งาน</string>
<string name="content_system_many">หลายระบบ</string>
<string name="fm_drive_internal">ภายใน</string>
+1
View File
@@ -1806,6 +1806,7 @@
<string name="game_sync_err_steam_library">Steam kütüphanesi kullanılamıyor</string>
<string name="game_sync_err_previous_sd">Önceki SD kütüphanesi kullanılamıyor</string>
<string name="game_sync_err_game_storage">Oyun depolama alanı kullanılamıyor</string>
<string name="game_sync_err_added_games">Eklenen oyunlar klasörü kullanılamıyor</string>
<string name="game_sync_err_manifests">Steam manifest dosyaları kullanılamıyor</string>
<string name="content_system_many">Birçok sistem</string>
<string name="fm_drive_internal">Dahili</string>
+1
View File
@@ -1852,6 +1852,7 @@
<string name="game_sync_err_steam_library">Бібліотека Steam недоступна</string>
<string name="game_sync_err_previous_sd">Попередня бібліотека на SD-карті недоступна</string>
<string name="game_sync_err_game_storage">Сховище ігор недоступне</string>
<string name="game_sync_err_added_games">Папка доданих ігор недоступна</string>
<string name="game_sync_err_manifests">Маніфести Steam недоступні</string>
<string name="content_system_many">Багато систем</string>
<string name="fm_drive_internal">Внутрішня пам’ять</string>
+1
View File
@@ -1796,6 +1796,7 @@
<string name="game_sync_err_steam_library">Thư viện Steam không khả dụng</string>
<string name="game_sync_err_previous_sd">Thư viện SD trước đó không khả dụng</string>
<string name="game_sync_err_game_storage">Lưu trữ game không khả dụng</string>
<string name="game_sync_err_added_games">Thư mục game đã thêm không khả dụng</string>
<string name="game_sync_err_manifests">Manifest của Steam không khả dụng</string>
<string name="content_system_many">Nhiều hệ máy</string>
<string name="fm_drive_internal">Nội bộ</string>
@@ -1873,6 +1873,7 @@
<string name="game_sync_err_steam_library">Steam 库不可用</string>
<string name="game_sync_err_previous_sd">之前的 SD 卡库不可用</string>
<string name="game_sync_err_game_storage">游戏存储不可用</string>
<string name="game_sync_err_added_games">已添加游戏的文件夹不可用</string>
<string name="game_sync_err_manifests">Steam 清单文件不可用</string>
<string name="content_system_many">多种平台</string>
<string name="fm_drive_internal">内部存储</string>
@@ -1795,6 +1795,7 @@
<string name="game_sync_err_steam_library">無法使用 Steam 收藏庫</string>
<string name="game_sync_err_previous_sd">無法使用先前的 SD 卡收藏庫</string>
<string name="game_sync_err_game_storage">無法使用遊戲儲存位置</string>
<string name="game_sync_err_added_games">無法使用已新增遊戲的資料夾</string>
<string name="game_sync_err_manifests">無法使用 Steam 清單檔案</string>
<string name="content_system_many">多個系統</string>
<string name="fm_drive_internal">內部</string>
@@ -1795,6 +1795,7 @@
<string name="game_sync_err_steam_library">無法使用 Steam 收藏庫</string>
<string name="game_sync_err_previous_sd">無法使用先前的 SD 卡收藏庫</string>
<string name="game_sync_err_game_storage">無法使用遊戲儲存空間</string>
<string name="game_sync_err_added_games">無法使用已新增遊戲的資料夾</string>
<string name="game_sync_err_manifests">無法使用 Steam 資訊清單</string>
<string name="content_system_many">多種主機</string>
<string name="fm_drive_internal">內部</string>
+1
View File
@@ -2054,6 +2054,7 @@
<string name="game_sync_err_steam_library">Steam library is unavailable</string>
<string name="game_sync_err_previous_sd">Previous SD library is unavailable</string>
<string name="game_sync_err_game_storage">Game storage is unavailable</string>
<string name="game_sync_err_added_games">Added games folder is unavailable</string>
<string name="game_sync_err_manifests">Steam manifests are unavailable</string>
<string name="content_system_many">Many systems</string>
<string name="fm_drive_internal">Internal</string>
@@ -72,61 +72,6 @@ class GameFileSyncTest {
GameFileSync.disable(context)
}
@Test fun unmountedAddedGamesKeepTheirFilesWithoutStoppingTheSync() {
val context = RuntimeEnvironment.getApplication()
val root = LinuxRuntime.rootDir(context)
listOf("usr/bin/gamescope", LinuxRuntime.SESSION_SCRIPT.removePrefix("/")).forEach { path ->
File(root, path).apply { parentFile!!.mkdirs(); writeText("") }
}
AddonPack.PROOT.file(context, AddonPack.COMPLETE).apply { parentFile!!.mkdirs(); writeText("") }
SessionPrefs.setGameStorage(context, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(context, emptyList())
val steamapps = File(root, "root/.local/share/Steam/steamapps").apply { mkdirs() }
val manifest = File(steamapps, "appmanifest_8400.acf").apply {
writeText("\"AppState\"\n{\n\"name\" \"Geometry Wars\"\n\"StateFlags\" \"4\"\n}")
}
val card = File(context.filesDir, "old-card/Games")
val solo = File(context.filesDir, "old-card/Solo")
SessionPrefs.setGameFolderBinds(context, listOf(card.path to "${AddedGames.GUEST_DIR}/Games", solo.path to "${AddedGames.GUEST_DIR}/Solo"))
val shortcuts = listOf("Card Game" to 0xC0FFEE01L, "Card Removed" to 0xC0FFEE02L, "Card Copy" to 0xC0FFEE03L, "Solo" to 0xC0FFEE04L).map { (name, appId) ->
val dir = if (name == "Solo") solo else File(card, name)
AddedExes.put(context, AddedExes.Entry(dir.path, File(dir, "game.exe").path))
SessionPrefs.addedGameAppId(context, dir.path, appId)
Library.SteamGame(0, name, null, Library.ADDED, (appId shl 32) or 0x02000000L, gameFiles = dir)
}
val (kept, removed, copied, single) = shortcuts
val folder = File(context.filesDir, "exports-added").apply { mkdirs() }
GameFileSync.enable(context, folder)
assertEquals(folder.path, GameFileSync.folder(context))
assertEquals("8400", File(folder, "Geometry Wars.steam").readText())
GameFiles.sync(context, folder, Library.launchableGames(context, strictRead = true) + shortcuts)
shortcuts.forEach { assertEquals(it.gameIdString, File(folder, "${it.name}.steam").readText()) }
SessionPrefs.setAddedGameRemoved(context, removed.gameFiles!!.path, true)
assertTrue(manifest.delete())
File(steamapps, "appmanifest_620.acf").writeText("\"AppState\"\n{\n\"name\" \"Portal 2\"\n\"StateFlags\" \"4\"\n}")
GameFileSync.syncConfigured(context)
assertEquals("620", File(folder, "Portal 2.steam").readText())
assertFalse(File(folder, "Geometry Wars.steam").exists())
assertEquals(kept.gameIdString, File(folder, "Card Game.steam").readText())
assertEquals(copied.gameIdString, File(folder, "Card Copy.steam").readText())
assertEquals(single.gameIdString, File(folder, "Solo.steam").readText())
assertFalse(File(folder, "Card Removed.steam").exists())
val copy = Library.SteamGame(0, "Card Copy", null, Library.ADDED, (0xBEEF0003L shl 32) or 0x02000000L,
gameFiles = File(context.filesDir, "new-card/Games/Card Copy"))
val steamCopy = Library.SteamGame(8400, "Card Game", null, "internal", gameFiles = File(context.filesDir, "steam/Card Game"))
assertEquals(setOf(kept.gameIdString, single.gameIdString), AddedGames.unmountedShortcuts(context, listOf(copy, steamCopy)))
assertTrue(card.mkdirs())
assertEquals(setOf(single.gameIdString), AddedGames.unmountedShortcuts(context, emptyList()))
assertTrue(solo.mkdirs())
assertEquals(emptySet<String>(), AddedGames.unmountedShortcuts(context, emptyList()))
GameFileSync.syncConfigured(context)
shortcuts.forEach { assertFalse(File(folder, "${it.name}.steam").exists()) }
assertTrue(File(folder, "Portal 2.steam").isFile)
GameFileSync.disable(context)
shortcuts.forEach { AddedExes.drop(context, it.gameFiles!!.path) }
SessionPrefs.setGameFolderBinds(context, emptyList())
}
@Test fun libraryReadableOnlyWhenListableOrNotCreatedOnPresentParent() {
val base = File(RuntimeEnvironment.getApplication().filesDir, "readable").apply { mkdirs() }
assertTrue(GameFileSync.libraryReadable(File(base, "dir").apply { mkdirs() }))
@@ -142,35 +142,6 @@ class GameFilesTest {
assertEquals("user edit", modified.readText())
}
@Test fun syncKeepsOnlyVanishedGamesItIsAskedToKeep() {
val folder = tmp.newFolder()
val steam = game()
val second = game("620", "Portal 2")
val shortcut = game(java.lang.Long.toUnsignedString((0xC0FFEE01L shl 32) or 0x02000000L), "Card Game")
val dropped = game(java.lang.Long.toUnsignedString((0xC0FFEE03L shl 32) or 0x02000000L), "Card Removed")
val moved = game(java.lang.Long.toUnsignedString((0xC0FFEE02L shl 32) or 0x02000000L), "Card Tool")
GameFiles.sync(app, folder, listOf(steam, second, shortcut, dropped, moved))
val renamed = game("620", "Portal 2 Remastered")
val third = game("1", "New install")
val movedRenamed = game(moved.gameIdString, "Card Tool Deluxe")
val keep = setOf(steam.gameIdString, shortcut.gameIdString, moved.gameIdString)
GameFiles.sync(app, folder, listOf(renamed, third, movedRenamed), keep = keep)
assertEquals("8400", File(folder, GameFiles.filename(steam)).readText())
assertEquals(shortcut.gameIdString, File(folder, GameFiles.filename(shortcut)).readText())
assertFalse(File(folder, GameFiles.filename(dropped)).exists())
assertFalse(File(folder, GameFiles.filename(second)).exists())
assertFalse(File(folder, GameFiles.filename(moved)).exists())
assertEquals("620", File(folder, GameFiles.filename(renamed)).readText())
assertEquals("1", File(folder, GameFiles.filename(third)).readText())
assertEquals(moved.gameIdString, File(folder, GameFiles.filename(movedRenamed)).readText())
GameFiles.sync(app, folder, listOf(renamed, third, movedRenamed))
assertFalse(File(folder, GameFiles.filename(steam)).exists())
assertFalse(File(folder, GameFiles.filename(shortcut)).exists())
assertTrue(File(folder, GameFiles.filename(renamed)).isFile)
assertTrue(File(folder, GameFiles.filename(third)).isFile)
assertTrue(File(folder, GameFiles.filename(movedRenamed)).isFile)
}
@Test fun failedExportDoesNotPruneOldInventoryAndNeverOverwritesCollisions() {
val folder = tmp.newFolder()
val first = game()
@@ -517,3 +517,30 @@ A program started from the card was traced the same way. Three things were measu
The rest of that launch was the program's own launcher and CPU-bound start-up, which did
not wait on the card in these traces.
## Cold listings in native sessions (2026-11-25)
A Wine program on the card lists each directory with `opendir(".")` after `fchdir`, so
the Steam client's listing cache (absolute `/steamapps` paths, client process only) never
applies to it. Tracing a Battle.net launch showed the repeat listings were already cheap
(0.5 to 1 ms each, 0.27 s in all); the cost was the first, cold read of each directory
(about 78 ms each, 22 s for 290 directories).
`dircache.c` now times each `readdir` call in every program. When a call takes 20 ms or
more on FUSE, exFAT, FAT, NTFS3 or sdcardfs, and the program already runs more than one
thread, the subfolders that listing returns are read ahead by three background threads.
A program listing a folder that was read ahead has that folder's subfolders read ahead in
turn, so the read-ahead follows the program's own walk. The threads only read
directories, so nothing the program sees can be stale. `DD_NO_DIR_PREFETCH=1` turns it
off.
Paired cold runs on the FIT, both halves of the WoW AddOns tree after the same memory
eviction, with the halves swapped between runs:
| Tree | Off | On |
| --- | --- | --- |
| Deep tree, 125 directories | 13.6, 14.0, 13.8 s | 10.0, 11.2, 12.6 s |
| Shallow tree, 136 directories | 11.3, 9.3, 12.6 s | 10.2, 12.2, 12.0 s |
The gain is limited because cold directory reads on the card do not overlap: more reader
threads only hide the card's latency behind the program's own work between listings.
-19
View File
@@ -425,22 +425,3 @@ at a pointer that never left the top-left corner. Steam picks Disabled for some
cursor followed the mouse while every click landed at (0,0). In Disabled the nested pointer now warps the X pointer as
in the other modes; real fingers are still ignored. `tools/tests/test_gamescope_disabled_touch_mouse.py` compiles the
branch from this patch.
## 0142 Steam is entered at the corner it is reset to
When Steam's window takes focus with `bResetToCorner`, gamescope parks the pointer in its bottom-right corner so
nothing in Big Picture is hovered and the controller owns the UI. Upstream fe7f21c (3.16.24) moved
`wlserver_mousefocus` ahead of that reset, so the window is first entered under the current pointer, then warped to
its centre (`wlserver_mousewarp`, synthetic), then moved to the corner. SteamOS's 3.16.23 still resets before focus,
so its motions reach no window and the X pointer stays at (0,0). On upstream 3.16.29 they reach Steam: on a Steam Deck
the pointer is at (1279,799) right after focus. The Deck shows no hover because Big Picture's page exists about 1 s
before the reset. On a Retroid Pocket Duo the page is created at the same moment, Chromium keeps the centre position
as its hover, and the second library tile stayed highlighted on every start (4 of 4).
Steam is now entered at the corner. The centre is still stored in `mouse_surface_cursorx/y`, so the gamepad cursor
starts there as before, but no motion is sent for it. The fake pointer position stays in the corner. Only the
`bResetToCorner` path changes. Other windows are entered under the pointer as upstream does.
With the patch, the Duo starts with only the bottom bar under the parked pointer hovered and controller focus on the
first tile (4 of 4 starts), and returns from a game the same way (3 of 3). Making 0100 ignore the X server's initial
pointer instead was tried and rejected: the centre motion still arrived, and the header or search bar ended up hovered.
@@ -1,31 +0,0 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -5790,7 +5790,16 @@
if ( win_surface(pFocus->inputFocusWindow) != nullptr && pFocus->cursor )
{
- wlserver_mousefocus( pFocus->inputFocusWindow->main_surface(), pFocus->cursor->x(), pFocus->cursor->y() );
+ int nEnterX = pFocus->cursor->x();
+ int nEnterY = pFocus->cursor->y();
+ // A window reset to the corner below must not first be entered under the cursor:
+ // a page that loads during the reset keeps that position as its hover.
+ if ( pFocus->inputFocusWindow->GetFocus()->bResetToCorner )
+ {
+ nEnterX = pFocus->inputFocusWindow->GetGeometry().nWidth - 1;
+ nEnterY = pFocus->inputFocusWindow->GetGeometry().nHeight - 1;
+ }
+ wlserver_mousefocus( pFocus->inputFocusWindow->main_surface(), nEnterX, nEnterY );
focus_log.debugf( "Setting mouse focus to: %s (%x)", pFocus->inputFocusWindow->debug_name(), pFocus->inputFocusWindow->id() );
}
@@ -5813,7 +5822,8 @@
if ( pFocus->inputFocusWindow->GetFocus()->bResetToCorner )
{
wlserver_lock();
- wlserver_mousewarp( pFocus->inputFocusWindow->GetGeometry().nWidth / 2, pFocus->inputFocusWindow->GetGeometry().nHeight / 2, 0, true );
+ wlserver.mouse_surface_cursorx = pFocus->inputFocusWindow->GetGeometry().nWidth / 2;
+ wlserver.mouse_surface_cursory = pFocus->inputFocusWindow->GetGeometry().nHeight / 2;
wlserver_fake_mouse_pos( pFocus->inputFocusWindow->GetGeometry().nWidth - 1, pFocus->inputFocusWindow->GetGeometry().nHeight - 1 );
wlserver_unlock();
}
+260 -3
View File
@@ -5,6 +5,7 @@
#include <fcntl.h>
#include <limits.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
@@ -682,12 +683,267 @@ static void finish(struct handle *h) {
give(&lock);
}
#define PREFETCH_SLOW_NS 20000000LL
#define PREFETCH_THREADS 3
#define PREFETCH_QUEUE 512
#define PREFETCH_BATCH 128
#define PREFETCH_SCANS 16
#define PREFETCH_SEEN 1024
#define EXFAT_MAGIC 0x2011BAB0
#define MSDOS_MAGIC 0x4d44
#define NTFS3_MAGIC 0x7366746e
#define SDCARDFS_MAGIC 0x5dca2df5
struct scan { char *path; char *names[PREFETCH_BATCH]; int n; };
static pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t qwake = PTHREAD_COND_INITIALIZER;
static char *queue[PREFETCH_QUEUE];
static int qtop, qcount;
static int workers;
static struct scan *scans[PREFETCH_SCANS];
static DIR *scan_keys[PREFETCH_SCANS];
static struct { dev_t dev; ino_t ino; } seen[PREFETCH_SEEN];
static int nseen, seen_at;
static int prefetching(void) {
static int on = -1;
if (on < 0) {
const char *off = getenv("DD_NO_DIR_PREFETCH");
on = !(off && strcmp(off, "1") == 0);
}
return on;
}
static void prefetch_fork(void) {
pthread_mutex_init(&qlock, NULL);
pthread_cond_init(&qwake, NULL);
for (int i = 0; i < PREFETCH_QUEUE; i++) queue[i] = NULL;
qtop = qcount = workers = 0;
for (int i = 0; i < PREFETCH_SCANS; i++) {
scans[i] = NULL;
scan_keys[i] = NULL;
}
nseen = seen_at = 0;
}
__attribute__((constructor)) static void prefetch_init(void) {
pthread_atfork(NULL, NULL, prefetch_fork);
}
static long long precise_ns(void) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (long long)t.tv_sec * 1000000000LL + t.tv_nsec;
}
static int slow_storage(int fd) {
struct statfs fs;
if (fstatfs(fd, &fs) != 0) return 0;
unsigned long type = (unsigned long)fs.f_type;
return type == FUSE_MAGIC || type == EXFAT_MAGIC || type == MSDOS_MAGIC || type == NTFS3_MAGIC ||
type == SDCARDFS_MAGIC;
}
static int threaded(void) {
char buf[1024];
int fd = open("/proc/self/stat", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) return 0;
buf[n] = 0;
char *at = strrchr(buf, ')');
long count = 0;
if (at == NULL || sscanf(at + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %*u %*u %*d %*d %*d %*d %ld", &count) != 1)
return 0;
return count > 1;
}
static int was_seen(dev_t dev, ino_t ino) {
for (int i = 0; i < nseen; i++)
if (seen[i].ino == ino && seen[i].dev == dev) return 1;
return 0;
}
static void *prefetcher(void *arg) {
(void)arg;
pthread_setname_np(pthread_self(), "dd-prefetch");
NEXT(opendir);
NEXT(readdir64);
NEXT(closedir);
NEXT(dirfd);
for (;;) {
pthread_mutex_lock(&qlock);
while (qcount == 0) pthread_cond_wait(&qwake, &qlock);
qtop = (qtop + PREFETCH_QUEUE - 1) % PREFETCH_QUEUE;
char *path = queue[qtop];
queue[qtop] = NULL;
qcount--;
pthread_mutex_unlock(&qlock);
DIR *d = next_opendir(path);
free(path);
if (d == NULL) continue;
struct stat st;
if (fstat(next_dirfd(d), &st) == 0) {
pthread_mutex_lock(&qlock);
if (!was_seen(st.st_dev, st.st_ino)) {
seen[seen_at].dev = st.st_dev;
seen[seen_at].ino = st.st_ino;
seen_at = (seen_at + 1) % PREFETCH_SEEN;
if (nseen < PREFETCH_SEEN) __atomic_store_n(&nseen, nseen + 1, __ATOMIC_RELEASE);
}
pthread_mutex_unlock(&qlock);
}
while (next_readdir64(d)) {}
next_closedir(d);
}
return NULL;
}
static void start_prefetchers(void) {
pthread_attr_t attr;
sigset_t all, old;
if (pthread_attr_init(&attr) != 0) return;
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr, 256 * 1024);
sigfillset(&all);
pthread_sigmask(SIG_SETMASK, &all, &old);
while (workers < PREFETCH_THREADS) {
pthread_t t;
if (pthread_create(&t, &attr, prefetcher, NULL) != 0) break;
workers++;
}
pthread_sigmask(SIG_SETMASK, &old, NULL);
pthread_attr_destroy(&attr);
}
static void flush_scan(struct scan *s) {
size_t base = strlen(s->path);
pthread_mutex_lock(&qlock);
for (int i = s->n - 1; i >= 0; i--) {
size_t n = strlen(s->names[i]);
char *child = base + n + 2 <= PATH_MAX ? malloc(base + n + 2) : NULL;
if (child) {
memcpy(child, s->path, base);
child[base] = '/';
memcpy(child + base + 1, s->names[i], n + 1);
if (qcount == PREFETCH_QUEUE) free(queue[qtop]);
else qcount++;
queue[qtop] = child;
qtop = (qtop + 1) % PREFETCH_QUEUE;
}
free(s->names[i]);
}
s->n = 0;
if (qcount > 0) {
if (workers < PREFETCH_THREADS) start_prefetchers();
pthread_cond_broadcast(&qwake);
}
pthread_mutex_unlock(&qlock);
}
static int scan_slot(DIR *key) {
for (int i = 0; i < PREFETCH_SCANS; i++) {
if (__atomic_load_n(&scan_keys[i], __ATOMIC_ACQUIRE) == key) return i;
}
return -1;
}
static void end_scan(DIR *key) {
int i = scan_slot(key);
if (i < 0) return;
struct scan *s = scans[i];
scans[i] = NULL;
__atomic_store_n(&scan_keys[i], NULL, __ATOMIC_RELEASE);
flush_scan(s);
free(s->path);
free(s);
}
static void begin_scan(DIR *key, int fd) {
char link[64], path[PATH_MAX];
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
ssize_t n = readlink(link, path, sizeof(path) - 1);
if (n <= 0 || path[0] != '/') return;
path[n] = 0;
struct scan *s = calloc(1, sizeof(*s));
if (s == NULL || (s->path = strdup(path)) == NULL) {
free(s);
return;
}
pthread_mutex_lock(&qlock);
for (int i = 0; i < PREFETCH_SCANS; i++) {
if (__atomic_load_n(&scan_keys[i], __ATOMIC_ACQUIRE) == NULL) {
scans[i] = s;
__atomic_store_n(&scan_keys[i], key, __ATOMIC_RELEASE);
s = NULL;
break;
}
}
pthread_mutex_unlock(&qlock);
if (s) {
free(s->path);
free(s);
}
}
static int continues_walk(DIR *real, int fd) {
if (__atomic_load_n(&nseen, __ATOMIC_ACQUIRE) == 0 || next_telldir(real) != 0) return 0;
struct stat st;
if (fstat(fd, &st) != 0) return 0;
pthread_mutex_lock(&qlock);
int found = was_seen(st.st_dev, st.st_ino);
pthread_mutex_unlock(&qlock);
return found;
}
static void note(struct scan *s, const struct dirent64 *r) {
if (r->d_type != DT_DIR || strcmp(r->d_name, ".") == 0 || strcmp(r->d_name, "..") == 0 || s->n >= PREFETCH_BATCH)
return;
if ((s->names[s->n] = strdup(r->d_name)) != NULL) s->n++;
}
static struct dirent64 *pull(DIR *key, DIR *real, struct dirent64 *(*next)(DIR *)) {
if (holding || !prefetching()) return next(real);
NEXT(telldir);
NEXT(dirfd);
int i = scan_slot(key);
if (i < 0) {
int saved = errno;
int fd = next_dirfd(real);
int walk = continues_walk(real, fd);
errno = saved;
long long start = walk ? 0 : precise_ns();
struct dirent64 *r = next(real);
if (r == NULL) return r;
saved = errno;
if (walk || (precise_ns() - start >= PREFETCH_SLOW_NS && slow_storage(fd) &&
(__atomic_load_n(&workers, __ATOMIC_ACQUIRE) > 0 || threaded())))
begin_scan(key, fd);
i = scan_slot(key);
errno = saved;
if (i < 0) return r;
note(scans[i], r);
return r;
}
struct dirent64 *r = next(real);
int saved = errno;
if (r == NULL) {
end_scan(key);
} else {
note(scans[i], r);
}
errno = saved;
return r;
}
static struct dirent64 *entry(struct handle *h) {
NEXT(readdir64);
if (h->real) {
int saved = errno;
errno = 0;
struct dirent64 *r = next_readdir64(h->real);
struct dirent64 *r = pull((DIR *)h, h->real, next_readdir64);
int error = errno;
if (h->fill) {
if (r) {
@@ -711,13 +967,13 @@ static struct dirent64 *entry(struct handle *h) {
struct dirent64 *readdir64(DIR *d) {
NEXT(readdir64);
struct handle *h = lookup(d);
return h ? entry(h) : next_readdir64(d);
return h ? entry(h) : pull(d, d, next_readdir64);
}
struct dirent *readdir(DIR *d) {
NEXT(readdir);
struct handle *h = lookup(d);
return h ? (struct dirent *)entry(h) : next_readdir(d);
return h ? (struct dirent *)entry(h) : (struct dirent *)pull(d, d, (struct dirent64 * (*)(DIR *))next_readdir);
}
#pragma GCC diagnostic push
@@ -747,6 +1003,7 @@ int readdir_r(DIR *d, struct dirent *out, struct dirent **result) {
int closedir(DIR *d) {
NEXT(closedir);
if (holding && registered(d) < 0) return next_closedir(d);
end_scan(d);
take(&lock);
int i = registered(d);
struct handle *h = i >= 0 ? handles[i] : NULL;
+131
View File
@@ -20,9 +20,40 @@ FAKE = r"""
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/inotify.h>
#include <sys/prctl.h>
#include <unistd.h>
int real_opendirs;
static int prefetcher(void) {
char name[16] = "";
prctl(PR_GET_NAME, name);
return strcmp(name, "dd-prefetch") == 0;
}
static void cold(DIR *d) {
const char *slow = getenv("SLOW");
char link[64], path[4096];
if (!slow || prefetcher()) return;
snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd(d));
ssize_t n = readlink(link, path, sizeof(path) - 1);
path[n > 0 ? n : 0] = 0;
if (n > 5 && !strcmp(path + n - 5, "/cold")) usleep(atoi(slow) * 1000);
}
struct dirent *readdir(DIR *d) {
static struct dirent *(*next)(DIR *);
if (!next) next = dlsym(RTLD_NEXT, "readdir");
cold(d);
return next(d);
}
struct dirent64 *readdir64(DIR *d) {
static struct dirent64 *(*next)(DIR *);
if (!next) next = dlsym(RTLD_NEXT, "readdir64");
cold(d);
return next(d);
}
int real_accesses;
int real_stats;
@@ -130,9 +161,30 @@ int statfs(const char *path, struct statfs *out) {
return r;
}
int closedir(DIR *d) {
static int (*next)(DIR *);
if (!next) next = dlsym(RTLD_NEXT, "closedir");
const char *log = prefetcher() ? getenv("PREFETCH_DONE") : NULL;
FILE *f = log ? fopen(log, "a") : NULL;
if (f) {
fprintf(f, "done\n");
fclose(f);
}
return next(d);
}
DIR *opendir(const char *path) {
static DIR *(*next)(const char *);
if (!next) next = dlsym(RTLD_NEXT, "opendir");
if (prefetcher()) {
const char *log = getenv("PREFETCH_LOG");
FILE *f = log ? fopen(log, "a") : NULL;
if (f) {
fprintf(f, "%s\n", path);
fclose(f);
}
return next(path);
}
if (getenv("FASTPATH")) {
int fd = open(path, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NONBLOCK);
DIR *d = fd < 0 ? NULL : fdopendir(fd);
@@ -207,6 +259,12 @@ static void raw(const char *dir) {
print(names, n);
}
static void *idle(void *arg) {
(void)arg;
pause();
return NULL;
}
static const char *stress_dir;
static int stop;
@@ -350,6 +408,29 @@ int main(int argc, char **argv) {
if (d) closedir(d);
i += 2;
}
else if (!strcmp(op, "sleep")) { usleep(atoi(a) * 1000); i++; }
else if (!strcmp(op, "await")) {
const char *log = getenv("PREFETCH_DONE");
int lines = 0;
for (int tries = 0; tries < 2000 && lines < atoi(a); tries++) {
FILE *f = log ? fopen(log, "r") : NULL;
int c;
lines = 0;
while (f && (c = fgetc(f)) != EOF) lines += c == '\n';
if (f) fclose(f);
if (lines < atoi(a)) usleep(5000);
}
if (lines < atoi(a)) return 3;
i++;
}
else if (!strcmp(op, "threads")) {
FILE *f = fopen("/proc/self/status", "r");
char line[256];
while (f && fgets(line, sizeof(line), f))
if (!strncmp(line, "Threads:", 8)) printf("%d\n", atoi(line + 8));
if (f) fclose(f);
}
else if (!strcmp(op, "thread")) { pthread_t t; pthread_create(&t, NULL, idle, NULL); }
else if (!strcmp(op, "stats")) printf("%d\n", stats ? *stats : -1);
else if (!strcmp(op, "accesses")) printf("%d\n", accesses ? *accesses : -1);
else if (!strcmp(op, "opens")) printf("%d\n", opens ? *opens : -1);
@@ -897,6 +978,56 @@ class DirCachePreloadTest(unittest.TestCase):
out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"DD_NO_DIR_CACHE": "1"})
self.assertEqual("2", out[-1])
def cold_tree(self, root):
top = root / "cold"
for sub in ("a/deep/leaf", "b", "c"):
(top / sub).mkdir(parents=True)
(top / "f.txt").touch()
return top.resolve()
def prefetched(self, *args, program=None, env=None):
logs = Path(tempfile.mkdtemp(dir=self.dir))
log = logs / "prefetch.log"
out = self.run_program("thread", *args, program=program,
env=dict({"SLOW": "40", "PREFETCH_LOG": str(log),
"PREFETCH_DONE": str(logs / "done.log")}, **(env or {})))
return out, sorted(log.read_text().splitlines()) if log.exists() else []
def test_slow_listings_on_slow_storage_prefetch_the_walk_ahead(self):
for program, root in ((self.other, self.lib.parent), (self.steam, self.lib)):
top = self.cold_tree(root)
out, fetched = self.prefetched("list", top, "await", 3, "list", top / "a", "await", 4, program=program)
self.assertEqual(["a,b,c,f.txt", "deep"], out)
self.assertEqual(sorted(str(top / d) for d in ("a", "a/deep", "b", "c")), fetched)
def test_only_slow_listings_on_slow_storage_are_prefetched(self):
internal = self.cold_tree(Path(tempfile.mkdtemp(dir=self.dir)) / "ext4")
warm = self.lib.parent / "warm"
(warm / "child").mkdir(parents=True)
top = self.cold_tree(self.lib.parent)
out, fetched = self.prefetched("list", internal, "list", warm, "list", top, "await", 3, program=self.other)
self.assertEqual(["a,b,c,f.txt", "child", "a,b,c,f.txt"], out)
self.assertEqual(sorted(str(top / d) for d in ("a", "b", "c")), fetched)
def test_single_threaded_programs_stay_single_threaded(self):
top = self.cold_tree(self.lib.parent)
logs = Path(tempfile.mkdtemp(dir=self.dir))
log = logs / "prefetch.log"
env = {"SLOW": "40", "PREFETCH_LOG": str(log), "PREFETCH_DONE": str(logs / "done.log")}
out = self.run_program("list", top, "threads", program=self.other, env=env)
self.assertEqual(["a,b,c,f.txt", "1"], out)
self.assertFalse(log.exists())
self.run_program("thread", "list", top, "await", 3, program=self.other, env=env)
self.assertEqual(sorted(str(top / d) for d in ("a", "b", "c")), sorted(log.read_text().splitlines()))
def test_prefetching_can_be_turned_off(self):
top = self.cold_tree(self.lib.parent)
out, off = self.prefetched("list", top, "threads", program=self.other, env={"DD_NO_DIR_PREFETCH": "1"})
_, on = self.prefetched("list", top, "await", 3, program=self.other)
self.assertEqual(["a,b,c,f.txt", "2"], out)
self.assertEqual([], off)
self.assertEqual(sorted(str(top / d) for d in ("a", "b", "c")), on)
if __name__ == "__main__":
unittest.main()