/* * Vfs.cpp * Virtual File System with numerical logical drive identifiers * Copyright (c) 2025 Daniel Hammer */ #include "Vfs.hpp" #include #include #include namespace Fs::Vfs { static FsDriver* driveTable[MaxDrives]; static bool driveActive[MaxDrives]; static uint32_t driveGeneration[MaxDrives]; static bool initialized = false; // Calls in flight per drive slot. A dispatch pins its drive (under // tableLock) for the duration of the driver call, so UnregisterDrive can // tell when nothing is still inside a driver it is about to free. static uint32_t driveRefs[MaxDrives]; // Protects the drive table, generations and pin counts. Never held across // a driver call. static kcp::Mutex tableLock; // Serializes every call into the ordinary (non-concurrent) drivers, which // share block devices and scratch state and rely on one call at a time. // Drivers that set FsDriver::concurrent (network / userspace filesystems) // are dispatched outside it: their calls block on a remote peer, and a // stalled server must not freeze the local disks. static kcp::Mutex localLock; // A pinned driver: valid between Pin* and Unpin. struct Pinned { FsDriver* driver = nullptr; int drive = -1; }; static void EnterDriver(Pinned& pin, int drive, FsDriver* driver) { driveRefs[drive]++; pin.driver = driver; pin.drive = drive; tableLock.Release(); if (!driver->concurrent) localLock.Acquire(); } static void Unpin(Pinned& pin) { if (pin.driver == nullptr) return; if (!pin.driver->concurrent) localLock.Release(); tableLock.Acquire(); driveRefs[pin.drive]--; tableLock.Release(); pin.driver = nullptr; } // Upper bound on digits in a drive number. Without it the accumulator in // ParsePath overflows on a long digit run and wraps into a valid drive -- // "4294967296:/x" would otherwise resolve to drive 0. static constexpr int MaxDriveDigits = 4; // Parse "N:/path" into drive number and local path. // Returns true on success, sets outDrive and outPath. static bool ParsePath(const char* path, int& outDrive, const char*& outPath) { if (path == nullptr) return false; // Parse decimal drive number before ':' int drive = 0; int i = 0; int digits = 0; while (path[i] >= '0' && path[i] <= '9') { if (++digits > MaxDriveDigits) return false; drive = drive * 10 + (path[i] - '0'); i++; } if (digits == 0) return false; if (path[i] != ':') return false; // Everything after "N:" is the local path outDrive = drive; outPath = &path[i + 1]; return true; } // Resolve a drive number to its driver, or nullptr if the slot is out of // range, unregistered, or empty. Caller must hold tableLock; to call into // the driver, pin it (PinDrive / PinFile) instead. static FsDriver* DriverForLocked(int driveNumber) { if (driveNumber < 0 || driveNumber >= MaxDrives) return nullptr; if (!driveActive[driveNumber]) return nullptr; return driveTable[driveNumber]; } // As DriverForLocked, but for an already-open handle: also rejects handles // whose generation stamp is stale (the drive was unmounted and reused). static FsDriver* DriverForFileLocked(const BackendFile& file) { if (file.localHandle < 0) return nullptr; FsDriver* driver = DriverForLocked(file.driveNumber); if (driver == nullptr) return nullptr; if (file.generation != driveGeneration[file.driveNumber]) return nullptr; return driver; } static void BumpDriveGeneration(int driveNumber) { driveGeneration[driveNumber]++; if (driveGeneration[driveNumber] == 0) { driveGeneration[driveNumber] = 1; } } // Pin the driver of a drive for one call. Returns false (nothing pinned) // when the drive is not mounted. outGeneration, when given, receives the // generation the pin was taken under. static bool PinDrive(int driveNumber, Pinned& pin, uint32_t* outGeneration = nullptr) { tableLock.Acquire(); FsDriver* driver = DriverForLocked(driveNumber); if (driver == nullptr) { tableLock.Release(); return false; } if (outGeneration != nullptr) *outGeneration = driveGeneration[driveNumber]; EnterDriver(pin, driveNumber, driver); return true; } static bool PinFile(const BackendFile& file, Pinned& pin) { tableLock.Acquire(); FsDriver* driver = DriverForFileLocked(file); if (driver == nullptr) { tableLock.Release(); return false; } EnterDriver(pin, file.driveNumber, driver); return true; } void Initialize() { for (int i = 0; i < MaxDrives; i++) { driveRefs[i] = 0; driveTable[i] = nullptr; driveActive[i] = false; driveGeneration[i] = 1; } initialized = true; Kt::KernelLogStream(Kt::OK, "VFS") << "Initialized (" << MaxDrives << " drives)"; } bool IsInitialized() { return initialized; } int RegisterDrive(int driveNumber, FsDriver* driver) { if (driveNumber < 0 || driveNumber >= MaxDrives) return -1; if (driver == nullptr) return -1; if (!initialized) return -1; tableLock.Acquire(); if (driveActive[driveNumber]) { tableLock.Release(); return -1; } driveTable[driveNumber] = driver; BumpDriveGeneration(driveNumber); driveActive[driveNumber] = true; tableLock.Release(); Kt::KernelLogStream(Kt::OK, "VFS") << "Registered drive " << driveNumber; return 0; } int UnregisterDrive(int driveNumber) { if (!initialized) return -1; if (driveNumber < 0 || driveNumber >= MaxDrives) return -1; tableLock.Acquire(); if (!driveActive[driveNumber]) { tableLock.Release(); return -1; } driveActive[driveNumber] = false; FsDriver* driver = driveTable[driveNumber]; driveTable[driveNumber] = nullptr; BumpDriveGeneration(driveNumber); tableLock.Release(); // Unmount frees the FsDriver itself, so wait until every call that // pinned it before the slot was deactivated has returned. Such calls // are bounded local I/O (concurrent drivers own their storage and // leave Unmount null), so this is a short spin, as the old single // dispatch lock was. if (driver != nullptr && driver->Unmount != nullptr) { for (;;) { tableLock.Acquire(); uint32_t refs = driveRefs[driveNumber]; tableLock.Release(); if (refs == 0) break; Arch::Pause(); } driver->Unmount(driver->ctx); } Kt::KernelLogStream(Kt::OK, "VFS") << "Unregistered drive " << driveNumber; return 0; } bool IsDriveRegistered(int driveNumber) { if (driveNumber < 0 || driveNumber >= MaxDrives) return false; tableLock.Acquire(); bool registered = driveActive[driveNumber]; tableLock.Release(); return registered; } uint32_t DrivePinCount(int driveNumber) { if (driveNumber < 0 || driveNumber >= MaxDrives) return 0; tableLock.Acquire(); uint32_t refs = driveRefs[driveNumber]; tableLock.Release(); return refs; } int FindLowestAvailableDrive(int firstDrive) { if (!initialized) return -1; if (firstDrive < 0) firstDrive = 0; tableLock.Acquire(); for (int i = firstDrive; i < MaxDrives; i++) { if (!driveActive[i]) { tableLock.Release(); return i; } } tableLock.Release(); return -1; } int OpenBackendFile(const char* path, BackendFile& outFile) { outFile.driveNumber = -1; outFile.localHandle = -1; outFile.generation = 0; int drive; const char* localPath; if (!ParsePath(path, drive, localPath)) return -1; Pinned pin; uint32_t generation = 0; if (!PinDrive(drive, pin, &generation)) return -1; FsDriver* driver = pin.driver; int localHandle = (driver->Open != nullptr) ? driver->Open(driver->ctx, localPath) : -1; Unpin(pin); if (localHandle < 0) return -1; outFile.driveNumber = drive; outFile.localHandle = localHandle; outFile.generation = generation; return 0; } int ReadBackendFile(const BackendFile& file, uint8_t* buffer, uint64_t offset, uint64_t size) { Pinned pin; if (!PinFile(file, pin)) return -1; FsDriver* driver = pin.driver; int result = (driver->Read != nullptr) ? driver->Read(driver->ctx, file.localHandle, buffer, offset, size) : -1; Unpin(pin); return result; } uint64_t GetBackendFileSize(const BackendFile& file) { Pinned pin; if (!PinFile(file, pin)) return 0; FsDriver* driver = pin.driver; uint64_t result = (driver->GetSize != nullptr) ? driver->GetSize(driver->ctx, file.localHandle) : 0; Unpin(pin); return result; } bool BackendFileCanWrite(const BackendFile& file) { tableLock.Acquire(); FsDriver* driver = DriverForFileLocked(file); bool canWrite = driver != nullptr && driver->Write != nullptr; tableLock.Release(); return canWrite; } void CloseBackendFile(BackendFile& file) { Pinned pin; if (PinFile(file, pin)) { FsDriver* driver = pin.driver; if (driver->Close != nullptr) driver->Close(driver->ctx, file.localHandle); Unpin(pin); } file.driveNumber = -1; file.localHandle = -1; file.generation = 0; } int WriteBackendFile(const BackendFile& file, const uint8_t* buffer, uint64_t offset, uint64_t size) { Pinned pin; if (!PinFile(file, pin)) return -1; FsDriver* driver = pin.driver; int result = (driver->Write != nullptr) ? driver->Write(driver->ctx, file.localHandle, buffer, offset, size) : -1; Unpin(pin); return result; } int CreateBackendFile(const char* path, BackendFile& outFile) { outFile.driveNumber = -1; outFile.localHandle = -1; outFile.generation = 0; int drive; const char* localPath; if (!ParsePath(path, drive, localPath)) return -1; Pinned pin; uint32_t generation = 0; if (!PinDrive(drive, pin, &generation)) return -1; FsDriver* driver = pin.driver; int localHandle = (driver->Create != nullptr) ? driver->Create(driver->ctx, localPath) : -1; Unpin(pin); if (localHandle < 0) return -1; outFile.driveNumber = drive; outFile.localHandle = localHandle; outFile.generation = generation; return 0; } int VfsDelete(const char* path) { int drive; const char* localPath; if (!ParsePath(path, drive, localPath)) return -1; Pinned pin; if (!PinDrive(drive, pin)) return -1; FsDriver* driver = pin.driver; int result = (driver->Delete != nullptr) ? driver->Delete(driver->ctx, localPath) : -1; Unpin(pin); return result; } int VfsStat(const char* path, StatInfo& out) { int drive; const char* localPath; out = StatInfo{}; if (!ParsePath(path, drive, localPath)) return -1; Pinned pin; if (!PinDrive(drive, pin)) return -1; FsDriver* driver = pin.driver; int result = (driver->Stat != nullptr) ? driver->Stat(driver->ctx, localPath, &out) : -1; Unpin(pin); return result; } int VfsSetTimes(const char* path, int64_t atime, int64_t mtime) { int drive; const char* localPath; if (!ParsePath(path, drive, localPath)) return -1; Pinned pin; if (!PinDrive(drive, pin)) return -2; FsDriver* driver = pin.driver; int result = (driver->SetTimes != nullptr) ? driver->SetTimes(driver->ctx, localPath, atime, mtime) : -2; Unpin(pin); return result; } int VfsMkdir(const char* path) { int drive; const char* localPath; if (!ParsePath(path, drive, localPath)) return -1; Pinned pin; if (!PinDrive(drive, pin)) return -1; FsDriver* driver = pin.driver; int result = (driver->Mkdir != nullptr) ? driver->Mkdir(driver->ctx, localPath) : -1; Unpin(pin); return result; } int VfsDriveList(int* outDrives, int maxEntries) { if (outDrives == nullptr || maxEntries <= 0) return 0; tableLock.Acquire(); int count = 0; for (int i = 0; i < MaxDrives && count < maxEntries; i++) { if (driveActive[i]) { outDrives[count++] = i; } } tableLock.Release(); return count; } static int CopyDriveString(int driveNumber, const char* (*FsDriver::*hook)(void*), char* out, int maxLen) { if (out == nullptr || maxLen <= 0) return -1; out[0] = '\0'; Pinned pin; if (!PinDrive(driveNumber, pin)) return -1; FsDriver* driver = pin.driver; if (driver->*hook == nullptr) { Unpin(pin); return 0; } const char* value = (driver->*hook)(driver->ctx); if (value == nullptr || value[0] == '\0') { Unpin(pin); return 0; } int copied = 0; while (value[copied] != '\0' && copied < maxLen - 1) { out[copied] = value[copied]; copied++; } out[copied] = '\0'; Unpin(pin); return copied; } int VfsDriveKind(int driveNumber) { tableLock.Acquire(); FsDriver* driver = DriverForLocked(driveNumber); int kind = driver != nullptr ? (int)driver->kind : 0; tableLock.Release(); return kind; } int VfsDriveLabel(int driveNumber, char* outLabel, int maxLen) { return CopyDriveString(driveNumber, &FsDriver::GetLabel, outLabel, maxLen); } int VfsDriveFsType(int driveNumber, char* outType, int maxLen) { return CopyDriveString(driveNumber, &FsDriver::GetFsType, outType, maxLen); } int VfsGrow(int driveNumber, uint64_t partSectors, bool apply, GrowStatus* out) { Pinned pin; if (!PinDrive(driveNumber, pin)) return -2; FsDriver* driver = pin.driver; int result = (driver->Grow != nullptr) ? driver->Grow(driver->ctx, partSectors, apply, out) : -2; Unpin(pin); return result; } int VfsRename(const char* oldPath, const char* newPath) { int oldDrive, newDrive; const char* oldLocal; const char* newLocal; if (!ParsePath(oldPath, oldDrive, oldLocal)) return -1; if (!ParsePath(newPath, newDrive, newLocal)) return -1; // Cross-drive rename not supported if (oldDrive != newDrive) return -1; Pinned pin; if (!PinDrive(oldDrive, pin)) return -1; FsDriver* driver = pin.driver; int result = (driver->Rename != nullptr) ? driver->Rename(driver->ctx, oldLocal, newLocal) : -1; Unpin(pin); return result; } int VfsReadDir(const char* path, const char** outNames, int maxEntries) { return VfsReadDirAt(path, outNames, maxEntries, 0); } int VfsReadDirAt(const char* path, const char** outNames, int maxEntries, int startIndex) { int drive; const char* localPath; if (startIndex < 0) return -1; if (!ParsePath(path, drive, localPath)) return -1; Pinned pin; if (!PinDrive(drive, pin)) return -1; FsDriver* driver = pin.driver; int result; if (driver->ReadDirAt) { result = driver->ReadDirAt(driver->ctx, localPath, outNames, maxEntries, startIndex); } else if (driver->ReadDir) { // Driver without pagination support: only the first page is reachable. result = (startIndex == 0) ? driver->ReadDir(driver->ctx, localPath, outNames, maxEntries) : 0; } else { result = -1; } Unpin(pin); return result; } }