diff --git a/runtime/include/switch_sd_list.h b/runtime/include/switch_sd_list.h new file mode 100644 index 0000000..89a936b --- /dev/null +++ b/runtime/include/switch_sd_list.h @@ -0,0 +1,34 @@ +#pragma once + +// Lists a folder on the Switch's SD card through the card's own directory reads, which carry every +// file's size. Listing with std::filesystem costs a stat per file on top of the directory read, and +// on the Switch each stat is several file system requests (the entry's type, then open, size and +// close): for Retro Rewind's pack, thousands of files read at every start (DVDInit's disc index). + +#include +#include +#include + +namespace SwitchSdList { + +struct Entry { + std::string path; // the root, as given, joined with the names below it + bool directory = false; + uint64_t size = 0; // files only +}; + +// Calls `visit` for every entry under `root`, a folder before what is in it (the order of +// std::filesystem::recursive_directory_iterator). False, having visited nothing, when `root` is +// not an "sdmc:/" path or cannot be opened, or on any other platform: the caller lists it itself. +// A sub-folder that cannot be opened is left out. +bool List(const std::string& root, bool recursive, const std::function& visit); + +// What is at `path` on the SD card, from one listing of its folder, kept for the next lookup in +// that folder: Retro Rewind's XML names 152 single files across a few folders, each a stat (or +// two) before. Unknown when the listing has no entry spelled so (names on the card ignore case), +// `path` is not an "sdmc:/" path, its folder cannot be listed, or on any other platform: the caller +// stats it itself. For boot-time scans of files nothing writes meanwhile. +enum class Found { Unknown, File, Directory }; +Found Lookup(const std::string& path, uint64_t* size = nullptr); + +} // namespace SwitchSdList diff --git a/runtime/src/hle/storage/dvd.cpp b/runtime/src/hle/storage/dvd.cpp index 14b6c9d..68bf030 100644 --- a/runtime/src/hle/storage/dvd.cpp +++ b/runtime/src/hle/storage/dvd.cpp @@ -15,6 +15,7 @@ extern "C" void GxNotifyGuestRamDmaWrite(uint32_t addr, uint32_t size); #include "runtime_log.h" #include "runtime_product.h" #include "sound_core.h" +#include "switch_sd_list.h" #include #include @@ -494,22 +495,65 @@ static bool DvdEntryExists(const std::string& dvdPath) { g_pathToEntry.end(); } -// Walk `root` and hand every entry to `visit`. Uses the error_code iterator forms so an +// One file or folder found by WalkDirectory, with the file's size already known. +struct WalkEntry { + fs::path path; + bool isFile = false; + std::uintmax_t size = 0; +}; + +// Walk `root` and hand every file and folder to `visit`. Uses the error_code iterator forms so an // unreadable entry doesn't abort the rest of the overlay. `announceErrors` keeps the // disc-index scan noisy and the by-name mapping quiet, matching each caller's old behavior. +// A file whose size can't be read is skipped (announced the same way). +// +// On the Switch's SD card the listing comes from the card's own directory reads, which carry the +// sizes (switch_sd_list.h): no stat per file, which was most of the disc index's time for Retro +// Rewind's thousands of files. template static void WalkDirectory(const fs::path& root, bool recursive, bool announceErrors, Visit&& visit) { - std::error_code ec; - // Each entry is a few SD card reads, and the boot-time scans run to thousands of entries: // keep the startup cover on screen moving meanwhile. + WalkEntry walked; + const bool listed = SwitchSdList::List(root.string(), recursive, [&](const SwitchSdList::Entry& entry) { + walked.path = entry.path; + walked.isFile = !entry.directory; + walked.size = entry.size; + visit(walked); + VI_HLE_PresentBootFrame(); + }); + if (listed) { + return; + } + + std::error_code ec; + const auto toWalkEntry = [&](const fs::directory_entry& entry) -> bool { + std::error_code entryEc; + walked.path = entry.path(); + walked.isFile = entry.is_regular_file(entryEc) && !entryEc; + walked.size = 0; + if (walked.isFile) { + walked.size = fs::file_size(entry.path(), entryEc); + if (entryEc) { + if (announceErrors) { + RT_LOG(RT_TAG_DVD) << "WARNING: skipping " << entry.path().string() << ": " + << entryEc.message() << std::endl; + } + return false; + } + } + return true; + }; + if (!recursive) { for (const auto& entry : fs::directory_iterator( root, fs::directory_options::skip_permission_denied, ec)) { if (ec) { break; } - visit(entry); + if (toWalkEntry(entry)) { + visit(walked); + } VI_HLE_PresentBootFrame(); } return; @@ -535,11 +579,15 @@ static void WalkDirectory(const fs::path& root, bool recursive, bool announceErr << ec.message() << std::endl; return; } - visit(entry); + if (toWalkEntry(entry)) { + visit(walked); + } return; } - visit(entry); + if (toWalkEntry(entry)) { + visit(walked); + } VI_HLE_PresentBootFrame(); } } @@ -554,23 +602,15 @@ static void ScanDirectory(const fs::path& root, const std::string& virtualPrefix return; } - const auto registerEntry = [&](const fs::directory_entry& entry) { - std::error_code entryEc; - if (!entry.is_regular_file(entryEc) || entryEc) { - return; - } - - const std::uintmax_t size = fs::file_size(entry.path(), entryEc); - if (entryEc) { - RT_LOG(RT_TAG_DVD) << "WARNING: skipping " << entry.path().string() << ": " - << entryEc.message() << std::endl; + const auto registerEntry = [&](const WalkEntry& entry) { + if (!entry.isFile) { return; } // Lexical, not fs::relative: every entry path is `root` plus components, and fs::relative // canonicalizes through the real filesystem, which fails for device-prefixed paths like // Switch's "sdmc:/..." and silently dropped every disc file. - const fs::path relative = entry.path().lexically_relative(root); + const fs::path relative = entry.path.lexically_relative(root); if (relative.empty()) { return; } @@ -583,7 +623,7 @@ static void ScanDirectory(const fs::path& root, const std::string& virtualPrefix if (!addNewFiles && !DvdEntryExists(dvdPath)) { return; } - RegisterFileEntry(std::move(dvdPath), entry.path(), static_cast(size)); + RegisterFileEntry(std::move(dvdPath), entry.path, static_cast(entry.size)); }; WalkDirectory(root, recursive, /*announceErrors=*/true, registerEntry); @@ -608,23 +648,18 @@ static void ApplyFolderByNameMapping(const RuntimeRiivolution::Mapping& mapping) } uint32_t replaced = 0; - const auto applyEntry = [&](const fs::directory_entry& entry) { - std::error_code entryEc; - if (!entry.is_regular_file(entryEc) || entryEc) { + const auto applyEntry = [&](const WalkEntry& entry) { + if (!entry.isFile) { return; } - std::string name = entry.path().filename().string(); + std::string name = entry.path.filename().string(); RuntimeHle::LowerInPlace(name); const auto matches = discPathsByName.find(name); if (matches == discPathsByName.end()) { return; } - const std::uintmax_t size = fs::file_size(entry.path(), entryEc); - if (entryEc) { - return; - } for (const std::string& dvdPath : matches->second) { - RegisterFileEntry(dvdPath, entry.path(), static_cast(size)); + RegisterFileEntry(dvdPath, entry.path, static_cast(entry.size)); ++replaced; } }; @@ -662,7 +697,11 @@ static void ScanOverlayRoot(const RuntimeRiivolution::Overlay& overlay) { break; } std::error_code ec; - const std::uintmax_t size = fs::file_size(mapping.hostPath, ec); + uint64_t listedSize = 0; + const std::uintmax_t size = + SwitchSdList::Lookup(mapping.hostPath.string(), &listedSize) == SwitchSdList::Found::File + ? listedSize + : fs::file_size(mapping.hostPath, ec); if (!ec) { RegisterFileEntry(mapping.discPath, mapping.hostPath, static_cast(size)); } diff --git a/runtime/src/hle/storage/riivolution.cpp b/runtime/src/hle/storage/riivolution.cpp index cfcba9d..94c3728 100644 --- a/runtime/src/hle/storage/riivolution.cpp +++ b/runtime/src/hle/storage/riivolution.cpp @@ -19,6 +19,7 @@ #include "runtime_log.h" #include "runtime_product.h" #include "switch_launcher.h" +#include "switch_sd_list.h" #include #include @@ -239,7 +240,9 @@ void RiivoCollectMappings(const RiivolutionContract::Patch& patch, const std::st continue; } const fs::path hostFile(*resolved); - if (!fs::is_regular_file(hostFile, ec)) { + const SwitchSdList::Found found = SwitchSdList::Lookup(hostFile.string()); + if (found == SwitchSdList::Found::Directory || + (found == SwitchSdList::Found::Unknown && !fs::is_regular_file(hostFile, ec))) { ++set.skippedExternals; continue; } @@ -255,7 +258,9 @@ void RiivoCollectMappings(const RiivolutionContract::Patch& patch, const std::st continue; } const fs::path hostFolder(*resolved); - if (!fs::is_directory(hostFolder, ec)) { + const SwitchSdList::Found found = SwitchSdList::Lookup(hostFolder.string()); + if (found == SwitchSdList::Found::File || + (found == SwitchSdList::Found::Unknown && !fs::is_directory(hostFolder, ec))) { ++set.skippedExternals; continue; } diff --git a/runtime/src/switch_sd_list.cpp b/runtime/src/switch_sd_list.cpp new file mode 100644 index 0000000..6e08488 --- /dev/null +++ b/runtime/src/switch_sd_list.cpp @@ -0,0 +1,151 @@ +#include "switch_sd_list.h" + +#if defined(__SWITCH__) +#include + +#include +#include +#include +#include +#endif + +namespace SwitchSdList { + +#if defined(__SWITCH__) +namespace { + +constexpr const char* kPrefix = "sdmc:"; + +// One folder's entries, read before descending so only one directory handle is open at a time. +bool ReadFolder(FsFileSystem* fs, const std::string& path, std::vector& out) { + char fsPath[FS_MAX_PATH]; + if (path.size() >= sizeof(fsPath)) { + return false; + } + std::memcpy(fsPath, path.c_str(), path.size() + 1); + FsDir dir; + if (R_FAILED(fsFsOpenDirectory(fs, fsPath, FsDirOpenMode_ReadDirs | FsDirOpenMode_ReadFiles, &dir))) { + return false; + } + out.clear(); + FsDirectoryEntry batch[64]; + for (;;) { + s64 count = 0; + if (R_FAILED(fsDirRead(&dir, &count, sizeof(batch) / sizeof(batch[0]), batch)) || count <= 0) { + break; + } + out.insert(out.end(), batch, batch + count); + } + fsDirClose(&dir); + return true; +} + +// Joins as std::filesystem::path's operator/ does, so entries are spelled as directory_iterator +// spells them (the caller takes paths relative to the root it gave). +std::string Join(const std::string& dir, const char* name) { + return dir.empty() || dir.back() == '/' ? dir + name : dir + "/" + name; +} + +// `entries` is the folder at `fsPath` (`shown` as the caller spells it), already read. +void Walk(FsFileSystem* fs, const std::string& fsPath, const std::string& shown, + const std::vector& entries, bool recursive, const std::function& visit) { + Entry entry; + for (const FsDirectoryEntry& e : entries) { + const std::string child = Join(fsPath, e.name); + entry.path = Join(shown, e.name); + entry.directory = e.type == FsDirEntryType_Dir; + entry.size = entry.directory ? 0 : static_cast(e.file_size); + visit(entry); + std::vector children; + if (entry.directory && recursive && ReadFolder(fs, child, children)) { + const std::string childShown = entry.path; + Walk(fs, child, childShown, children, recursive, visit); + } + } +} + +} // namespace + +bool List(const std::string& root, bool recursive, const std::function& visit) { + if (root.compare(0, std::strlen(kPrefix), kPrefix) != 0) { + return false; + } + FsFileSystem* fs = fsdevGetDeviceFileSystem("sdmc"); + if (fs == nullptr) { + return false; + } + std::string fsPath = root.substr(std::strlen(kPrefix)); + if (fsPath.empty() || fsPath.front() != '/') { + fsPath.insert(fsPath.begin(), '/'); + } + while (fsPath.size() > 1 && fsPath.back() == '/') { + fsPath.pop_back(); + } + std::vector entries; + if (!ReadFolder(fs, fsPath, entries)) { + return false; + } + Walk(fs, fsPath, root, entries, recursive, visit); + return true; +} + +Found Lookup(const std::string& path, uint64_t* size) { + if (path.compare(0, std::strlen(kPrefix), kPrefix) != 0) { + return Found::Unknown; + } + std::string fsPath = path.substr(std::strlen(kPrefix)); + while (fsPath.size() > 1 && fsPath.back() == '/') { + fsPath.pop_back(); + } + const size_t slash = fsPath.rfind('/'); + if (slash == std::string::npos || slash + 1 >= fsPath.size()) { + return Found::Unknown; + } + const std::string folder = slash == 0 ? "/" : fsPath.substr(0, slash); + const std::string name = fsPath.substr(slash + 1); + + // The SD card's names are case-insensitive, its listings are not: keep the case as listed and + // let a miss fall back to the caller's own stat. + struct Folder { + bool listed = false; + std::unordered_map entries; + }; + static std::mutex mutex; + static std::unordered_map folders; + std::lock_guard lock(mutex); + Folder& cached = folders[folder]; + if (!cached.listed) { + FsFileSystem* fs = fsdevGetDeviceFileSystem("sdmc"); + std::vector entries; + if (fs == nullptr || !ReadFolder(fs, folder, entries)) { + folders.erase(folder); + return Found::Unknown; + } + for (const FsDirectoryEntry& e : entries) { + cached.entries.emplace(e.name, e); + } + cached.listed = true; + } + const auto it = cached.entries.find(name); + if (it == cached.entries.end()) { + return Found::Unknown; + } + if (it->second.type == FsDirEntryType_Dir) { + return Found::Directory; + } + if (size != nullptr) { + *size = static_cast(it->second.file_size); + } + return Found::File; +} +#else +bool List(const std::string&, bool, const std::function&) { + return false; +} + +Found Lookup(const std::string&, uint64_t*) { + return Found::Unknown; +} +#endif + +} // namespace SwitchSdList