Skip to main content

strat9_kernel/vfs/
mod.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Virtual File System (VFS) - Plan 9-inspired namespace.
24//!
25//! The VFS provides:
26//! - Scheme abstraction: Pluggable backends (IPC, kernel, devices)
27//! - Mount table: Map path prefixes to schemes
28//! - File descriptors: Per-process FD tables
29//! - Path resolution: Navigate the namespace hierarchy
30//!
31//! ## Architecture
32//!
33//! ```text
34//! User syscall (open "/net/tcp/0")
35//!      ↓
36//! VFS::open() : path resolution
37//!      ↓
38//! MountTable::resolve() => ("/net" => IpcScheme, "tcp/0")
39//!      ↓
40//! IpcScheme::open("tcp/0") => IPC message to network stack
41//!      ↓
42//! OpenFile created with scheme reference + file_id
43//!      ↓
44//! FD allocated in process FD table
45//!      ↓
46//! Returns FD to userspace
47//! ```
48
49pub mod blkdev_scheme;
50pub mod bt_scheme;
51pub mod bulk;
52pub mod console_scheme;
53pub mod fd;
54pub mod file;
55pub mod input_scheme;
56pub mod ipcfs;
57pub mod log_scheme;
58pub mod meminfo;
59pub mod mount;
60pub use bulk::BulkHandle;
61pub mod pipe;
62pub mod procfs;
63pub mod pty_scheme;
64pub mod ramfs_scheme;
65pub mod scheme;
66pub mod scheme_router;
67pub mod threads_scheme;
68pub mod vmm_net_scheme;
69pub mod vmm_scheme;
70
71use crate::{process::current_task_clone, sync::SpinLock, syscall::error::SyscallError};
72use alloc::{boxed::Box, string::String, sync::Arc};
73use core::fmt::Write;
74
75pub use blkdev_scheme::BlkDevScheme;
76pub use fd::{FileDescriptorTable, STDERR, STDIN, STDOUT};
77pub use file::OpenFile;
78pub use mount::{
79    list_mounts, mount, mount_count, mount_replace, owner_of, resolve, unmount, unmount_owned_by,
80    Namespace,
81};
82pub use pipe::PipeScheme;
83pub use procfs::ProcScheme;
84pub use ramfs_scheme::RamfsScheme;
85pub use scheme::{
86    DirEntry, DynScheme, FileFlags, FileStat, IpcScheme, KernelScheme, OpenFlags, Scheme, DT_DIR,
87};
88pub use scheme_router::{
89    get_initfs_file_bytes, init_builtin_schemes, list_schemes, mount_scheme, register_initfs_file,
90    register_scheme,
91};
92
93use crate::memory::{UserSliceRead, UserSliceWrite};
94
95/// Largest device frame copied atomically (one `scheme.write` call).
96///
97/// Device protocols (Screen, DMG2) treat one user write as one message; the
98/// 4 KiB chunk loop below would split larger frames and corrupt their headers.
99const MAX_ATOMIC_DEVICE_WRITE: u64 = 64 * 1024 * 1024;
100
101// Re-export AT_FDCWD from the ABI so VFS callers can use it.
102pub use crate::syscall::numbers::AT_FDCWD;
103
104// ============================================================================
105// High-level VFS API
106// ============================================================================
107
108/// Open a file and return a file descriptor.
109/// Open a file with an already-resolved path (avoids double mount::resolve).
110///
111/// Used by `sys_open` and `open_at` which resolve the path once before calling
112/// this. The silo permission check must have already been performed.
113pub fn open(path: &str, flags: OpenFlags) -> Result<u32, SyscallError> {
114    let (scheme, relative_path) = mount::resolve(path)?;
115
116    let open_result = scheme.open(&relative_path, flags)?;
117
118    let open_file = Arc::new(OpenFile::new(
119        scheme,
120        open_result.file_id,
121        String::from(path),
122        flags,
123        open_result.flags,
124        open_result.size,
125    ));
126
127    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
128    let fd = unsafe { (&mut *task.process.fd_table.get()).insert(open_file) };
129
130    Ok(fd)
131}
132
133/// Resolve `path` against the current task CWD and enforce silo path policy.
134pub fn resolve_and_check_path_for_current_task(
135    path: &str,
136    want_read: bool,
137    want_write: bool,
138    want_execute: bool,
139) -> Result<String, SyscallError> {
140    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
141    let cwd = unsafe { (&*task.process.cwd.get()).clone() };
142    let abs = resolve_path(path, &cwd);
143    crate::silo::enforce_path_for_current_task(&abs, want_read, want_write, want_execute)?;
144    Ok(abs)
145}
146
147/// Current working directory of the calling task.
148///
149/// In-kernel counterpart of the `getcwd` syscall, for callers that already live
150/// in the kernel and therefore have no user buffer to write into.
151pub fn current_dir() -> Result<String, SyscallError> {
152    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
153    Ok(unsafe { (&*task.process.cwd.get()).clone() })
154}
155
156/// Change the current working directory of the calling task.
157///
158/// In-kernel counterpart of the `chdir` syscall: `path` is resolved against the
159/// current directory, then checked to be an existing directory.
160pub fn set_current_dir(path: &str) -> Result<(), SyscallError> {
161    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
162    let cwd = unsafe { (&*task.process.cwd.get()).clone() };
163    let abs = resolve_path(path, &cwd);
164
165    let (scheme, rel) = mount::resolve(&abs)?;
166    let res = scheme.open(&rel, OpenFlags::READ | OpenFlags::DIRECTORY)?;
167    let _ = scheme.close(res.file_id);
168
169    unsafe { *task.process.cwd.get() = abs };
170    Ok(())
171}
172
173/// Resolve `path` (absolute or relative) against the calling task's directory.
174///
175/// This is the single path-collapsing implementation of the kernel. The shell
176/// resolves paths with it instead of keeping a second working directory and a
177/// private copy of the normalisation rules, which is how the two used to drift
178/// apart.
179///
180/// No policy is enforced here: the operation the caller performs next (open,
181/// mkdir, unlink, ...) applies its own.
182pub fn resolve_path_for_current_task(path: &str) -> Result<String, SyscallError> {
183    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
184    let cwd = unsafe { (&*task.process.cwd.get()).clone() };
185    Ok(resolve_path(path, &cwd))
186}
187
188/// Open a file relative to a directory FD.
189///
190/// - If `dir_fd == AT_FDCWD`, resolve against the process CWD (equivalent to `open()`).
191/// - Otherwise, resolve against the path of the given directory FD.
192///
193/// This is the foundation for capability-based path resolution: the directory
194/// FD acts as the root of the namespace for this operation, naturally
195/// preventing `../` escapes beyond the FD's subtree.
196pub fn open_at(dir_fd: u64, path: &str, flags: OpenFlags) -> Result<u32, SyscallError> {
197    if dir_fd == AT_FDCWD as u64 {
198        // Fall back to process CWD : original open() behavior.
199        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
200        let cwd = unsafe { (&*task.process.cwd.get()).clone() };
201        let abs = resolve_path(path, &cwd);
202        crate::silo::enforce_path_for_current_task(
203            &abs,
204            flags.contains(OpenFlags::READ) || flags.contains(OpenFlags::DIRECTORY),
205            flags.contains(OpenFlags::WRITE) || flags.contains(OpenFlags::CREATE),
206            false,
207        )?;
208        open(&abs, flags)
209    } else {
210        // Resolve relative to the directory FD.
211        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
212        let fd_table = unsafe { &*task.process.fd_table.get() };
213        let dir_file = fd_table.get(dir_fd as u32)?;
214        if !dir_file.flags().contains(FileFlags::DIRECTORY) {
215            return Err(SyscallError::NotADirectory);
216        }
217        let dir_path = dir_file.path();
218        let abs = resolve_path(path, dir_path);
219        crate::silo::enforce_path_for_current_task(
220            &abs,
221            flags.contains(OpenFlags::READ) || flags.contains(OpenFlags::DIRECTORY),
222            flags.contains(OpenFlags::WRITE) || flags.contains(OpenFlags::CREATE),
223            false,
224        )?;
225        open(&abs, flags)
226    }
227}
228
229/// Stat a file relative to a directory FD.
230///
231/// Same resolution semantics as `open_at`.
232pub fn fstat_at(dir_fd: u64, path: &str) -> Result<FileStat, SyscallError> {
233    if dir_fd == AT_FDCWD as u64 {
234        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
235        let cwd = unsafe { (&*task.process.cwd.get()).clone() };
236        let abs = resolve_path(path, &cwd);
237        stat_path(&abs)
238    } else {
239        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
240        let fd_table = unsafe { &*task.process.fd_table.get() };
241        let dir_file = fd_table.get(dir_fd as u32)?;
242        if !dir_file.flags().contains(FileFlags::DIRECTORY) {
243            return Err(SyscallError::NotADirectory);
244        }
245        let dir_path = dir_file.path();
246        let abs = resolve_path(path, dir_path);
247        stat_path(&abs)
248    }
249}
250
251/// Create a directory.
252pub fn mkdir(path: &str, mode: u32) -> Result<(), SyscallError> {
253    let (scheme, relative_path) = mount::resolve(path)?;
254    scheme.create_directory(&relative_path, mode)?;
255    Ok(())
256}
257
258/// Create an empty regular file.
259pub fn create_file(path: &str, mode: u32) -> Result<(), SyscallError> {
260    let (scheme, relative_path) = mount::resolve(path)?;
261    scheme.create_file(&relative_path, mode)?;
262    Ok(())
263}
264
265/// Remove a file or directory.
266pub fn unlink(path: &str) -> Result<(), SyscallError> {
267    let (scheme, relative_path) = mount::resolve(path)?;
268    scheme.unlink(&relative_path)?;
269    Ok(())
270}
271
272/// Rename a file or directory (must be within the same mount).
273pub fn rename(old_path: &str, new_path: &str) -> Result<(), SyscallError> {
274    let (scheme, old_rel) = mount::resolve(old_path)?;
275    let (scheme2, new_rel) = mount::resolve(new_path)?;
276    if !Arc::ptr_eq(&scheme, &scheme2) {
277        return Err(SyscallError::NotSupported);
278    }
279    scheme.rename(&old_rel, &new_rel)
280}
281
282/// Change permission bits on a path.
283pub fn chmod(path: &str, mode: u32) -> Result<(), SyscallError> {
284    let (scheme, relative_path) = mount::resolve(path)?;
285    scheme.chmod(&relative_path, mode)
286}
287
288/// Change permission bits on an open fd.
289pub fn fchmod(fd: u32, mode: u32) -> Result<(), SyscallError> {
290    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
291    let fd_table = unsafe { &*task.process.fd_table.get() };
292    let file = fd_table.get(fd)?;
293    file.scheme().fchmod(file.file_id(), mode)
294}
295
296/// Truncate a file by path.
297///
298/// Opens the file with WRITE, truncates, and closes. The scheme's truncate()
299/// method is called directly if available; otherwise opens+closes as fallback.
300pub fn truncate(path: &str, length: u64) -> Result<(), SyscallError> {
301    let (scheme, relative_path) = mount::resolve(path)?;
302
303    // Try direct truncate via path first (avoids open/close round-trip).
304    // Only works if the scheme supports truncate by path.
305    match scheme.truncate_by_path(&relative_path, length) {
306        Ok(()) => return Ok(()),
307        Err(SyscallError::NotImplemented) => {
308            // Scheme doesn't support path-based truncate: fall back to
309            // open + truncate + close.
310        }
311        Err(e) => return Err(e),
312    }
313
314    let res = scheme.open(&relative_path, OpenFlags::WRITE)?;
315    let r = scheme.truncate(res.file_id, length);
316    let _ = scheme.close(res.file_id);
317    r
318}
319
320/// Truncate an open fd.
321pub fn ftruncate(fd: u32, length: u64) -> Result<(), SyscallError> {
322    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
323    let fd_table = unsafe { &*task.process.fd_table.get() };
324    let file = fd_table.get(fd)?;
325    file.scheme().truncate(file.file_id(), length)
326}
327
328/// Create a hard link (must be within the same mount).
329pub fn link(old_path: &str, new_path: &str) -> Result<(), SyscallError> {
330    let (scheme, old_rel) = mount::resolve(old_path)?;
331    let (scheme2, new_rel) = mount::resolve(new_path)?;
332    if !Arc::ptr_eq(&scheme, &scheme2) {
333        return Err(SyscallError::NotSupported);
334    }
335    scheme.link(&old_rel, &new_rel)
336}
337
338/// Create a symbolic link.
339pub fn symlink(target: &str, link_path: &str) -> Result<(), SyscallError> {
340    let (scheme, link_rel) = mount::resolve(link_path)?;
341    scheme.symlink(target, &link_rel)
342}
343
344/// Read the target of a symbolic link.
345pub fn readlink(path: &str) -> Result<String, SyscallError> {
346    let (scheme, relative_path) = mount::resolve(path)?;
347    scheme.readlink(&relative_path)
348}
349
350/// Read from a file descriptor.
351pub fn read(fd: u32, buf: &mut [u8]) -> Result<usize, SyscallError> {
352    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
353    // SAFETY: Syscall context
354    let fd_table = unsafe { &*task.process.fd_table.get() };
355    let file = fd_table.get(fd)?;
356    file.read(buf)
357}
358
359/// Write to a file descriptor.
360pub fn write(fd: u32, buf: &[u8]) -> Result<usize, SyscallError> {
361    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
362    // SAFETY: Syscall context
363    let fd_table = unsafe { &*task.process.fd_table.get() };
364    let file = fd_table.get(fd)?;
365    file.write(buf)
366}
367
368/// Close a file descriptor.
369///
370/// Removes the fd from the table.  If this was the last Arc<OpenFile> reference
371/// (no dup'd / fork'd copies remain) the Drop impl will call scheme.close().
372pub fn close(fd: u32) -> Result<(), SyscallError> {
373    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
374    // SAFETY: Syscall context
375    let fd_table = unsafe { &mut *task.process.fd_table.get() };
376    let _file = fd_table.remove(fd)?;
377    Ok(())
378    // _file (Arc<OpenFile>) is dropped here; if refcount => 0, Drop fires => scheme.close()
379}
380
381/// Seek within a file.
382pub fn seek(fd: u32, offset: u64) -> Result<u64, SyscallError> {
383    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
384    // SAFETY: Syscall context
385    let fd_table = unsafe { &*task.process.fd_table.get() };
386    let file = fd_table.get(fd)?;
387    file.seek(offset)
388}
389
390/// Get current offset in a file.
391pub fn tell(fd: u32) -> Result<u64, SyscallError> {
392    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
393    // SAFETY: Syscall context
394    let fd_table = unsafe { &*task.process.fd_table.get() };
395    let file = fd_table.get(fd)?;
396    Ok(file.tell())
397}
398
399/// Get file size.
400pub fn fsize(fd: u32) -> Result<u64, SyscallError> {
401    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
402    // SAFETY: Syscall context
403    let fd_table = unsafe { &*task.process.fd_table.get() };
404    let file = fd_table.get(fd)?;
405    file.size()
406}
407
408/// Sync file to storage.
409pub fn fsync(fd: u32) -> Result<(), SyscallError> {
410    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
411    // SAFETY: Syscall context
412    let fd_table = unsafe { &*task.process.fd_table.get() };
413    let file = fd_table.get(fd)?;
414    file.sync()
415}
416
417/// POSIX lseek on a file descriptor.
418pub fn lseek(fd: u32, offset: i64, whence: u32) -> Result<u64, SyscallError> {
419    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
420    let fd_table = unsafe { &*task.process.fd_table.get() };
421    let file = fd_table.get(fd)?;
422    file.lseek(offset, whence)
423}
424
425/// fstat on an open file descriptor.
426pub fn fstat(fd: u32) -> Result<FileStat, SyscallError> {
427    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
428    let fd_table = unsafe { &*task.process.fd_table.get() };
429    let file = fd_table.get(fd)?;
430    file.stat()
431}
432
433/// stat by path (scheme-specific; the default opens, stats and closes).
434pub fn stat_path(path: &str) -> Result<FileStat, SyscallError> {
435    let (scheme, relative_path) = mount::resolve(path)?;
436    scheme.stat_by_path(&relative_path)
437}
438
439/// Read directory entries from an open directory fd.
440pub fn getdents(fd: u32) -> Result<alloc::vec::Vec<DirEntry>, SyscallError> {
441    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
442    let fd_table = unsafe { &*task.process.fd_table.get() };
443    let file = fd_table.get(fd)?;
444    let mut entries = file.readdir()?;
445
446    // Mounts are VFS prefixes, not entries of the underlying scheme. Merge
447    // the direct child mounts of this directory so `ls /dev` shows
448    // `console`, `display`, `input`, `pts`, ... even though the /dev scheme
449    // itself only knows null/zero/random/urandom.
450    let dir = file.path().trim_end_matches('/');
451    let dir = if dir.is_empty() { "/" } else { dir };
452    for prefix in list_mounts() {
453        let child = if dir == "/" {
454            prefix.strip_prefix('/')
455        } else {
456            prefix
457                .strip_prefix(dir)
458                .and_then(|rest| rest.strip_prefix('/'))
459        };
460        let Some(child) = child else {
461            continue;
462        };
463        if child.is_empty() || child.contains('/') {
464            continue;
465        }
466        if entries.iter().any(|entry| entry.name == child) {
467            continue;
468        }
469        entries.push(DirEntry {
470            ino: 0,
471            file_type: DT_DIR,
472            name: String::from(child),
473        });
474    }
475
476    Ok(entries)
477}
478
479/// Create a background stdin: a pipe read-end whose write end is immediately
480/// closed.  Any `read()` on the returned file will return 0 (EOF) at once,
481/// preventing processes launched in the background from blocking on stdin or
482/// spinning on EBADF.
483pub fn create_background_stdin() -> Arc<OpenFile> {
484    let pipe_scheme = get_pipe_scheme();
485    let (base_id, pipe) = pipe_scheme.create_pipe();
486
487    // Close write end now (refcount => 0 => write_closed = true).
488    // Subsequent reads on the read end will return EOF immediately.
489    pipe.close_write();
490
491    let dyn_scheme: DynScheme = pipe_scheme as Arc<dyn Scheme>;
492    Arc::new(OpenFile::new(
493        dyn_scheme,
494        base_id, // even = read end
495        String::from("pipe:[bg-stdin]"),
496        OpenFlags::READ,
497        FileFlags::PIPE,
498        None,
499    ))
500}
501
502/// Create a pipe, returning (read_fd, write_fd).
503pub fn pipe() -> Result<(u32, u32), SyscallError> {
504    let pipe_scheme = get_pipe_scheme();
505    let (base_id, _pipe) = pipe_scheme.create_pipe();
506
507    let dyn_scheme: DynScheme = pipe_scheme as Arc<dyn Scheme>;
508
509    let read_file = Arc::new(OpenFile::new(
510        dyn_scheme.clone(),
511        base_id,
512        String::from("pipe:[read]"),
513        OpenFlags::READ,
514        FileFlags::PIPE,
515        None,
516    ));
517    let write_file = Arc::new(OpenFile::new(
518        dyn_scheme.clone(),
519        base_id + 1,
520        String::from("pipe:[write]"),
521        OpenFlags::WRITE,
522        FileFlags::PIPE,
523        None,
524    ));
525
526    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
527    let fd_table = unsafe { &mut *task.process.fd_table.get() };
528    let read_fd = fd_table.insert(read_file);
529    let write_fd = fd_table.insert(write_file);
530
531    Ok((read_fd, write_fd))
532}
533
534/// Duplicate a file descriptor (POSIX dup).
535pub fn dup(old_fd: u32) -> Result<u32, SyscallError> {
536    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
537    let fd_table = unsafe { &mut *task.process.fd_table.get() };
538    fd_table.duplicate(old_fd)
539}
540
541/// Duplicate a file descriptor to a specific number (POSIX dup2).
542pub fn dup2(old_fd: u32, new_fd: u32) -> Result<u32, SyscallError> {
543    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
544    let fd_table = unsafe { &mut *task.process.fd_table.get() };
545    fd_table.duplicate_to(old_fd, new_fd)
546}
547
548/// Read all remaining bytes from a file descriptor.
549pub fn read_all(fd: u32) -> Result<alloc::vec::Vec<u8>, SyscallError> {
550    let mut out = alloc::vec::Vec::new();
551    let mut buf = [0u8; 4096];
552    loop {
553        let n = read(fd, &mut buf)?;
554        if n == 0 {
555            break;
556        }
557        out.extend_from_slice(&buf[..n]);
558    }
559    Ok(out)
560}
561
562// ============================================================================
563// Syscall Handlers (Native ABI)
564// ============================================================================
565
566/// Syscall handler for opening a file.
567pub fn sys_open(path_ptr: u64, path_len: u64, flags: u64) -> Result<u64, SyscallError> {
568    let open_flags = OpenFlags::from_bits_truncate(flags as u32);
569    let want_read =
570        open_flags.contains(OpenFlags::READ) || open_flags.contains(OpenFlags::DIRECTORY);
571    let want_write = open_flags.contains(OpenFlags::WRITE)
572        || open_flags.contains(OpenFlags::CREATE)
573        || open_flags.contains(OpenFlags::TRUNCATE)
574        || open_flags.contains(OpenFlags::APPEND);
575    let path = resolve_for_syscall(path_ptr, path_len, want_read, want_write, false)?;
576    let fd = open(&path, open_flags)?;
577    Ok(fd as u64)
578}
579
580/// SYS_OPENAT (462): Open a file relative to a directory FD.
581pub fn sys_openat(
582    dir_fd: u64,
583    path_ptr: u64,
584    path_len: u64,
585    flags: u64,
586) -> Result<u64, SyscallError> {
587    const MAX_PATH_LEN: usize = 4096;
588    if path_len == 0 || path_len as usize > MAX_PATH_LEN {
589        return Err(SyscallError::InvalidArgument);
590    }
591    let raw = read_user_path(path_ptr, path_len)?;
592    let open_flags = OpenFlags::from_bits_truncate(flags as u32);
593    let fd = open_at(dir_fd, &raw, open_flags)?;
594    Ok(fd as u64)
595}
596
597/// SYS_FSTATAT (463): Stat a file relative to a directory FD.
598pub fn sys_fstatat(
599    dir_fd: u64,
600    path_ptr: u64,
601    path_len: u64,
602    statbuf_ptr: u64,
603) -> Result<u64, SyscallError> {
604    use crate::memory::UserSliceWrite;
605    const MAX_PATH_LEN: usize = 4096;
606    if path_len == 0 || path_len as usize > MAX_PATH_LEN || statbuf_ptr == 0 {
607        return Err(SyscallError::InvalidArgument);
608    }
609    let raw = read_user_path(path_ptr, path_len)?;
610    let st = fstat_at(dir_fd, &raw)?;
611    let user = UserSliceWrite::new(statbuf_ptr, core::mem::size_of::<FileStat>())?;
612    let bytes = unsafe {
613        core::slice::from_raw_parts(
614            &st as *const FileStat as *const u8,
615            core::mem::size_of::<FileStat>(),
616        )
617    };
618    user.copy_from(bytes);
619    Ok(0)
620}
621
622/// SYS_ACCESS (413): Check file access permissions without opening a FD.
623pub fn sys_access(path_ptr: u64, path_len: u64, mode: u64) -> Result<u64, SyscallError> {
624    let path = resolve_for_syscall(path_ptr, path_len, true, false, false)?;
625    let st = stat_path(&path)?;
626    check_access_permissions(&st, mode as u32)?;
627    Ok(0)
628}
629
630/// SYS_FACCESSAT (468): Check file access relative to a directory FD.
631pub fn sys_faccessat(
632    dir_fd: u64,
633    path_ptr: u64,
634    path_len: u64,
635    mode: u64,
636    _flags: u64,
637) -> Result<u64, SyscallError> {
638    let raw = read_user_path(path_ptr, path_len)?;
639
640    let abs = if dir_fd == AT_FDCWD as u64 {
641        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
642        let cwd = unsafe { (&*task.process.cwd.get()).clone() };
643        resolve_path(&raw, &cwd)
644    } else {
645        let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
646        let fd_table = unsafe { &*task.process.fd_table.get() };
647        let dir_file = fd_table.get(dir_fd as u32)?;
648        let dir_path = dir_file.path();
649        resolve_path(&raw, dir_path)
650    };
651
652    crate::silo::enforce_path_for_current_task(&abs, true, false, false)?;
653    let st = stat_path(&abs)?;
654    check_access_permissions(&st, mode as u32)?;
655    Ok(0)
656}
657
658/// POSIX access mode flags
659const F_OK: u32 = 0;
660const R_OK: u32 = 4;
661const W_OK: u32 = 2;
662const X_OK: u32 = 1;
663
664/// Check file permissions against the access mode.
665///
666/// F_OK (0): just check that the file exists (already done by stat_path).
667/// R_OK/W_OK/X_OK: check the corresponding permission bits for the current
668/// process's real UID/GID (access() semantics).
669fn check_access_permissions(st: &FileStat, mode: u32) -> Result<(), SyscallError> {
670    if mode == F_OK {
671        return Ok(()); // File exists (we got stat successfully)
672    }
673
674    // Get real UID/GID (access() uses REAL IDs, not effective)
675    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
676    let uid = task.uid.load(core::sync::atomic::Ordering::Relaxed);
677    let gid = task.gid.load(core::sync::atomic::Ordering::Relaxed);
678
679    let file_uid = st.st_uid;
680    let file_gid = st.st_gid;
681    let file_mode = st.st_mode;
682
683    let mut granted = 0u32;
684
685    // Owner permissions
686    if uid == file_uid {
687        if file_mode & 0o400 != 0 {
688            granted |= R_OK;
689        }
690        if file_mode & 0o200 != 0 {
691            granted |= W_OK;
692        }
693        if file_mode & 0o100 != 0 {
694            granted |= X_OK;
695        }
696    }
697    // Group permissions
698    if gid == file_gid {
699        if file_mode & 0o040 != 0 {
700            granted |= R_OK;
701        }
702        if file_mode & 0o020 != 0 {
703            granted |= W_OK;
704        }
705        if file_mode & 0o010 != 0 {
706            granted |= X_OK;
707        }
708    }
709    // Other permissions
710    if file_mode & 0o004 != 0 {
711        granted |= R_OK;
712    }
713    if file_mode & 0o002 != 0 {
714        granted |= W_OK;
715    }
716    if file_mode & 0o001 != 0 {
717        granted |= X_OK;
718    }
719
720    // Check that ALL requested bits are granted
721    if mode & !granted != 0 {
722        return Err(SyscallError::PermissionDenied);
723    }
724    Ok(())
725}
726
727/// Syscall handler for reading from a file.
728pub fn sys_read(fd: u32, buf_ptr: u64, buf_len: u64) -> Result<u64, SyscallError> {
729    if buf_len == 0 {
730        return Ok(0);
731    }
732
733    // Read directly into chunks to avoid large kernel allocations
734    let mut kbuf = [0u8; 4096];
735    let mut total_read = 0;
736
737    while total_read < buf_len as usize {
738        let to_read = core::cmp::min(kbuf.len(), buf_len as usize - total_read);
739        let n = read(fd, &mut kbuf[..to_read])?;
740        if n == 0 {
741            break;
742        }
743
744        let chunk_addr = buf_ptr
745            .checked_add(total_read as u64)
746            .ok_or(SyscallError::Fault)?;
747        let chunk_user = UserSliceWrite::new(chunk_addr, n)?;
748        chunk_user.copy_from(&kbuf[..n]);
749
750        total_read += n;
751        if n < to_read {
752            break;
753        }
754    }
755
756    Ok(total_read as u64)
757}
758
759/// Syscall handler for writing to a file.
760pub fn sys_write(fd: u32, buf_ptr: u64, buf_len: u64) -> Result<u64, SyscallError> {
761    if buf_len == 0 {
762        return Ok(0);
763    }
764
765    // For stdout/stderr, fall back to direct console output only when no
766    // FD entry exists (early boot).  Once the FD table is populated (or
767    // after dup2 redirection) the normal VFS path is used.
768    if fd == 1 || fd == 2 {
769        let use_console = match current_task_clone() {
770            Some(t) => {
771                let fd_table = unsafe { &*t.process.fd_table.get() };
772                !fd_table.contains(fd)
773            }
774            None => true,
775        };
776        if use_console {
777            crate::silo::enforce_console_access()?;
778            let len = core::cmp::min(buf_len as usize, 16 * 1024);
779            let mut kbuf = [0u8; 4096];
780            let mut total_written = 0;
781            while total_written < len {
782                let to_write = core::cmp::min(kbuf.len(), len - total_written);
783                let chunk_addr = buf_ptr
784                    .checked_add(total_written as u64)
785                    .ok_or(SyscallError::Fault)?;
786                let chunk = UserSliceRead::new(chunk_addr, to_write)?;
787                let n = chunk.copy_to(&mut kbuf[..to_write]);
788                if crate::arch::vga::is_available() {
789                    if let Ok(s) = core::str::from_utf8(&kbuf[..n]) {
790                        crate::serial_print!("{}", s);
791                        crate::vga_print!("{}", s);
792                    } else {
793                        for &byte in &kbuf[..n] {
794                            crate::serial_print!("{}", byte as char);
795                        }
796                    }
797                } else {
798                    for &byte in &kbuf[..n] {
799                        crate::serial_print!("{}", byte as char);
800                    }
801                }
802                total_written += n;
803            }
804            return Ok(total_written as u64);
805        }
806    }
807
808    // Device frames must reach the scheme in one piece: copy the complete
809    // user buffer and issue a single write instead of the 4 KiB chunk loop.
810    if buf_len <= MAX_ATOMIC_DEVICE_WRITE {
811        if let Some(task) = current_task_clone() {
812            // SAFETY: syscall context; the fd table belongs to the current task.
813            let fd_table = unsafe { &*task.process.fd_table.get() };
814            if let Ok(file) = fd_table.get(fd) {
815                let flags = file.flags();
816                if flags.contains(FileFlags::DEVICE) && flags.contains(FileFlags::CHUNK_WRITE) {
817                    let user = UserSliceRead::new(buf_ptr, buf_len as usize)?;
818                    let mut kbuf = alloc::vec![0u8; buf_len as usize];
819                    user.copy_to(&mut kbuf);
820                    let n = write(fd, &kbuf)?;
821                    return Ok(n as u64);
822                }
823            }
824        }
825    }
826
827    let mut kbuf = [0u8; 4096];
828    let mut total_written = 0;
829
830    while total_written < buf_len as usize {
831        let to_write = core::cmp::min(kbuf.len(), buf_len as usize - total_written);
832        let chunk_addr = buf_ptr
833            .checked_add(total_written as u64)
834            .ok_or(SyscallError::Fault)?;
835        let chunk_user = UserSliceRead::new(chunk_addr, to_write)?;
836        chunk_user.copy_to(&mut kbuf[..to_write]);
837
838        let n = write(fd, &kbuf[..to_write])?;
839        total_written += n;
840        if n < to_write {
841            break;
842        }
843    }
844
845    Ok(total_written as u64)
846}
847
848/// Syscall handler for closing a file.
849pub fn sys_close(fd: u32) -> Result<u64, SyscallError> {
850    close(fd)?;
851    Ok(0)
852}
853
854/// Syscall handler for lseek.
855pub fn sys_lseek(fd: u32, offset: i64, whence: u32) -> Result<u64, SyscallError> {
856    lseek(fd, offset, whence)
857}
858
859/// Syscall handler for fstat.
860pub fn sys_fstat(fd: u32, stat_ptr: u64) -> Result<u64, SyscallError> {
861    let st = fstat(fd)?;
862    let user = UserSliceWrite::new(stat_ptr, core::mem::size_of::<FileStat>())?;
863    let bytes = unsafe {
864        core::slice::from_raw_parts(
865            &st as *const FileStat as *const u8,
866            core::mem::size_of::<FileStat>(),
867        )
868    };
869    user.copy_from(bytes);
870    Ok(0)
871}
872
873/// SYS_STAT (409): Get file status by path.
874pub fn sys_stat(path_ptr: u64, path_len: u64, stat_ptr: u64) -> Result<u64, SyscallError> {
875    let path = resolve_for_syscall(path_ptr, path_len, true, false, false)?;
876    let st = stat_path(&path)?;
877    let user_out = UserSliceWrite::new(stat_ptr, core::mem::size_of::<FileStat>())?;
878    let out_bytes = unsafe {
879        core::slice::from_raw_parts(
880            &st as *const FileStat as *const u8,
881            core::mem::size_of::<FileStat>(),
882        )
883    };
884    user_out.copy_from(out_bytes);
885    Ok(0)
886}
887
888/// Syscall handler for getdents.
889///
890/// Writes a packed array of `KernelDirent` entries into the user buffer.
891/// Returns the number of bytes written.
892pub fn sys_getdents(fd: u32, buf_ptr: u64, buf_len: u64) -> Result<u64, SyscallError> {
893    use strat9_abi::data::DirentHeader;
894
895    let entries = getdents(fd)?;
896    let mut offset: usize = 0;
897    let buf_size = buf_len as usize;
898
899    for entry in &entries {
900        let name_bytes = entry.name.as_bytes();
901        let name_len = core::cmp::min(name_bytes.len(), 255) as u16;
902        let entry_size = DirentHeader::SIZE + name_len as usize + 1;
903
904        if offset + entry_size > buf_size {
905            break;
906        }
907
908        let user = UserSliceWrite::new(buf_ptr + offset as u64, entry_size)?;
909        let mut kbuf = [0u8; 268];
910        kbuf[0..8].copy_from_slice(&entry.ino.to_le_bytes());
911        kbuf[8] = entry.file_type;
912        kbuf[9..11].copy_from_slice(&name_len.to_le_bytes());
913        kbuf[11] = 0; // DirentHeader::_padding
914        kbuf[12..12 + name_len as usize].copy_from_slice(&name_bytes[..name_len as usize]);
915        kbuf[12 + name_len as usize] = 0;
916        user.copy_from(&kbuf[..entry_size]);
917
918        offset += entry_size;
919    }
920
921    Ok(offset as u64)
922}
923
924/// Syscall handler for pipe.
925pub fn sys_pipe(fds_ptr: u64) -> Result<u64, SyscallError> {
926    let (read_fd, write_fd) = pipe()?;
927    let user = UserSliceWrite::new(fds_ptr, 8)?; // 2 x u32
928    let mut buf = [0u8; 8];
929    buf[0..4].copy_from_slice(&read_fd.to_le_bytes());
930    buf[4..8].copy_from_slice(&write_fd.to_le_bytes());
931    user.copy_from(&buf);
932    Ok(0)
933}
934
935/// Syscall handler for dup.
936pub fn sys_dup(old_fd: u32) -> Result<u64, SyscallError> {
937    let new_fd = dup(old_fd)?;
938    Ok(new_fd as u64)
939}
940
941/// Syscall handler for dup2.
942pub fn sys_dup2(old_fd: u32, new_fd: u32) -> Result<u64, SyscallError> {
943    let fd = dup2(old_fd, new_fd)?;
944    Ok(fd as u64)
945}
946
947// ========== Path helpers ==============================
948
949/// Read a NUL-terminated or length-bounded path from user space.
950///
951/// `path_ptr` and `path_len` come directly from syscall arguments.
952/// If `path_len` is 0 the string is assumed to be NUL-terminated up to 4096 bytes.
953fn read_user_path(path_ptr: u64, path_len: u64) -> Result<alloc::string::String, SyscallError> {
954    const MAX_PATH: usize = 4096;
955    let len = if path_len == 0 || path_len as usize > MAX_PATH {
956        MAX_PATH
957    } else {
958        path_len as usize
959    };
960    let user = UserSliceRead::new(path_ptr, len)?;
961    let bytes = user.read_to_vec();
962    // Trim at first NUL byte if present.
963    let trimmed = bytes.split(|&b| b == 0).next().unwrap_or(&bytes);
964    if trimmed.is_empty() {
965        return Err(SyscallError::InvalidArgument);
966    }
967    core::str::from_utf8(trimmed)
968        .map(|s| alloc::string::String::from(s))
969        .map_err(|_| SyscallError::InvalidArgument)
970}
971
972/// Resolve a userspace path to an absolute path and enforce silo policy.
973///
974/// Combines: read_user_path => resolve against CWD => silo enforce.
975/// Used by most syscall handlers to avoid duplicating this 4-line pattern.
976fn resolve_for_syscall(
977    path_ptr: u64,
978    path_len: u64,
979    want_read: bool,
980    want_write: bool,
981    want_execute: bool,
982) -> Result<alloc::string::String, SyscallError> {
983    const MAX_PATH_LEN: usize = 4096;
984    if path_len == 0 || path_len as usize > MAX_PATH_LEN {
985        return Err(SyscallError::InvalidArgument);
986    }
987    let raw = read_user_path(path_ptr, path_len)?;
988    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
989    let cwd = unsafe { (&*task.process.cwd.get()).clone() };
990    let abs = resolve_path(&raw, &cwd);
991    crate::silo::enforce_path_for_current_task(&abs, want_read, want_write, want_execute)?;
992    Ok(abs)
993}
994
995/// Resolve `path` relative to the current working directory when it is not
996/// absolute. Returns the normalized absolute path.
997fn resolve_path(path: &str, cwd: &str) -> alloc::string::String {
998    let raw = if path.starts_with('/') {
999        alloc::string::String::from(path)
1000    } else if cwd.ends_with('/') {
1001        alloc::format!("{}{}", cwd, path)
1002    } else {
1003        alloc::format!("{}/{}", cwd, path)
1004    };
1005    normalize_path(&raw)
1006}
1007
1008/// Collapse `.`, `..` and duplicate `/` in an absolute path.
1009fn normalize_path(path: &str) -> alloc::string::String {
1010    let mut parts: alloc::vec::Vec<&str> = alloc::vec::Vec::new();
1011    for seg in path.split('/') {
1012        match seg {
1013            "" | "." => {}
1014            ".." => {
1015                parts.pop();
1016            }
1017            other => parts.push(other),
1018        }
1019    }
1020    let mut out = alloc::string::String::with_capacity(path.len());
1021    if parts.is_empty() {
1022        out.push('/');
1023    } else {
1024        for p in &parts {
1025            out.push('/');
1026            out.push_str(p);
1027        }
1028    }
1029    out
1030}
1031
1032// ========== New VFS syscall handlers ================================================================================================================================================================
1033
1034/// SYS_CHDIR (440): Change current working directory.
1035pub fn sys_chdir(path_ptr: u64, path_len: u64) -> Result<u64, SyscallError> {
1036    let abs = resolve_for_syscall(path_ptr, path_len, true, false, false)?;
1037
1038    let (scheme, rel) = mount::resolve(&abs)?;
1039    let res = scheme.open(&rel, OpenFlags::READ | OpenFlags::DIRECTORY)?;
1040    let _ = scheme.close(res.file_id);
1041
1042    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1043    unsafe { *task.process.cwd.get() = abs };
1044    Ok(0)
1045}
1046
1047/// SYS_FCHDIR (441): Change cwd using an open file descriptor.
1048pub fn sys_fchdir(fd: u32) -> Result<u64, SyscallError> {
1049    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1050    let path = {
1051        let fd_table = unsafe { &*task.process.fd_table.get() };
1052        let file = fd_table.get(fd)?;
1053        alloc::string::String::from(file.path())
1054    };
1055    unsafe { *task.process.cwd.get() = path };
1056    Ok(0)
1057}
1058
1059/// SYS_GETCWD (442): Write the current working directory into a user buffer.
1060pub fn sys_getcwd(buf_ptr: u64, buf_len: u64) -> Result<u64, SyscallError> {
1061    if buf_len == 0 {
1062        return Err(SyscallError::InvalidArgument);
1063    }
1064    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1065    let cwd = unsafe { (&*task.process.cwd.get()).clone() };
1066    let bytes = cwd.as_bytes();
1067    let needed = bytes.len() + 1;
1068    if needed > buf_len as usize {
1069        return Err(SyscallError::Range);
1070    }
1071    let out = UserSliceWrite::new(buf_ptr, needed)?;
1072    let mut tmp = alloc::vec![0u8; needed];
1073    tmp[..bytes.len()].copy_from_slice(bytes);
1074    tmp[bytes.len()] = 0;
1075    out.copy_from(&tmp);
1076    Ok(needed as u64)
1077}
1078
1079/// SYS_IOCTL (443): I/O control : stub.
1080///
1081/// Returns ENOTTY for all file descriptors that are not character devices.
1082/// Terminal / PTY support will be added when a TTY driver is implemented.
1083pub fn sys_ioctl(_fd: u32, _request: u64, _arg: u64) -> Result<u64, SyscallError> {
1084    Err(SyscallError::NotATty)
1085}
1086
1087/// SYS_UMASK (444): Set file creation mask; return the old mask.
1088pub fn sys_umask(mask: u64) -> Result<u64, SyscallError> {
1089    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1090    let old = task
1091        .process
1092        .umask
1093        .swap(mask as u32 & 0o777, core::sync::atomic::Ordering::Relaxed);
1094    Ok(old as u64)
1095}
1096
1097/// SYS_UNLINK (445): Remove a file.
1098pub fn sys_unlink(path_ptr: u64, path_len: u64) -> Result<u64, SyscallError> {
1099    let abs = resolve_for_syscall(path_ptr, path_len, false, true, false)?;
1100    unlink(&abs)?;
1101    Ok(0)
1102}
1103
1104/// SYS_RMDIR (446): Remove an empty directory.
1105pub fn sys_rmdir(path_ptr: u64, path_len: u64) -> Result<u64, SyscallError> {
1106    let abs = resolve_for_syscall(path_ptr, path_len, false, true, false)?;
1107    let st = stat_path(&abs)?;
1108    if st.st_mode & 0o170000 != 0o040000 {
1109        return Err(SyscallError::InvalidArgument);
1110    }
1111    unlink(&abs)?;
1112    Ok(0)
1113}
1114
1115/// SYS_MKDIR (447): Create a directory.
1116pub fn sys_mkdir(path_ptr: u64, path_len: u64, mode: u64) -> Result<u64, SyscallError> {
1117    let abs = resolve_for_syscall(path_ptr, path_len, false, true, false)?;
1118    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1119    let umask = task
1120        .process
1121        .umask
1122        .load(core::sync::atomic::Ordering::Relaxed);
1123    let effective_mode = (mode as u32) & !umask;
1124    mkdir(&abs, effective_mode)?;
1125    Ok(0)
1126}
1127
1128/// SYS_RENAME (448): Rename a file or directory.
1129pub fn sys_rename(
1130    old_ptr: u64,
1131    old_len: u64,
1132    new_ptr: u64,
1133    new_len: u64,
1134) -> Result<u64, SyscallError> {
1135    let old_abs = resolve_for_syscall(old_ptr, old_len, true, true, false)?;
1136    let new_abs = resolve_for_syscall(new_ptr, new_len, false, true, false)?;
1137    rename(&old_abs, &new_abs)?;
1138    Ok(0)
1139}
1140
1141/// SYS_LINK (449): Create a hard link.
1142pub fn sys_link(
1143    old_ptr: u64,
1144    old_len: u64,
1145    new_ptr: u64,
1146    new_len: u64,
1147) -> Result<u64, SyscallError> {
1148    let old_abs = resolve_for_syscall(old_ptr, old_len, true, false, false)?;
1149    let new_abs = resolve_for_syscall(new_ptr, new_len, false, true, false)?;
1150    link(&old_abs, &new_abs)?;
1151    Ok(0)
1152}
1153
1154/// SYS_SYMLINK (450): Create a symbolic link.
1155pub fn sys_symlink(
1156    target_ptr: u64,
1157    target_len: u64,
1158    linkpath_ptr: u64,
1159    linkpath_len: u64,
1160) -> Result<u64, SyscallError> {
1161    let target = read_user_path(target_ptr, target_len)?;
1162    let link_abs = resolve_for_syscall(linkpath_ptr, linkpath_len, false, true, false)?;
1163    symlink(&target, &link_abs)?;
1164    Ok(0)
1165}
1166
1167/// SYS_READLINK (451): Read a symbolic link.
1168pub fn sys_readlink(
1169    path_ptr: u64,
1170    path_len: u64,
1171    buf_ptr: u64,
1172    buf_len: u64,
1173) -> Result<u64, SyscallError> {
1174    let abs = resolve_for_syscall(path_ptr, path_len, true, false, false)?;
1175    let target = readlink(&abs)?;
1176    let bytes = target.as_bytes();
1177    let n = bytes.len().min(buf_len as usize);
1178    let user = UserSliceWrite::new(buf_ptr, n)?;
1179    user.copy_from(&bytes[..n]);
1180    Ok(n as u64)
1181}
1182
1183/// SYS_CHMOD (452): Change file mode bits.
1184pub fn sys_chmod(path_ptr: u64, path_len: u64, mode: u64) -> Result<u64, SyscallError> {
1185    let abs = resolve_for_syscall(path_ptr, path_len, false, true, false)?;
1186    chmod(&abs, mode as u32)?;
1187    Ok(0)
1188}
1189
1190/// Set access/modification times of a path. See [`Scheme::utimens`].
1191pub fn utimens(
1192    path: &str,
1193    atime: scheme::TimeSpec,
1194    mtime: scheme::TimeSpec,
1195) -> Result<(), SyscallError> {
1196    let (scheme, relative_path) = mount::resolve(path)?;
1197    scheme.utimens(&relative_path, atime, mtime)
1198}
1199
1200/// SYS_UTIMENSAT (469): Set file access and modification times by path.
1201///
1202/// `times_ptr` points to `[TimeSpec; 2]` (atime, mtime); `0` means "both now".
1203pub fn sys_utimensat(
1204    path_ptr: u64,
1205    path_len: u64,
1206    times_ptr: u64,
1207    flags: u64,
1208) -> Result<u64, SyscallError> {
1209    use scheme::{UTIME_NOW, UTIME_OMIT};
1210    if flags != 0 {
1211        return Err(SyscallError::InvalidArgument);
1212    }
1213    let abs = resolve_for_syscall(path_ptr, path_len, false, true, false)?;
1214
1215    let now = |ns: u32| scheme::TimeSpec {
1216        tv_sec: 0,
1217        tv_nsec: ns as i64,
1218    };
1219    let (atime, mtime) = if times_ptr == 0 {
1220        (now(UTIME_NOW), now(UTIME_NOW))
1221    } else {
1222        let sz = core::mem::size_of::<scheme::TimeSpec>();
1223        let a = UserSliceRead::new(times_ptr, sz)?
1224            .read_val::<scheme::TimeSpec>()
1225            .map_err(|_| SyscallError::Fault)?;
1226        let m = UserSliceRead::new(times_ptr.checked_add(sz as u64).ok_or(SyscallError::Fault)?, sz)?
1227            .read_val::<scheme::TimeSpec>()
1228            .map_err(|_| SyscallError::Fault)?;
1229        for t in [&a, &m] {
1230            let special = t.tv_nsec == UTIME_NOW as i64 || t.tv_nsec == UTIME_OMIT as i64;
1231            if !special && !(0..1_000_000_000).contains(&t.tv_nsec) {
1232                return Err(SyscallError::InvalidArgument);
1233            }
1234        }
1235        (a, m)
1236    };
1237    utimens(&abs, atime, mtime)?;
1238    Ok(0)
1239}
1240
1241/// SYS_TRUNCATE (454): Truncate file to given length.
1242pub fn sys_truncate(path_ptr: u64, path_len: u64, length: u64) -> Result<u64, SyscallError> {
1243    let abs = resolve_for_syscall(path_ptr, path_len, false, true, false)?;
1244    truncate(&abs, length)?;
1245    Ok(0)
1246}
1247
1248/// SYS_FCHMOD (453): Change file mode bits on open fd.
1249pub fn sys_fchmod(fd: u32, mode: u64) -> Result<u64, SyscallError> {
1250    fchmod(fd, mode as u32)?;
1251    Ok(0)
1252}
1253
1254/// SYS_FTRUNCATE (455): Truncate open fd to given length.
1255pub fn sys_ftruncate(fd: u32, length: u64) -> Result<u64, SyscallError> {
1256    ftruncate(fd, length)?;
1257    Ok(0)
1258}
1259
1260/// SYS_PREAD (456): Read at offset without changing fd position.
1261pub fn sys_pread(fd: u32, buf_ptr: u64, buf_len: u64, offset: u64) -> Result<u64, SyscallError> {
1262    if buf_len == 0 {
1263        return Ok(0);
1264    }
1265    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1266    let fd_table = unsafe { &*task.process.fd_table.get() };
1267    let file = fd_table.get(fd)?;
1268    let mut kbuf = [0u8; 4096];
1269    let mut total = 0usize;
1270    let mut off = offset;
1271    while total < buf_len as usize {
1272        let to_read = core::cmp::min(kbuf.len(), buf_len as usize - total);
1273        let n = file.pread(off, &mut kbuf[..to_read])?;
1274        if n == 0 {
1275            break;
1276        }
1277        let user = UserSliceWrite::new(
1278            buf_ptr
1279                .checked_add(total as u64)
1280                .ok_or(SyscallError::Fault)?,
1281            n,
1282        )?;
1283        user.copy_from(&kbuf[..n]);
1284        total += n;
1285        off += n as u64;
1286        if n < to_read {
1287            break;
1288        }
1289    }
1290    Ok(total as u64)
1291}
1292
1293/// SYS_PWRITE (457): Write at offset without changing fd position.
1294pub fn sys_pwrite(fd: u32, buf_ptr: u64, buf_len: u64, offset: u64) -> Result<u64, SyscallError> {
1295    if buf_len == 0 {
1296        return Ok(0);
1297    }
1298    let task = current_task_clone().ok_or(SyscallError::PermissionDenied)?;
1299    let fd_table = unsafe { &*task.process.fd_table.get() };
1300    let file = fd_table.get(fd)?;
1301    let mut kbuf = [0u8; 4096];
1302    let mut total = 0usize;
1303    let mut off = offset;
1304    while total < buf_len as usize {
1305        let to_write = core::cmp::min(kbuf.len(), buf_len as usize - total);
1306        let user = UserSliceRead::new(
1307            buf_ptr
1308                .checked_add(total as u64)
1309                .ok_or(SyscallError::Fault)?,
1310            to_write,
1311        )?;
1312        user.copy_to(&mut kbuf[..to_write]);
1313        let n = file.pwrite(off, &kbuf[..to_write])?;
1314        total += n;
1315        off += n as u64;
1316        if n < to_write {
1317            break;
1318        }
1319    }
1320    Ok(total as u64)
1321}
1322
1323/// SYS_FSYNC (458): Synchronize file in-core state with storage.
1324pub fn sys_fsync(fd: u32) -> Result<u64, SyscallError> {
1325    fsync(fd)?;
1326    Ok(0)
1327}
1328
1329/// SYS_FDATASYNC (459): Synchronize file data (not metadata) with storage.
1330pub fn sys_fdatasync(fd: u32) -> Result<u64, SyscallError> {
1331    fsync(fd)?;
1332    Ok(0)
1333}
1334
1335// ============================================================================
1336// Global PipeScheme singleton
1337// ============================================================================
1338
1339static PIPE_SCHEME: SpinLock<Option<Arc<PipeScheme>>> = SpinLock::new(None);
1340
1341/// Returns pipe scheme.
1342fn get_pipe_scheme() -> Arc<PipeScheme> {
1343    let mut guard = PIPE_SCHEME.lock();
1344    if let Some(ref scheme) = *guard {
1345        return scheme.clone();
1346    }
1347    let scheme = Arc::new(PipeScheme::new());
1348    *guard = Some(scheme.clone());
1349    scheme
1350}
1351
1352/// Performs the build pci inventory text operation.
1353fn build_pci_inventory_text() -> String {
1354    #[cfg(target_arch = "x86_64")]
1355    {
1356        let devices = crate::hardware::pci_client::all_devices();
1357        let mut out = String::new();
1358        out.push_str("bus dev fn vendor device class subclass prog_if irq\n");
1359        for dev in devices.iter() {
1360            let _ = writeln!(
1361                out,
1362                "{:02x} {:02x} {} {:04x} {:04x} {:02x} {:02x} {:02x} {}",
1363                dev.address.bus,
1364                dev.address.device,
1365                dev.address.function,
1366                dev.vendor_id,
1367                dev.device_id,
1368                dev.class_code,
1369                dev.subclass,
1370                dev.prog_if,
1371                dev.interrupt_line
1372            );
1373        }
1374        return out;
1375    }
1376
1377    #[cfg(not(target_arch = "x86_64"))]
1378    {
1379        String::from("unsupported-arch\n")
1380    }
1381}
1382
1383// ============================================================================
1384// Initialization
1385// ============================================================================
1386
1387/// Initialize the VFS with default mounts.
1388pub fn init() {
1389    log::info!("[VFS] Initializing virtual file system");
1390
1391    //  Root filesystem (RamFS on "/") ========================================================================================================================
1392    // Must be mounted before any other scheme so that longest-prefix resolution
1393    // falls back to "/" for paths not covered by a more specific mount point.
1394    let rootfs = alloc::sync::Arc::new(RamfsScheme::new());
1395    if let Err(e) = mount::mount("/", rootfs.clone(), None) {
1396        log::error!("[VFS] Failed to mount /: {:?}", e);
1397    } else {
1398        // Populate the standard POSIX directory skeleton.
1399        for dir in &[
1400            "bin", "sbin", "etc", "tmp", "usr", "lib", "lib64", "home", "root", "run", "var",
1401            "mnt", "opt", "srv", "dev", "proc", "sys",
1402        ] {
1403            rootfs.ensure_dir(dir);
1404        }
1405        // Nested standard directories
1406        rootfs.ensure_dir("usr/bin");
1407        rootfs.ensure_dir("usr/sbin");
1408        rootfs.ensure_dir("usr/lib");
1409        rootfs.ensure_dir("var/log");
1410        rootfs.ensure_dir("var/tmp");
1411        rootfs.ensure_dir("run/lock");
1412        log::info!("[VFS] Mounted / (ramfs) with standard directory tree");
1413    }
1414
1415    // Initialize scheme router
1416    if let Err(e) = scheme_router::init_builtin_schemes() {
1417        log::error!("[VFS] Failed to init builtin schemes: {:?}", e);
1418    }
1419
1420    // Create and mount kernel scheme for /sys
1421    let kernel_scheme = KernelScheme::new();
1422
1423    // Register some basic kernel files
1424    static VERSION: &[u8] = b"Strat9-OS v0.1.0 (Bedrock)\n";
1425    kernel_scheme.register("version", VERSION.as_ptr(), VERSION.len());
1426
1427    static CMDLINE: &[u8] = b"quiet loglevel=debug\n";
1428    kernel_scheme.register("cmdline", CMDLINE.as_ptr(), CMDLINE.len());
1429
1430    let pci_inventory = build_pci_inventory_text().into_bytes().into_boxed_slice();
1431    let pci_inventory = Box::leak(pci_inventory);
1432    kernel_scheme.register("pci/inventory", pci_inventory.as_ptr(), pci_inventory.len());
1433
1434    let pci_count = pci_inventory
1435        .split(|b| *b == b'\n')
1436        .skip(1)
1437        .filter(|line| !line.is_empty())
1438        .count();
1439    let mut pci_count_str = String::new();
1440    let _ = writeln!(pci_count_str, "{}", pci_count);
1441    let pci_count = Box::leak(pci_count_str.into_bytes().into_boxed_slice());
1442    kernel_scheme.register("pci/count", pci_count.as_ptr(), pci_count.len());
1443
1444    // /sys/cpu/* : CPU information scheme (Plan9-style)
1445    #[cfg(target_arch = "x86_64")]
1446    {
1447        let host = crate::arch::cpuid::host();
1448        // VFS initializes before SMP/percpu registration is complete.
1449        // Expose at least 1 CPU (BSP) instead of showing 0.
1450        let cpu_count = crate::arch::percpu::online_count().max(1);
1451
1452        let count_s = Box::leak(
1453            alloc::format!("{}\n", cpu_count)
1454                .into_bytes()
1455                .into_boxed_slice(),
1456        );
1457        kernel_scheme.register("cpu/count", count_s.as_ptr(), count_s.len());
1458
1459        let vendor_s = Box::leak(
1460            alloc::format!("{}\n", host.vendor_string())
1461                .into_bytes()
1462                .into_boxed_slice(),
1463        );
1464        kernel_scheme.register("cpu/vendor", vendor_s.as_ptr(), vendor_s.len());
1465
1466        let model_s = Box::leak(
1467            alloc::format!("{}\n", host.model_name_str())
1468                .into_bytes()
1469                .into_boxed_slice(),
1470        );
1471        kernel_scheme.register("cpu/model", model_s.as_ptr(), model_s.len());
1472
1473        let features_s = Box::leak(
1474            alloc::format!(
1475                "{}\n",
1476                crate::arch::cpuid::features_to_flags_string(host.features)
1477            )
1478            .into_bytes()
1479            .into_boxed_slice(),
1480        );
1481        kernel_scheme.register("cpu/features", features_s.as_ptr(), features_s.len());
1482
1483        let xcr0_s = Box::leak(
1484            alloc::format!("{:#x}\n", host.supported_xcr0)
1485                .into_bytes()
1486                .into_boxed_slice(),
1487        );
1488        kernel_scheme.register("cpu/xcr0", xcr0_s.as_ptr(), xcr0_s.len());
1489
1490        let xsave_s = Box::leak(
1491            alloc::format!("{}\n", host.xsave_size_current)
1492                .into_bytes()
1493                .into_boxed_slice(),
1494        );
1495        kernel_scheme.register("cpu/xsave_size", xsave_s.as_ptr(), xsave_s.len());
1496    }
1497
1498    #[cfg(target_arch = "riscv64")]
1499    {
1500        let cpu_count = crate::arch::percpu::get_cpu_count().max(1);
1501        let register_cpu_value = |path: &str, value: &str| {
1502            let bytes = Box::leak(
1503                alloc::format!("{}\n", value)
1504                    .into_bytes()
1505                    .into_boxed_slice(),
1506            );
1507            kernel_scheme.register(path, bytes.as_ptr(), bytes.len());
1508        };
1509
1510        register_cpu_value("cpu/count", &alloc::format!("{}", cpu_count));
1511        register_cpu_value("cpu/vendor", "not discovered");
1512        register_cpu_value("cpu/model", "not discovered");
1513        register_cpu_value("cpu/features", "not discovered (DTB support pending)");
1514        register_cpu_value("cpu/xcr0", "not applicable");
1515        register_cpu_value("cpu/xsave_size", "not applicable");
1516    }
1517
1518    let kernel_scheme = Arc::new(kernel_scheme);
1519
1520    // Mount /sys
1521    if let Err(e) = mount::mount("/sys", kernel_scheme.clone(), None) {
1522        log::error!("[VFS] Failed to mount /sys: {:?}", e);
1523    } else {
1524        log::info!("[VFS] Mounted /sys (kernel scheme)");
1525    }
1526
1527    // Register and mount procfs
1528    let proc_scheme = Arc::new(ProcScheme::new());
1529    if let Err(e) = register_scheme("proc", proc_scheme.clone()) {
1530        log::error!("[VFS] Failed to register proc scheme: {:?}", e);
1531    } else {
1532        log::info!("[VFS] Registered proc scheme");
1533    }
1534
1535    if let Err(e) = mount::mount("/proc", proc_scheme, None) {
1536        log::error!("[VFS] Failed to mount /proc: {:?}", e);
1537    } else {
1538        log::info!("[VFS] Mounted /proc (procfs)");
1539    }
1540
1541    // Mount /thread : Plan 9 style thread control files (ThreadsScheme)
1542    let threads = Arc::new(threads_scheme::ThreadsScheme::new());
1543    if let Err(e) = mount::mount("/thread", threads, None) {
1544        log::error!("[VFS] Failed to mount /thread: {:?}", e);
1545    } else {
1546        log::info!("[VFS] Mounted /thread (threads scheme)");
1547    }
1548
1549    let ipc_scheme = Arc::new(ipcfs::IpcControlScheme::new());
1550    if let Err(e) = mount::mount("/ipc", ipc_scheme, None) {
1551        log::error!("[VFS] Failed to mount /ipc: {:?}", e);
1552    } else {
1553        log::info!("[VFS] Mounted /ipc (kernel ipc control scheme)");
1554    }
1555
1556    // Mount /dev : raw block-device scheme backed by AHCI.
1557    // The scheme is registered regardless of whether a disk is present:
1558    // device files appear dynamically when the hardware is available.
1559    let dev_scheme = Arc::new(BlkDevScheme::new());
1560    if let Err(e) = mount::mount("/dev", dev_scheme, None) {
1561        log::error!("[VFS] Failed to mount /dev: {:?}", e);
1562    } else {
1563        log::info!("[VFS] Mounted /dev (block-device scheme)");
1564    }
1565
1566    // Display scheme (/dev/vasistas) : registered by the framebuffer init, but
1567    // mount it here as a safety net (ordering between FB and VFS init is not
1568    // guaranteed, and a duplicate mount is harmless).
1569    //
1570    // Two outcomes are expected and silent:
1571    //   - AlreadyExists : framebuffer init already mounted it;
1572    //   - BadHandle     : the "vasistas" scheme is not registered yet, which is
1573    //                     the normal case here : framebuffer init runs later and
1574    //                     performs the authoritative register + mount.
1575    // Anything else is a real failure worth a warning.
1576    match mount_scheme("vasistas", "/dev/vasistas") {
1577        Ok(()) => log::info!("[VFS] Mounted /dev/vasistas (vasistas scheme)"),
1578        Err(SyscallError::AlreadyExists) | Err(SyscallError::BadHandle) => {}
1579        Err(e) => log::warn!("[VFS] /dev/vasistas not mounted: {:?}", e),
1580    }
1581
1582    // Console scheme (/dev/console) : backs stdin/stdout/stderr for ELF processes
1583    let console = console_scheme::init_console_scheme();
1584    if let Err(e) = mount::mount("/dev/console", console, None) {
1585        log::error!("[VFS] Failed to mount /dev/console: {:?}", e);
1586    } else {
1587        log::info!("[VFS] Mounted /dev/console (serial + keyboard)");
1588    }
1589
1590    // PTY scheme (/dev/pts) : pseudo-terminals for interactive programs
1591    pty_scheme::init_pty_scheme();
1592    log::info!("[VFS] Mounted /dev/pts (PTY scheme)");
1593
1594    // Input scheme (/dev/input) : raw keyboard and mouse events for userspace Input Server
1595    let input_scheme = Arc::new(input_scheme::InputScheme::new());
1596    if let Err(e) = mount::mount("/dev/input", input_scheme, None) {
1597        log::error!("[VFS] Failed to mount /dev/input: {:?}", e);
1598    } else {
1599        log::info!("[VFS] Mounted /dev/input (raw keyboard + mouse events)");
1600    }
1601
1602    // Bluetooth HCI scheme (`/dev/bt`). The USB probe may already have
1603    // registered it before `/dev` existed, so this call is idempotent and
1604    // retries the mount.
1605    bt_scheme::init_bt_scheme();
1606
1607    // Kernel boot log ring (`/dev/log`). The serial hook fills the ring from
1608    // the first formatted log record, so a late daemon can replay boot output.
1609    if let Err(e) = log_scheme::init_log_scheme() {
1610        log::warn!("[VFS] /dev/log not mounted: {:?}", e);
1611    }
1612
1613    // s9vm diagnostic view (`/dev/vmm`), read-only: mirrors the engine state
1614    // for userland tools without exposing any control operation.
1615    if let Err(e) = vmm_scheme::init_vmm_scheme() {
1616        log::warn!("[VFS] /dev/vmm not mounted: {:?}", e);
1617    }
1618
1619    // s9vm guest network relay (`/dev/vmm-net`): one directory per world with
1620    // `<id>/{tx,rx,info}`; frame boundaries are preserved in both directions.
1621    // `/net` is the host network namespace (userspace strate) and is left
1622    // untouched.
1623    if let Err(e) = vmm_net_scheme::init_vmm_net_scheme() {
1624        log::warn!("[VFS] /dev/vmm-net not mounted: {:?}", e);
1625    }
1626
1627    log::info!("[VFS] VFS ready");
1628}