feat: add SMB networking support

This commit is contained in:
daniel committed 2026-11-22 08:43:18 +01:00
1 parent 6665750528
commit 2af2e90606
55 files changed
+7456 -158

No files matched your search

+1 -1
View File
@@ -12,4 +12,4 @@
#pragma once
#define MONTAUK_BUILD_NUMBER 132
#define MONTAUK_BUILD_NUMBER 137
+2
View File
@@ -212,6 +212,8 @@ namespace montauk::abi {
}
static int Sys_DriveKind(int driveNumber) {
int kind = Fs::Vfs::VfsDriveKind(driveNumber);
if (kind != 0) return kind; // provider-backed (network) drive
int blockDev = Fs::FsProbe::GetBlockDeviceForDrive(driveNumber);
if (blockDev < 0) return 0;
auto* dev = Drivers::Storage::GetBlockDevice(blockDev);
+3 -1
View File
@@ -77,8 +77,10 @@ namespace montauk::abi {
Fs::Vfs::VfsDriveLabel(v.drive, v.label, sizeof(v.label));
Fs::Vfs::VfsDriveFsType(v.drive, v.fsType, sizeof(v.fsType));
v.kind = (uint32_t)Fs::Vfs::VfsDriveKind(v.drive);
v.partIndex = Fs::FsProbe::GetPartitionForDrive(v.drive);
if (v.partIndex < 0) continue; // ramdisk: no backing partition
if (v.partIndex < 0) continue; // ramdisk / network: no backing partition
auto* part = Drivers::Storage::Gpt::GetPartition(v.partIndex);
if (part == nullptr) continue;
+21
View File
@@ -39,6 +39,7 @@
#include "CrashReportSyscall.hpp" // SYS_CRASH_REPORT
#include "Clipboard.hpp" // SYS_CLIPBOARD_* (text and multi-format)
#include "UserMemory.hpp"
#include "UserFsSyscall.hpp" // SYS_USERFS_MOUNT, SYS_USERFS_RECV, SYS_USERFS_REPLY, SYS_USERFS_UNMOUNT, SYS_USERFS_INFO
namespace montauk::abi {
@@ -456,6 +457,26 @@ namespace montauk::abi {
case SYS_FS_SYNC:
if (!Sched::Consent::Require(CAP_STORAGE_ADMIN)) return CapabilityDenied;
return Sys_FsSync();
case SYS_USERFS_MOUNT:
if (!UserMemory::Readable<UserFsMountParams>(frame->arg1)) return BadPointer;
return Sys_UserFsMount((const UserFsMountParams*)frame->arg1);
case SYS_USERFS_RECV:
if (!UserMemory::Writable<UserFsRequest>(frame->arg2)) return BadPointer;
if (frame->arg4 > 0x1000000ULL) return InvalidArgument;
if (!UserMemory::Range(frame->arg3, frame->arg4, true)) return BadPointer;
return Sys_UserFsRecv((int)frame->arg1, (UserFsRequest*)frame->arg2,
(uint8_t*)frame->arg3, (uint32_t)frame->arg4, frame->arg5);
case SYS_USERFS_REPLY:
if (frame->arg5 > USERFS_MAX_DATA) return InvalidArgument;
if (frame->arg5 > 0 && !UserMemory::Range(frame->arg4, frame->arg5, false)) return BadPointer;
return Sys_UserFsReply((int)frame->arg1, frame->arg2, (int64_t)frame->arg3,
frame->arg5 > 0 ? (const uint8_t*)frame->arg4 : nullptr,
(uint32_t)frame->arg5);
case SYS_USERFS_UNMOUNT:
return Sys_UserFsUnmount((int)frame->arg1);
case SYS_USERFS_INFO:
if (!UserMemory::Writable<UserFsInfo>(frame->arg2)) return BadPointer;
return Sys_UserFsInfo((int)frame->arg1, (UserFsInfo*)frame->arg2);
case SYS_FS_GROW:
if (!Sched::Consent::Require(CAP_STORAGE_ADMIN)) return CapabilityDenied;
if (!UserMemory::Range(frame->arg2, sizeof(FsGrowStatus), true)) return BadPointer;
+73 -1
View File
@@ -408,6 +408,17 @@ namespace montauk::abi {
/* Time.hpp -- wall clock as UTC unix seconds (SYS_GETTIME is local time). */
static constexpr uint64_t SYS_GETUNIXTIME = 209; // () -> seconds
/* UserFsSyscall.hpp -- userspace filesystem providers. A provider process
mounts a drive and then serves the VFS calls other processes make on it:
it receives each as a UserFsRequest and answers with a result and
optional data. The drive disappears when the provider unmounts or exits.
Used by smbfs.elf to expose SMB shares as ordinary drives. */
static constexpr uint64_t SYS_USERFS_MOUNT = 210; // (const UserFsMountParams*) -> drive / status
static constexpr uint64_t SYS_USERFS_RECV = 211; // (drive, UserFsRequest*, data, dataMax, timeoutMs) -> 1 / 0 / status
static constexpr uint64_t SYS_USERFS_REPLY = 212; // (drive, id, result, data, len) -> status
static constexpr uint64_t SYS_USERFS_UNMOUNT = 213; // (drive) -> status; non-providers request an eject
static constexpr uint64_t SYS_USERFS_INFO = 214; // (drive, UserFsInfo*) -> status
/* Kernel-owned process capabilities. User identities may namespace
per-user resources, but never participate in authorization decisions. */
static constexpr uint64_t CAP_PROCESS_ADMIN = 1ULL << 0;
@@ -974,7 +985,7 @@ namespace montauk::abi {
int32_t drive; // VFS drive number ("N:/")
int32_t blockDev; // backing block device index, -1 if none
int32_t partIndex; // global GPT partition index, -1 if none
uint32_t kind; // BlockDeviceKind: 0=none/ramdisk, 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC
uint32_t kind; // BlockDeviceKind: 0=none/ramdisk, 1=SATA, 2=SATAPI, 3=NVMe, 4=USB MSC, 5=SD, 6=network (DRIVE_KIND_NETWORK)
uint64_t startLba; // partition start LBA, 0 if none
uint64_t sectorCount; // partition length in sectors, 0 if none
uint32_t sectorSize; // logical sector size in bytes, 0 if none
@@ -1013,6 +1024,67 @@ namespace montauk::abi {
uint32_t stepsTotal;
};
/* ---- Userspace filesystem providers (SYS_USERFS_*) ---- */
/* VolInfo::kind / SYS_DRIVEKIND value of a provider-backed drive. */
static constexpr uint32_t DRIVE_KIND_NETWORK = 6;
/* Largest data payload of one request or reply. The kernel splits larger
reads and writes; SYS_USERFS_RECV needs a buffer at least this big. */
static constexpr uint32_t USERFS_MAX_DATA = 65536;
/* UserFsRequest::op. Unless noted, the provider replies with result >= 0
on success or a negative StatusCodes value. */
static constexpr uint32_t USERFS_OP_OPEN = 1; // path -> provider file handle (>= 0)
static constexpr uint32_t USERFS_OP_CREATE = 2; // path (create or truncate) -> provider file handle
static constexpr uint32_t USERFS_OP_CLOSE = 3; // handle; no reply expected (id == 0)
static constexpr uint32_t USERFS_OP_READ = 4; // handle, offset, size -> bytes read, reply data
static constexpr uint32_t USERFS_OP_WRITE = 5; // handle, offset, size, request data -> bytes written
static constexpr uint32_t USERFS_OP_GETSIZE = 6; // handle -> size in bytes
static constexpr uint32_t USERFS_OP_READDIR = 7; // path, offset = first index, size = max entries
// -> count; reply data = NUL-terminated names,
// directories with a trailing '/'
static constexpr uint32_t USERFS_OP_STAT = 8; // path -> 0, reply data = FileStat
static constexpr uint32_t USERFS_OP_DELETE = 9; // path (file or empty directory)
static constexpr uint32_t USERFS_OP_MKDIR = 10; // path
static constexpr uint32_t USERFS_OP_RENAME = 11; // path -> path2
static constexpr uint32_t USERFS_OP_SETTIMES = 12; // path, atime, mtime
static constexpr uint32_t USERFS_OP_UNMOUNT = 13; // eject requested: flush, then unmount or exit; no reply
struct UserFsMountParams {
char label[36]; // volume label shown for the drive
char fsType[12]; // short type name, e.g. "smb"
char source[128]; // what is mounted, e.g. "smb://nas/media"
uint32_t flags; // USERFS_MOUNT_*
uint32_t _pad0;
};
static constexpr uint32_t USERFS_MOUNT_READONLY = 1u << 0;
struct UserFsRequest {
uint64_t id; // pass back to SYS_USERFS_REPLY; 0 = no reply expected
uint32_t op; // USERFS_OP_*
int32_t handle; // provider file handle (CLOSE/READ/WRITE/GETSIZE)
uint64_t offset;
uint64_t size;
int64_t atime;
int64_t mtime;
uint32_t dataLen; // bytes of request data copied to the RECV buffer
uint32_t replyMax; // most reply data the kernel will accept
char path[256]; // drive-local path, starts with '/'
char path2[256];
};
struct UserFsInfo {
int32_t drive;
int32_t providerPid;
uint32_t flags;
uint32_t _pad0;
char label[36];
char fsType[12];
char source[128];
};
struct ProcInfo {
int32_t pid;
int32_t parentPid;
+41
View File
@@ -0,0 +1,41 @@
/*
* UserFsSyscall.hpp
* SYS_USERFS_* syscalls: userspace filesystem providers
* Copyright (c) 2026 Daniel Hammer
*/
#pragma once
#include <Fs/UserFs.hpp>
#include "Syscall.hpp"
namespace montauk::abi {
static int64_t Sys_UserFsMount(const UserFsMountParams* params) {
// Copy first: the strings must be terminated and stable while parsed.
UserFsMountParams local = *params;
local.label[sizeof(local.label) - 1] = '\0';
local.fsType[sizeof(local.fsType) - 1] = '\0';
local.source[sizeof(local.source) - 1] = '\0';
return Fs::UserFs::Mount(&local);
}
static int64_t Sys_UserFsRecv(int drive, UserFsRequest* out, uint8_t* data,
uint32_t dataMax, uint64_t timeoutMs) {
return Fs::UserFs::Recv(drive, out, data, dataMax, timeoutMs);
}
static int64_t Sys_UserFsReply(int drive, uint64_t id, int64_t result,
const uint8_t* data, uint32_t len) {
return Fs::UserFs::Reply(drive, id, result, data, len);
}
static int64_t Sys_UserFsUnmount(int drive) {
return Fs::UserFs::Unmount(drive);
}
static int64_t Sys_UserFsInfo(int drive, UserFsInfo* out) {
return Fs::UserFs::Info(drive, out);
}
}
+755
View File
@@ -0,0 +1,755 @@
/*
* UserFs.cpp
* Userspace filesystem providers: VFS drives served by a process
* Copyright (c) 2026 Daniel Hammer
*/
#include "UserFs.hpp"
#include "Vfs.hpp"
#include <Common/StatusCodes.hpp>
#include <CppLib/Spinlock.hpp>
#include <Libraries/Memory.hpp>
#include <Libraries/String.hpp>
#include <Sched/Scheduler.hpp>
#include <Terminal/Terminal.hpp>
#include <Timekeeping/Timer.hpp>
#include <Arch/Cpu.hpp>
namespace Fs::UserFs {
using montauk::abi::UserFsRequest;
using montauk::abi::UserFsMountParams;
using montauk::abi::UserFsInfo;
using montauk::abi::FileStat;
using montauk::abi::USERFS_MAX_DATA;
// Requests that may be queued or in service per mount; further callers
// wait for a slot.
static constexpr int MaxRequests = 16;
// Handles whose close has not been delivered to the provider yet.
static constexpr int CloseRingSize = 128;
// Per-thread buffers holding the names of a thread's last ReadDir.
static constexpr int NameSlots = 8;
static constexpr uint32_t NameBufSize = 4096;
// How long a caller waits for the provider before giving up. Providers
// must bound their own network waits below this.
static constexpr uint64_t RequestTimeoutMs = 45000;
enum ReqState : uint8_t { ReqFree = 0, ReqPending, ReqTaken, ReqDone };
struct MountState;
// One mounting of a slot. It is the FsDriver's ctx, so a call that the
// VFS dispatched before an unmount still holds the instance it was
// dispatched to and can tell that it is dead, even after the slot has
// been mounted again by another provider.
struct Instance {
MountState* mount;
bool dead;
};
struct Request {
ReqState state;
// The provider side is copying to or from `data` outside the lock; the
// waiter may not release the slot (and its buffer) until this clears.
bool busy;
UserFsRequest hdr;
Instance* inst; // mounting the request was made on
int ownerPid; // process of the waiting caller
uint8_t* data; // bounce buffer, owned by the waiting caller
uint32_t dataCap;
uint32_t replyLen;
int64_t result;
};
struct NameBuf {
int tid;
uint8_t* page;
};
struct MountState {
kcp::Spinlock lock;
bool active;
Instance* current; // live instance while active, else null
bool ejectRequested;
int ownerPid;
int ownerSession;
int drive;
uint32_t flags;
char label[36];
char fsType[12];
char source[128];
Vfs::FsDriver driver;
Request reqs[MaxRequests];
uint64_t nextId;
int32_t closeRing[CloseRingSize];
uint32_t closeHead;
uint32_t closeCount;
NameBuf names[NameSlots];
uint32_t nameCursor;
// Wake object for callers waiting for a free request slot.
uint8_t slotWait;
};
static MountState g_mounts[MaxMounts];
static kcp::Mutex g_mountsLock;
// Instances of unmounted drives, freed once no dispatched call can still
// hold them (g_mountsLock). If the list is full an instance is leaked,
// which costs a few bytes and nothing else.
static constexpr int MaxRetired = 64;
static Instance* g_retired[MaxRetired];
static bool CurrentKilled() {
auto* thr = Sched::GetCurrentThreadPtr();
return thr == nullptr || thr->killPending.load(std::memory_order_acquire);
}
static void CopyStr(char* dst, const char* src, int max) {
int i = 0;
if (src != nullptr) {
for (; i < max - 1 && src[i]; i++) dst[i] = src[i];
}
dst[i] = '\0';
}
static MountState* MountForDrive(int drive) {
if (drive < FirstDrive || drive >= FirstDrive + MaxMounts) return nullptr;
MountState* m = &g_mounts[drive - FirstDrive];
return m->active ? m : nullptr;
}
// ==========================================================================
// Caller side: queue a request and wait for the provider's answer
// ==========================================================================
// Release a request slot the caller gave up on or has consumed. Waits out
// a provider-side copy in progress so the bounce buffer is not freed under it.
static void ReleaseSlot(MountState* m, Request* req) {
for (;;) {
m->lock.Acquire();
if (!req->busy) break;
m->lock.Release();
Arch::Pause();
}
req->state = ReqFree;
req->hdr.id = 0;
req->inst = nullptr;
req->ownerPid = -1;
req->data = nullptr;
req->dataCap = 0;
m->lock.Release();
Sched::WakeObjectWaiters(&m->slotWait);
}
// Send one request and wait for its reply. `in`/`inLen` is request data
// (written to the provider), `out`/`outMax` receives reply data. Returns
// the provider's result, or a negative status if it could not be delivered.
static int64_t Call(Instance* inst, const UserFsRequest& proto,
const uint8_t* in, uint32_t inLen,
uint8_t* out, uint32_t outMax, uint32_t* outLen) {
MountState* m = inst->mount;
if (outLen != nullptr) *outLen = 0;
if (inst->dead) return NoDevice;
// The provider calling into its own drive would wait on itself.
int pid = Sched::GetCurrentPid();
if (pid < 0 || pid == m->ownerPid) return Busy;
if (inLen > USERFS_MAX_DATA || outMax > USERFS_MAX_DATA) return InvalidArgument;
uint32_t cap = inLen > outMax ? inLen : outMax;
uint8_t* bounce = nullptr;
if (cap > 0) {
bounce = new uint8_t[cap];
if (bounce == nullptr) return OutOfMemory;
if (inLen > 0) memcpy(bounce, in, inLen);
}
uint64_t deadline = Timekeeping::GetMilliseconds() + RequestTimeoutMs;
// Claim a slot.
Request* req = nullptr;
for (;;) {
uint64_t observed = Sched::ObserveObjectWake(&m->slotWait);
m->lock.Acquire();
if (!inst->dead) {
for (int i = 0; i < MaxRequests; i++) {
if (m->reqs[i].state != ReqFree || m->reqs[i].busy) continue;
req = &m->reqs[i];
req->inst = inst;
req->ownerPid = pid;
req->hdr = proto;
req->hdr.id = ++m->nextId;
req->hdr.dataLen = inLen;
req->hdr.replyMax = outMax;
req->data = bounce;
req->dataCap = cap;
req->replyLen = 0;
req->result = GenericFailure;
req->state = ReqPending;
break;
}
}
bool active = !inst->dead;
m->lock.Release();
if (req != nullptr) break;
uint64_t now = Timekeeping::GetMilliseconds();
if (!active || now >= deadline || CurrentKilled()) {
delete[] bounce;
return active ? TimedOut : NoDevice;
}
Sched::BlockOnObjectSince(&m->slotWait, 50, observed);
}
Sched::WakeObjectWaiters(m);
// Wait for the reply.
int64_t result = GenericFailure;
for (;;) {
uint64_t observed = Sched::ObserveObjectWake(req);
m->lock.Acquire();
bool done = req->state == ReqDone;
bool active = !inst->dead;
m->lock.Release();
if (done) {
result = req->result;
uint32_t n = req->replyLen;
if (n > outMax) n = outMax;
if (n > 0 && out != nullptr) memcpy(out, bounce, n);
if (outLen != nullptr) *outLen = n;
break;
}
uint64_t now = Timekeeping::GetMilliseconds();
if (!active) { result = NoDevice; break; }
if (now >= deadline) { result = TimedOut; break; }
if (CurrentKilled()) { result = GenericFailure; break; }
uint64_t wait = deadline - now;
if (wait > 250) wait = 250;
Sched::BlockOnObjectSince(req, wait, observed);
}
ReleaseSlot(m, req);
delete[] bounce;
return result;
}
static UserFsRequest MakeRequest(uint32_t op, const char* path) {
UserFsRequest r;
memset(&r, 0, sizeof(r));
r.op = op;
r.handle = -1;
if (path != nullptr) {
// Drive-root references arrive as "" or "/"; providers always see '/'.
CopyStr(r.path, path[0] ? path : "/", sizeof(r.path));
}
return r;
}
// ==========================================================================
// FsDriver entry points
// ==========================================================================
static int DrvOpen(void* ctx, const char* path) {
auto* inst = (Instance*)ctx;
int64_t r = Call(inst, MakeRequest(montauk::abi::USERFS_OP_OPEN, path), nullptr, 0, nullptr, 0, nullptr);
return (r >= 0 && r <= 0x7FFFFFFF) ? (int)r : -1;
}
static int DrvCreate(void* ctx, const char* path) {
auto* inst = (Instance*)ctx;
int64_t r = Call(inst, MakeRequest(montauk::abi::USERFS_OP_CREATE, path), nullptr, 0, nullptr, 0, nullptr);
return (r >= 0 && r <= 0x7FFFFFFF) ? (int)r : -1;
}
// Close never blocks: it runs during handle teardown, including on process
// exit. The handle is queued and delivered to the provider as a
// no-reply request ahead of anything else.
static void DrvClose(void* ctx, int handle) {
auto* inst = (Instance*)ctx;
MountState* m = inst->mount;
bool queued = false;
m->lock.Acquire();
if (!inst->dead && m->closeCount < CloseRingSize) {
m->closeRing[(m->closeHead + m->closeCount) % CloseRingSize] = handle;
m->closeCount++;
queued = true;
}
m->lock.Release();
if (queued) Sched::WakeObjectWaiters(m);
}
static int DrvRead(void* ctx, int handle, uint8_t* buffer, uint64_t offset, uint64_t size) {
auto* inst = (Instance*)ctx;
if (size > 0x7FFFFFFFULL) size = 0x7FFFFFFFULL;
uint64_t done = 0;
while (done < size) {
uint32_t chunk = (size - done > USERFS_MAX_DATA) ? USERFS_MAX_DATA : (uint32_t)(size - done);
UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_READ, nullptr);
r.handle = handle;
r.offset = offset + done;
r.size = chunk;
uint32_t got = 0;
int64_t res = Call(inst, r, nullptr, 0, buffer + done, chunk, &got);
if (res < 0) return done > 0 ? (int)done : -1;
if ((uint64_t)res < got) got = (uint32_t)res;
done += got;
if (got < chunk) break;
}
return (int)done;
}
static int DrvWrite(void* ctx, int handle, const uint8_t* buffer, uint64_t offset, uint64_t size) {
auto* inst = (Instance*)ctx;
if (size > 0x7FFFFFFFULL) size = 0x7FFFFFFFULL;
uint64_t done = 0;
while (done < size) {
uint32_t chunk = (size - done > USERFS_MAX_DATA) ? USERFS_MAX_DATA : (uint32_t)(size - done);
UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_WRITE, nullptr);
r.handle = handle;
r.offset = offset + done;
r.size = chunk;
int64_t res = Call(inst, r, buffer + done, chunk, nullptr, 0, nullptr);
if (res < 0) return done > 0 ? (int)done : -1;
uint32_t wrote = (uint64_t)res > chunk ? chunk : (uint32_t)res;
done += wrote;
if (wrote < chunk) break;
}
return (int)done;
}
static uint64_t DrvGetSize(void* ctx, int handle) {
auto* inst = (Instance*)ctx;
UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_GETSIZE, nullptr);
r.handle = handle;
int64_t res = Call(inst, r, nullptr, 0, nullptr, 0, nullptr);
return res < 0 ? 0 : (uint64_t)res;
}
// The VFS contract hands back pointers that outlive the driver call, so
// each calling thread gets a page that stays allocated for the life of the
// kernel; only its contents are replaced by that thread's next ReadDir.
static uint8_t* NameBufForCurrentThread(MountState* m) {
int tid = Sched::GetCurrentTid();
m->lock.Acquire();
NameBuf* slot = nullptr;
for (int i = 0; i < NameSlots; i++) {
if (m->names[i].page != nullptr && m->names[i].tid == tid) { slot = &m->names[i]; break; }
}
if (slot == nullptr) {
slot = &m->names[m->nameCursor % NameSlots];
m->nameCursor++;
slot->tid = tid;
}
uint8_t* page = slot->page;
m->lock.Release();
if (page == nullptr) {
uint8_t* fresh = new uint8_t[NameBufSize];
if (fresh == nullptr) return nullptr;
memset(fresh, 0, NameBufSize);
m->lock.Acquire();
if (slot->page == nullptr) {
slot->page = fresh;
fresh = nullptr;
}
page = slot->page;
m->lock.Release();
delete[] fresh;
}
return page;
}
static int DrvReadDirAt(void* ctx, const char* path, const char** outNames,
int maxEntries, int startIndex) {
auto* inst = (Instance*)ctx;
if (maxEntries <= 0) return 0;
uint8_t* page = NameBufForCurrentThread(inst->mount);
if (page == nullptr) return -1;
UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_READDIR, path);
r.offset = (uint64_t)startIndex;
r.size = (uint64_t)maxEntries;
uint32_t got = 0;
int64_t res = Call(inst, r, nullptr, 0, page, NameBufSize - 1, &got);
if (res < 0) return -1;
page[got] = '\0';
page[NameBufSize - 1] = '\0';
int count = 0;
uint32_t pos = 0;
while (count < maxEntries && count < res && pos < got) {
const char* name = (const char*)page + pos;
uint32_t len = 0;
while (pos + len < got && page[pos + len] != '\0') len++;
if (len == 0) break;
outNames[count++] = name;
pos += len + 1;
}
return count;
}
static int DrvReadDir(void* ctx, const char* path, const char** outNames, int maxEntries) {
return DrvReadDirAt(ctx, path, outNames, maxEntries, 0);
}
static int DrvStat(void* ctx, const char* path, Vfs::StatInfo* out) {
auto* inst = (Instance*)ctx;
FileStat st;
memset(&st, 0, sizeof(st));
uint32_t got = 0;
int64_t res = Call(inst, MakeRequest(montauk::abi::USERFS_OP_STAT, path), nullptr, 0,
(uint8_t*)&st, sizeof(st), &got);
if (res < 0 || got < sizeof(st)) return -1;
out->size = st.size;
out->mtime = st.mtime;
out->ctime = st.ctime;
out->atime = st.atime;
out->isDir = st.isDir != 0;
out->mode = st.mode != 0 ? st.mode
: (out->isDir ? (Vfs::ModeDir | 0755u) : (Vfs::ModeReg | 0644u));
return 0;
}
static int SimplePathOp(void* ctx, uint32_t op, const char* path, const char* path2 = nullptr) {
auto* inst = (Instance*)ctx;
UserFsRequest r = MakeRequest(op, path);
if (path2 != nullptr) CopyStr(r.path2, path2[0] ? path2 : "/", sizeof(r.path2));
int64_t res = Call(inst, r, nullptr, 0, nullptr, 0, nullptr);
return res < 0 ? -1 : 0;
}
static int DrvDelete(void* ctx, const char* path) {
return SimplePathOp(ctx, montauk::abi::USERFS_OP_DELETE, path);
}
static int DrvMkdir(void* ctx, const char* path) {
return SimplePathOp(ctx, montauk::abi::USERFS_OP_MKDIR, path);
}
static int DrvRename(void* ctx, const char* oldPath, const char* newPath) {
return SimplePathOp(ctx, montauk::abi::USERFS_OP_RENAME, oldPath, newPath);
}
// FsDriver::SetTimes codes: -1 missing, -2 unsupported, -3 bad time, -4 I/O.
static int DrvSetTimes(void* ctx, const char* path, int64_t atime, int64_t mtime) {
auto* inst = (Instance*)ctx;
UserFsRequest r = MakeRequest(montauk::abi::USERFS_OP_SETTIMES, path);
r.atime = atime;
r.mtime = mtime;
int64_t res = Call(inst, r, nullptr, 0, nullptr, 0, nullptr);
if (res >= 0) return 0;
if (res == NoSuchPath || res == NotFound) return -1;
if (res == UnsupportedOp) return -2;
if (res == InvalidArgument) return -3;
return -4;
}
static const char* DrvGetLabel(void* ctx) { return ((Instance*)ctx)->mount->label; }
static const char* DrvGetFsType(void* ctx) { return ((Instance*)ctx)->mount->fsType; }
// ==========================================================================
// Mount lifecycle
// ==========================================================================
static void Teardown(MountState* m) {
m->lock.Acquire();
bool wasActive = m->active;
Instance* inst = m->current;
m->active = false;
m->current = nullptr;
if (inst != nullptr) inst->dead = true;
m->lock.Release();
if (!wasActive) return;
// Waiters notice the dead mount and release their own slots.
for (int i = 0; i < MaxRequests; i++) Sched::WakeObjectWaiters(&m->reqs[i]);
Sched::WakeObjectWaiters(&m->slotWait);
Sched::WakeObjectWaiters(m);
Vfs::UnregisterDrive(m->drive);
if (inst != nullptr) {
g_mountsLock.Acquire();
for (int i = 0; i < MaxRetired; i++) {
if (g_retired[i] == nullptr) { g_retired[i] = inst; break; }
}
g_mountsLock.Release();
}
}
// Free retired instances no dispatched call can still be holding: a call
// pins its drive before it reads the driver's ctx, so once a drive's pin
// count has been zero after the unmount, only later mountings are in use.
// Caller holds g_mountsLock.
static void SweepRetired() {
for (int i = 0; i < MaxRetired; i++) {
Instance* inst = g_retired[i];
if (inst == nullptr || Vfs::DrivePinCount(inst->mount->drive) != 0) continue;
g_retired[i] = nullptr;
delete inst;
}
}
int Mount(const UserFsMountParams* params) {
if (params == nullptr) return InvalidArgument;
auto* proc = Sched::GetCurrentProcessPtr();
if (proc == nullptr) return GenericFailure;
bool readOnly = (params->flags & montauk::abi::USERFS_MOUNT_READONLY) != 0;
Instance* inst = new Instance{nullptr, false};
if (inst == nullptr) return OutOfMemory;
g_mountsLock.Acquire();
SweepRetired();
for (int i = 0; i < MaxMounts; i++) {
MountState* m = &g_mounts[i];
int drive = FirstDrive + i;
if (m->active || Vfs::IsDriveRegistered(drive)) continue;
inst->mount = m;
m->ejectRequested = false;
m->ownerPid = proc->pid;
m->ownerSession = proc->sessionId;
m->drive = drive;
m->flags = params->flags;
CopyStr(m->label, params->label, sizeof(m->label));
CopyStr(m->fsType, params->fsType, sizeof(m->fsType));
CopyStr(m->source, params->source, sizeof(m->source));
m->closeHead = 0;
m->closeCount = 0;
m->driver = Vfs::FsDriver{};
m->driver.ctx = inst;
m->driver.Open = DrvOpen;
m->driver.Read = DrvRead;
m->driver.GetSize = DrvGetSize;
m->driver.Close = DrvClose;
m->driver.ReadDir = DrvReadDir;
m->driver.ReadDirAt = DrvReadDirAt;
m->driver.Stat = DrvStat;
m->driver.GetLabel = DrvGetLabel;
m->driver.GetFsType = DrvGetFsType;
if (!readOnly) {
m->driver.Write = DrvWrite;
m->driver.Create = DrvCreate;
m->driver.Delete = DrvDelete;
m->driver.Mkdir = DrvMkdir;
m->driver.Rename = DrvRename;
m->driver.SetTimes = DrvSetTimes;
}
m->driver.concurrent = true;
m->driver.kind = Vfs::DriveKindNetwork;
m->lock.Acquire();
m->current = inst;
m->active = true;
m->lock.Release();
if (Vfs::RegisterDrive(drive, &m->driver) != 0) {
m->lock.Acquire();
m->active = false;
m->current = nullptr;
m->lock.Release();
continue;
}
g_mountsLock.Release();
Kt::KernelLogStream(Kt::OK, "UserFs") << "Drive " << drive << " provided by pid "
<< proc->pid << " (" << m->source << ")";
return drive;
}
g_mountsLock.Release();
delete inst;
return Busy;
}
static MountState* MountForOwner(int drive) {
MountState* m = MountForDrive(drive);
if (m == nullptr) return nullptr;
return m->ownerPid == Sched::GetCurrentPid() ? m : nullptr;
}
int Recv(int drive, UserFsRequest* out, uint8_t* data, uint32_t dataMax, uint64_t timeoutMs) {
if (out == nullptr) return InvalidArgument;
if (data == nullptr || dataMax < USERFS_MAX_DATA) return BufferTooSmall;
MountState* m = MountForOwner(drive);
if (m == nullptr) return NoDevice;
uint64_t deadline = Timekeeping::GetMilliseconds() + timeoutMs;
for (;;) {
uint64_t observed = Sched::ObserveObjectWake(m);
m->lock.Acquire();
if (!m->active) {
m->lock.Release();
return NoDevice;
}
// Closes first: they free provider handles and expect no reply.
if (m->closeCount > 0) {
int32_t handle = m->closeRing[m->closeHead];
m->closeHead = (m->closeHead + 1) % CloseRingSize;
m->closeCount--;
m->lock.Release();
memset(out, 0, sizeof(*out));
out->op = montauk::abi::USERFS_OP_CLOSE;
out->handle = handle;
return 1;
}
// Oldest pending request.
Request* req = nullptr;
for (int i = 0; i < MaxRequests; i++) {
if (m->reqs[i].state != ReqPending || m->reqs[i].inst != m->current) continue;
if (req == nullptr || m->reqs[i].hdr.id < req->hdr.id) req = &m->reqs[i];
}
if (req != nullptr) {
req->state = ReqTaken;
req->busy = true;
m->lock.Release();
*out = req->hdr;
if (req->hdr.dataLen > 0) memcpy(data, req->data, req->hdr.dataLen);
m->lock.Acquire();
req->busy = false;
m->lock.Release();
return 1;
}
if (m->ejectRequested) {
m->ejectRequested = false;
m->lock.Release();
memset(out, 0, sizeof(*out));
out->op = montauk::abi::USERFS_OP_UNMOUNT;
out->handle = -1;
return 1;
}
m->lock.Release();
uint64_t now = Timekeeping::GetMilliseconds();
if (timeoutMs == 0 || now >= deadline) return 0;
if (CurrentKilled()) return GenericFailure;
Sched::BlockOnObjectSince(m, deadline - now, observed);
}
}
int Reply(int drive, uint64_t id, int64_t result, const uint8_t* data, uint32_t len) {
if (id == 0) return InvalidArgument;
MountState* m = MountForOwner(drive);
if (m == nullptr) return NoDevice;
m->lock.Acquire();
Request* req = nullptr;
for (int i = 0; i < MaxRequests; i++) {
if (m->reqs[i].state == ReqTaken && !m->reqs[i].busy && m->reqs[i].hdr.id == id) {
req = &m->reqs[i];
break;
}
}
if (req == nullptr) {
// The caller gave up (timeout, killed) before the answer arrived.
m->lock.Release();
return NotFound;
}
if (len > req->hdr.replyMax) len = req->hdr.replyMax;
if (len > req->dataCap) len = req->dataCap;
if (data == nullptr) len = 0;
req->busy = true;
m->lock.Release();
if (len > 0) memcpy(req->data, data, len);
m->lock.Acquire();
req->replyLen = len;
req->result = result;
req->state = ReqDone;
req->busy = false;
m->lock.Release();
Sched::WakeObjectWaiters(req);
return Success;
}
int Unmount(int drive) {
MountState* m = MountForDrive(drive);
if (m == nullptr) return NoDevice;
auto* proc = Sched::GetCurrentProcessPtr();
if (proc == nullptr) return GenericFailure;
if (proc->pid == m->ownerPid) {
Teardown(m);
return Success;
}
if (proc->sessionId != m->ownerSession &&
!Sched::HasCapability(montauk::abi::CAP_STORAGE_ADMIN)) {
return PermissionDenied;
}
m->lock.Acquire();
m->ejectRequested = true;
m->lock.Release();
Sched::WakeObjectWaiters(m);
return Success;
}
int Info(int drive, UserFsInfo* out) {
if (out == nullptr) return InvalidArgument;
MountState* m = MountForDrive(drive);
if (m == nullptr) return NoDevice;
memset(out, 0, sizeof(*out));
m->lock.Acquire();
out->drive = m->drive;
out->providerPid = m->ownerPid;
out->flags = m->flags;
CopyStr(out->label, m->label, sizeof(out->label));
CopyStr(out->fsType, m->fsType, sizeof(out->fsType));
CopyStr(out->source, m->source, sizeof(out->source));
m->lock.Release();
return Success;
}
// Process exit terminates threads that are blocked in a call on the spot,
// without unwinding them, so a request slot such a thread was waiting in
// (and its bounce buffer) has to be reclaimed here. All of the process's
// threads are gone by now, so nothing else frees these.
static void ReclaimSlotsOf(MountState* m, int pid) {
for (int i = 0; i < MaxRequests; i++) {
Request* req = &m->reqs[i];
uint8_t* bounce = nullptr;
bool reclaimed = false;
for (;;) {
m->lock.Acquire();
if (req->state == ReqFree || req->ownerPid != pid) break;
if (!req->busy) {
bounce = req->data;
req->state = ReqFree;
req->hdr.id = 0;
req->inst = nullptr;
req->ownerPid = -1;
req->data = nullptr;
req->dataCap = 0;
reclaimed = true;
break;
}
m->lock.Release();
Arch::Pause();
}
m->lock.Release();
if (reclaimed) {
delete[] bounce;
Sched::WakeObjectWaiters(&m->slotWait);
}
}
}
void OnProcessExit(int pid) {
for (int i = 0; i < MaxMounts; i++) {
MountState* m = &g_mounts[i];
if (m->active && m->ownerPid == pid) Teardown(m);
ReclaimSlotsOf(m, pid);
}
}
}
+44
View File
@@ -0,0 +1,44 @@
/*
* UserFs.hpp
* Userspace filesystem providers: VFS drives served by a process
* Copyright (c) 2026 Daniel Hammer
*/
#pragma once
#include <cstdint>
#include <Api/Syscall.hpp>
// A provider process mounts a drive (Mount) and then serves it: every VFS call
// another process makes on that drive is queued as a UserFsRequest, the caller
// blocks, the provider picks the request up (Recv), does the work in userspace
// and answers (Reply). This keeps network protocols, their parsers and their
// credentials out of the kernel; smbfs.elf uses it to expose SMB shares.
//
// The drive is registered with FsDriver::concurrent set, so the VFS does not
// hold its local-driver lock while a caller waits on the provider.
namespace Fs::UserFs {
// Provider-backed drives occupy the fixed drive range
// [FirstDrive, FirstDrive + MaxMounts), clear of disk partitions.
static constexpr int MaxMounts = 16;
static constexpr int FirstDrive = 32;
// Returns the new drive number or a negative StatusCodes value.
int Mount(const montauk::abi::UserFsMountParams* params);
// Provider side. Recv returns 1 with a request, 0 on timeout (timeoutMs 0
// polls), or a negative status; `data` must hold USERFS_MAX_DATA bytes.
int Recv(int drive, montauk::abi::UserFsRequest* out, uint8_t* data,
uint32_t dataMax, uint64_t timeoutMs);
int Reply(int drive, uint64_t id, int64_t result, const uint8_t* data, uint32_t len);
// The provider unmounts at once. Another process in the provider's session
// (or a storage administrator) asks the provider to eject instead.
int Unmount(int drive);
int Info(int drive, montauk::abi::UserFsInfo* out);
// Unmount every drive the exiting process was providing.
void OnProcessExit(int pid);
}
+190 -112
View File
@@ -7,6 +7,7 @@
#include "Vfs.hpp"
#include <Terminal/Terminal.hpp>
#include <CppLib/Spinlock.hpp>
#include <Arch/Cpu.hpp>
namespace Fs::Vfs {
@@ -15,9 +16,44 @@ namespace Fs::Vfs {
static uint32_t driveGeneration[MaxDrives];
static bool initialized = false;
// Protects driver dispatch from concurrent CPU access. Hot-unplug only
// flips driveActive so an interrupted dispatch never sees a null driver.
static kcp::Mutex vfsLock;
// 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 --
@@ -50,8 +86,8 @@ namespace Fs::Vfs {
}
// Resolve a drive number to its driver, or nullptr if the slot is out of
// range, unregistered, or empty. Caller must hold vfsLock: the returned
// pointer is only valid for as long as the lock is held.
// 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;
@@ -77,8 +113,35 @@ namespace Fs::Vfs {
}
}
// 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;
@@ -97,15 +160,15 @@ namespace Fs::Vfs {
if (driver == nullptr) return -1;
if (!initialized) return -1;
vfsLock.Acquire();
tableLock.Acquire();
if (driveActive[driveNumber]) {
vfsLock.Release();
tableLock.Release();
return -1;
}
driveTable[driveNumber] = driver;
BumpDriveGeneration(driveNumber);
driveActive[driveNumber] = true;
vfsLock.Release();
tableLock.Release();
Kt::KernelLogStream(Kt::OK, "VFS") << "Registered drive " << driveNumber;
return 0;
@@ -115,23 +178,32 @@ namespace Fs::Vfs {
if (!initialized) return -1;
if (driveNumber < 0 || driveNumber >= MaxDrives) return -1;
vfsLock.Acquire();
tableLock.Acquire();
if (!driveActive[driveNumber]) {
vfsLock.Release();
tableLock.Release();
return -1;
}
driveActive[driveNumber] = false;
FsDriver* driver = driveTable[driveNumber];
driveTable[driveNumber] = nullptr;
BumpDriveGeneration(driveNumber);
tableLock.Release();
// Safe to tear down here: every dispatch path runs under vfsLock, so
// holding it means no call into this driver can still be in flight.
// Unmount frees the FsDriver itself, so nothing may touch it after.
// 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);
}
vfsLock.Release();
Kt::KernelLogStream(Kt::OK, "VFS") << "Unregistered drive " << driveNumber;
return 0;
@@ -139,25 +211,33 @@ namespace Fs::Vfs {
bool IsDriveRegistered(int driveNumber) {
if (driveNumber < 0 || driveNumber >= MaxDrives) return false;
vfsLock.Acquire();
tableLock.Acquire();
bool registered = driveActive[driveNumber];
vfsLock.Release();
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;
vfsLock.Acquire();
tableLock.Acquire();
for (int i = firstDrive; i < MaxDrives; i++) {
if (!driveActive[i]) {
vfsLock.Release();
tableLock.Release();
return i;
}
}
vfsLock.Release();
tableLock.Release();
return -1;
}
@@ -171,15 +251,12 @@ namespace Fs::Vfs {
if (!ParsePath(path, drive, localPath)) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(drive);
if (driver == nullptr || driver->Open == nullptr) {
vfsLock.Release();
return -1;
}
uint32_t generation = driveGeneration[drive];
int localHandle = driver->Open(driver->ctx, localPath);
vfsLock.Release();
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;
@@ -189,46 +266,42 @@ namespace Fs::Vfs {
}
int ReadBackendFile(const BackendFile& file, uint8_t* buffer, uint64_t offset, uint64_t size) {
vfsLock.Acquire();
FsDriver* driver = DriverForFileLocked(file);
if (driver == nullptr || driver->Read == nullptr) {
vfsLock.Release();
return -1;
}
int result = driver->Read(driver->ctx, file.localHandle, buffer, offset, size);
vfsLock.Release();
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) {
vfsLock.Acquire();
FsDriver* driver = DriverForFileLocked(file);
if (driver == nullptr || driver->GetSize == nullptr) {
vfsLock.Release();
return 0;
}
uint64_t result = driver->GetSize(driver->ctx, file.localHandle);
vfsLock.Release();
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) {
vfsLock.Acquire();
tableLock.Acquire();
FsDriver* driver = DriverForFileLocked(file);
bool canWrite = driver != nullptr && driver->Write != nullptr;
vfsLock.Release();
tableLock.Release();
return canWrite;
}
void CloseBackendFile(BackendFile& file) {
vfsLock.Acquire();
FsDriver* driver = DriverForFileLocked(file);
if (driver != nullptr && driver->Close != nullptr) {
driver->Close(driver->ctx, file.localHandle);
Pinned pin;
if (PinFile(file, pin)) {
FsDriver* driver = pin.driver;
if (driver->Close != nullptr) driver->Close(driver->ctx, file.localHandle);
Unpin(pin);
}
vfsLock.Release();
file.driveNumber = -1;
file.localHandle = -1;
@@ -236,15 +309,13 @@ namespace Fs::Vfs {
}
int WriteBackendFile(const BackendFile& file, const uint8_t* buffer, uint64_t offset, uint64_t size) {
vfsLock.Acquire();
FsDriver* driver = DriverForFileLocked(file);
if (driver == nullptr || driver->Write == nullptr) {
vfsLock.Release();
return -1;
}
int result = driver->Write(driver->ctx, file.localHandle, buffer, offset, size);
vfsLock.Release();
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;
}
@@ -258,15 +329,12 @@ namespace Fs::Vfs {
if (!ParsePath(path, drive, localPath)) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(drive);
if (driver == nullptr || driver->Create == nullptr) {
vfsLock.Release();
return -1;
}
uint32_t generation = driveGeneration[drive];
int localHandle = driver->Create(driver->ctx, localPath);
vfsLock.Release();
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;
@@ -281,12 +349,13 @@ namespace Fs::Vfs {
if (!ParsePath(path, drive, localPath)) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(drive);
int result = (driver != nullptr && driver->Delete != nullptr)
Pinned pin;
if (!PinDrive(drive, pin)) return -1;
FsDriver* driver = pin.driver;
int result = (driver->Delete != nullptr)
? driver->Delete(driver->ctx, localPath)
: -1;
vfsLock.Release();
Unpin(pin);
return result;
}
@@ -298,12 +367,13 @@ namespace Fs::Vfs {
if (!ParsePath(path, drive, localPath)) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(drive);
int result = (driver != nullptr && driver->Stat != nullptr)
Pinned pin;
if (!PinDrive(drive, pin)) return -1;
FsDriver* driver = pin.driver;
int result = (driver->Stat != nullptr)
? driver->Stat(driver->ctx, localPath, &out)
: -1;
vfsLock.Release();
Unpin(pin);
return result;
}
@@ -313,12 +383,13 @@ namespace Fs::Vfs {
if (!ParsePath(path, drive, localPath)) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(drive);
int result = (driver != nullptr && driver->SetTimes != nullptr)
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;
vfsLock.Release();
Unpin(pin);
return result;
}
@@ -328,26 +399,27 @@ namespace Fs::Vfs {
if (!ParsePath(path, drive, localPath)) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(drive);
int result = (driver != nullptr && driver->Mkdir != nullptr)
Pinned pin;
if (!PinDrive(drive, pin)) return -1;
FsDriver* driver = pin.driver;
int result = (driver->Mkdir != nullptr)
? driver->Mkdir(driver->ctx, localPath)
: -1;
vfsLock.Release();
Unpin(pin);
return result;
}
int VfsDriveList(int* outDrives, int maxEntries) {
if (outDrives == nullptr || maxEntries <= 0) return 0;
vfsLock.Acquire();
tableLock.Acquire();
int count = 0;
for (int i = 0; i < MaxDrives && count < maxEntries; i++) {
if (driveActive[i]) {
outDrives[count++] = i;
}
}
vfsLock.Release();
tableLock.Release();
return count;
}
static int CopyDriveString(int driveNumber, const char* (*FsDriver::*hook)(void*),
@@ -355,21 +427,18 @@ namespace Fs::Vfs {
if (out == nullptr || maxLen <= 0) return -1;
out[0] = '\0';
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(driveNumber);
if (driver == nullptr) {
vfsLock.Release();
return -1;
}
Pinned pin;
if (!PinDrive(driveNumber, pin)) return -1;
FsDriver* driver = pin.driver;
if (driver->*hook == nullptr) {
vfsLock.Release();
Unpin(pin);
return 0;
}
const char* value = (driver->*hook)(driver->ctx);
if (value == nullptr || value[0] == '\0') {
vfsLock.Release();
Unpin(pin);
return 0;
}
@@ -380,10 +449,18 @@ namespace Fs::Vfs {
}
out[copied] = '\0';
vfsLock.Release();
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);
}
@@ -393,12 +470,13 @@ namespace Fs::Vfs {
}
int VfsGrow(int driveNumber, uint64_t partSectors, bool apply, GrowStatus* out) {
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(driveNumber);
int result = (driver != nullptr && driver->Grow != nullptr)
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;
vfsLock.Release();
Unpin(pin);
return result;
}
@@ -413,12 +491,13 @@ namespace Fs::Vfs {
// Cross-drive rename not supported
if (oldDrive != newDrive) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(oldDrive);
int result = (driver != nullptr && driver->Rename != nullptr)
Pinned pin;
if (!PinDrive(oldDrive, pin)) return -1;
FsDriver* driver = pin.driver;
int result = (driver->Rename != nullptr)
? driver->Rename(driver->ctx, oldLocal, newLocal)
: -1;
vfsLock.Release();
Unpin(pin);
return result;
}
@@ -433,12 +512,11 @@ namespace Fs::Vfs {
if (startIndex < 0) return -1;
if (!ParsePath(path, drive, localPath)) return -1;
vfsLock.Acquire();
FsDriver* driver = DriverForLocked(drive);
Pinned pin;
if (!PinDrive(drive, pin)) return -1;
FsDriver* driver = pin.driver;
int result;
if (driver == nullptr) {
result = -1;
} else if (driver->ReadDirAt) {
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.
@@ -446,7 +524,7 @@ namespace Fs::Vfs {
} else {
result = -1;
}
vfsLock.Release();
Unpin(pin);
return result;
}
+19
View File
@@ -93,13 +93,30 @@ namespace Fs::Vfs {
// -1 is an I/O error, -2 a layout the driver cannot grow. Callers loop,
// so other I/O interleaves between slices.
int (*Grow)(void* ctx, uint64_t partSectors, bool apply, GrowStatus* out);
// True for drivers whose calls block on a peer outside the kernel
// (userspace / network filesystems). The VFS dispatches them without
// its local-driver lock, so several calls may be inside the driver at
// once and it must do its own locking. Such drivers own their storage:
// they leave Unmount null and must tolerate calls that were already
// dispatched when the drive was unregistered.
bool concurrent = false;
// DriveKind* override for drives with no backing block device
// (0 = derive the kind from the block device, as before).
uint8_t kind = 0;
};
// Drive kind reported for network / userspace-provided drives. Continues
// the BlockDeviceKind numbering used by SYS_DRIVEKIND and VolInfo::kind.
static constexpr uint8_t DriveKindNetwork = 6;
void Initialize();
bool IsInitialized();
int RegisterDrive(int driveNumber, FsDriver* driver);
int UnregisterDrive(int driveNumber);
bool IsDriveRegistered(int driveNumber);
// Calls currently dispatched on a drive slot, including calls that went
// to a driver since unregistered from it and have not returned yet.
uint32_t DrivePinCount(int driveNumber);
int FindLowestAvailableDrive(int firstDrive = 0);
int OpenBackendFile(const char* path, BackendFile& outFile);
@@ -120,6 +137,8 @@ namespace Fs::Vfs {
// Returns number of registered drives, fills outDrives[] with their indices
int VfsDriveList(int* outDrives, int maxEntries);
// FsDriver::kind of a mounted drive, 0 if unset or not mounted.
int VfsDriveKind(int driveNumber);
int VfsDriveLabel(int driveNumber, char* outLabel, int maxLen);
int VfsDriveFsType(int driveNumber, char* outType, int maxLen);
+5
View File
@@ -32,6 +32,7 @@
#include <Drivers/Graphics/IntelGPU.hpp>
#include <Ipc/Ipc.hpp>
#include <Drivers/USB/UserUsb.hpp>
#include <Fs/UserFs.hpp>
namespace Sched {
@@ -1631,6 +1632,10 @@ namespace Sched {
// exits without calling usb_close().
Drivers::USB::UserUsb::ReleaseAllForPid(exitingPid);
// Unmount drives this process was providing (userspace filesystems)
// before its handles go, so callers blocked on it fail at once.
Fs::UserFs::OnProcessExit(exitingPid);
// Release process-scoped IPC handles/mappings before tearing down the address space.
Ipc::CleanupProcessSlot(slot, exitingPid, proc.pageTableRoot);
montauk::abi::CleanupHeapForSlot(slot, proc.pageTableRoot);