ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! System call implementations.
//!
//! Each syscall validates its arguments, copies user data into kernel buffers
//! (TOCTOU defence), and delegates to the VFS layer in `crate::fs::vfs`.

use crate::errno;
use crate::serial_println;
use crate::syscall::user_ptr;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use spin::Mutex;

use crate::fs::{
    BlkFsMountMode, BlkFsMountOptions, BlockCache, BlockDeviceHandle, DummyBlockDev, File,
    FS_MANAGER, GLOBAL_FD_TABLE,
};

// ── File open flags (Linux-compatible) ──────────────────────────

pub mod open_flags {
    pub const O_RDONLY: usize = 0;
    pub const O_WRONLY: usize = 1;
    pub const O_RDWR: usize = 2;
    pub const O_CREAT: usize = 0x40;
    pub const O_TRUNC: usize = 0x200;
    pub const O_APPEND: usize = 0x400;
}

lazy_static! {
    static ref SYSCALL_MOUNT_DEVICES: Mutex<Vec<MountDeviceSlot>> = Mutex::new(Vec::new());
}

const DEFAULT_DUMMY_MOUNT_BLOCKS: usize = crate::fs::BLKFS_MIN_BLOCKS * 2;
const MAX_DUMMY_MOUNT_BLOCKS: usize = crate::fs::BLKFS_MIN_BLOCKS * 64;
const MAX_SYSCALL_MOUNT_DEVICE_SLOTS: usize = 16;

#[derive(Clone, Copy, PartialEq, Eq)]
enum MountDeviceSelector {
    Auto,
    Virtio,
    Dummy { blocks: usize },
}

struct MountRequest {
    path: String,
    device: MountDeviceSelector,
    options: BlkFsMountOptions,
}

struct MountDeviceSlot {
    mount_path: String,
    selector: MountDeviceSelector,
    virtio_backed: bool,
    dev: BlockDeviceHandle,
}

enum MountDeviceSlotChange {
    Unchanged,
    Inserted {
        mount_path: String,
    },
    Replaced {
        mount_path: String,
        selector: MountDeviceSelector,
        virtio_backed: bool,
        dev: BlockDeviceHandle,
    },
}

fn parse_mount_request(raw: &str) -> Result<MountRequest, &'static str> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err("Mount request is empty");
    }

    let (path_part, options_part) = match trimmed.split_once('?') {
        Some((path, options)) => (path.trim(), Some(options)),
        None => (trimmed, None),
    };
    if path_part.is_empty() {
        return Err("Mount path is empty");
    }
    let mount_path = normalize_syscall_mount_path(path_part)?;

    let mut device = MountDeviceSelector::Auto;
    let mut dummy_blocks: Option<usize> = None;
    let mut options = BlkFsMountOptions::default();

    if let Some(option_text) = options_part {
        for pair in option_text.split('&') {
            if pair.is_empty() {
                continue;
            }
            let (key, value) = pair
                .split_once('=')
                .ok_or("Mount option must be key=value")?;
            match key {
                "device" | "source" => {
                    device = match value {
                        "auto" => MountDeviceSelector::Auto,
                        "virtio" | "virtio-blk" => MountDeviceSelector::Virtio,
                        "dummy" | "ram" => MountDeviceSelector::Dummy {
                            blocks: DEFAULT_DUMMY_MOUNT_BLOCKS,
                        },
                        _ => return Err("Unsupported mount device"),
                    };
                }
                "blocks" => {
                    dummy_blocks = Some(parse_dummy_blocks(value)?);
                }
                "mode" => {
                    options.mode = parse_mount_mode(value)?;
                }
                "format" => {
                    options.mode = parse_format_option(value)?;
                }
                _ => return Err("Unsupported mount option"),
            }
        }
    }

    if let Some(blocks) = dummy_blocks {
        device = match device {
            MountDeviceSelector::Auto | MountDeviceSelector::Dummy { .. } => {
                MountDeviceSelector::Dummy { blocks }
            }
            MountDeviceSelector::Virtio => {
                return Err("blocks option requires dummy mount device");
            }
        };
    }

    Ok(MountRequest {
        path: mount_path,
        device,
        options,
    })
}

fn normalize_syscall_mount_path(path: &str) -> Result<String, &'static str> {
    let trimmed = path.trim();
    if !trimmed.starts_with('/') {
        return Err("Mount path must be absolute");
    }

    let dir_name = trimmed.trim_matches('/');
    if dir_name.is_empty() {
        return Err("Cannot mount over root");
    }
    if dir_name.contains('/') {
        return Err("Nested mount paths are not supported");
    }

    let mut mount_path = String::from("/");
    mount_path.push_str(dir_name);
    Ok(mount_path)
}

fn parse_dummy_blocks(raw: &str) -> Result<usize, &'static str> {
    let blocks = raw
        .parse::<usize>()
        .map_err(|_| "Invalid dummy block count")?;
    if blocks < crate::fs::BLKFS_MIN_BLOCKS {
        return Err("Dummy block device is too small for BlkFS");
    }
    if blocks > MAX_DUMMY_MOUNT_BLOCKS {
        return Err("Dummy block device is too large for teaching mount");
    }
    Ok(blocks)
}

fn parse_mount_mode(raw: &str) -> Result<BlkFsMountMode, &'static str> {
    match raw {
        "open-or-create" | "auto" => Ok(BlkFsMountMode::OpenOrCreate),
        "open-only" | "open" | "ro-open" => Ok(BlkFsMountMode::OpenOnly),
        "format" | "create" => Ok(BlkFsMountMode::Format),
        _ => Err("Unsupported BlkFS mount mode"),
    }
}

fn parse_format_option(raw: &str) -> Result<BlkFsMountMode, &'static str> {
    match raw {
        "always" | "true" | "1" => Ok(BlkFsMountMode::Format),
        "never" | "false" | "0" => Ok(BlkFsMountMode::OpenOnly),
        "auto" => Ok(BlkFsMountMode::OpenOrCreate),
        _ => Err("Unsupported format policy"),
    }
}

fn create_mount_device(
    selector: MountDeviceSelector,
) -> Result<(BlockDeviceHandle, bool), &'static str> {
    let mut virtio_backed = false;
    let raw: BlockDeviceHandle = match selector {
        MountDeviceSelector::Auto => {
            if let Some(virtio) = crate::block::VirtioBlkDev::probe() {
                virtio_backed = true;
                Arc::new(virtio)
            } else {
                Arc::new(DummyBlockDev::new(DEFAULT_DUMMY_MOUNT_BLOCKS))
            }
        }
        MountDeviceSelector::Virtio => {
            let virtio =
                crate::block::VirtioBlkDev::probe().ok_or("VirtIO block device not found")?;
            virtio_backed = true;
            Arc::new(virtio)
        }
        MountDeviceSelector::Dummy { blocks } => Arc::new(DummyBlockDev::new(blocks)),
    };
    Ok((Arc::new(BlockCache::new(raw)), virtio_backed))
}

fn device_for_mount_request(
    request: &MountRequest,
) -> Result<(BlockDeviceHandle, bool, MountDeviceSlotChange), &'static str> {
    {
        let devices = SYSCALL_MOUNT_DEVICES.lock();
        if let Some(slot) = devices.iter().find(|slot| slot.mount_path == request.path) {
            if slot.selector == request.device {
                return Ok((
                    Arc::clone(&slot.dev),
                    slot.virtio_backed,
                    MountDeviceSlotChange::Unchanged,
                ));
            }
        } else if devices.len() >= MAX_SYSCALL_MOUNT_DEVICE_SLOTS {
            return Err("Too many syscall-managed mount devices");
        }
    }

    let (dev, virtio_backed) = create_mount_device(request.device)?;

    let mut devices = SYSCALL_MOUNT_DEVICES.lock();
    if let Some(slot) = devices
        .iter_mut()
        .find(|slot| slot.mount_path == request.path)
    {
        if slot.selector == request.device {
            return Ok((
                Arc::clone(&slot.dev),
                slot.virtio_backed,
                MountDeviceSlotChange::Unchanged,
            ));
        }
        let change = MountDeviceSlotChange::Replaced {
            mount_path: request.path.clone(),
            selector: slot.selector,
            virtio_backed: slot.virtio_backed,
            dev: Arc::clone(&slot.dev),
        };
        slot.selector = request.device;
        slot.virtio_backed = virtio_backed;
        slot.dev = Arc::clone(&dev);
        return Ok((dev, virtio_backed, change));
    }

    if devices.len() >= MAX_SYSCALL_MOUNT_DEVICE_SLOTS {
        return Err("Too many syscall-managed mount devices");
    }
    devices.push(MountDeviceSlot {
        mount_path: request.path.clone(),
        selector: request.device,
        virtio_backed,
        dev: Arc::clone(&dev),
    });
    Ok((
        dev,
        virtio_backed,
        MountDeviceSlotChange::Inserted {
            mount_path: request.path.clone(),
        },
    ))
}

fn rollback_mount_device_slot(change: MountDeviceSlotChange) {
    match change {
        MountDeviceSlotChange::Unchanged => {}
        MountDeviceSlotChange::Inserted { mount_path } => {
            let mut devices = SYSCALL_MOUNT_DEVICES.lock();
            devices.retain(|slot| slot.mount_path != mount_path);
        }
        MountDeviceSlotChange::Replaced {
            mount_path,
            selector,
            virtio_backed,
            dev,
        } => {
            let mut devices = SYSCALL_MOUNT_DEVICES.lock();
            if let Some(slot) = devices
                .iter_mut()
                .find(|slot| slot.mount_path == mount_path)
            {
                slot.selector = selector;
                slot.virtio_backed = virtio_backed;
                slot.dev = dev;
            } else if devices.len() < MAX_SYSCALL_MOUNT_DEVICE_SLOTS {
                devices.push(MountDeviceSlot {
                    mount_path,
                    selector,
                    virtio_backed,
                    dev,
                });
            }
        }
    }
}

fn effective_mount_options(options: BlkFsMountOptions, virtio_backed: bool) -> BlkFsMountOptions {
    if virtio_backed && options.mode != BlkFsMountMode::Format {
        BlkFsMountOptions::open_only()
    } else {
        options
    }
}

fn file_for_fd(fd: usize, syscall: &str) -> Result<Arc<Mutex<dyn File>>, errno::Errno> {
    let fd_table = GLOBAL_FD_TABLE.lock();
    match fd_table.get(fd) {
        Some(file) => Ok(file),
        None => {
            serial_println!("[SYSCALL] {}: invalid fd={}", syscall, fd);
            Err(errno::EBADF)
        }
    }
}

// ── C-string reader ──────────────────────────────────────────────

/// Read a null-terminated C string from a user-space pointer.
///
/// # Safety
///
/// Caller must ensure `ptr` is a valid user-space address (or 0 for None).
/// Reads at most 4096 bytes to guard against unterminated strings.
/// The kernel reads user memory directly — PAGE_FAULT will trigger if the
/// address is unmapped.
pub fn read_c_string(ptr: usize) -> Option<String> {
    user_ptr::read_raw_c_string(ptr).ok()
}

// ── File-system syscalls ─────────────────────────────────────────

pub fn sys_read(fd: usize, buf: usize, len: usize) -> isize {
    serial_println!(
        "[SYSCALL] sys_read: fd={}, buf=0x{:x}, len={}",
        fd,
        buf,
        len
    );

    if len == 0 {
        return 0;
    }
    if buf == 0 {
        return errno::EINVAL;
    }

    // Handle stdin (fd 0) — block until input available
    if fd == 0 {
        let ch = loop {
            if let Some(c) = crate::task::keyboard::try_pop_char() {
                break c;
            }
            let ret: isize;
            unsafe {
                core::arch::asm!(
                    "li a7, 2",
                    "ecall",
                    "mv {}, a0",
                    out(reg) ret,
                    options(nostack)
                );
            }
            if ret >= 0 {
                break ret as u8;
            }
            riscv::asm::wfi();
        };
        if user_ptr::raw_copy_to_user(buf, &[ch]).is_err() {
            return errno::EFAULT;
        }
        return 1;
    }

    let file = match file_for_fd(fd, "sys_read") {
        Ok(file) => file,
        Err(errno) => return errno,
    };

    let capped = core::cmp::min(len, user_ptr::MAX_USER_COPY_LEN);
    let mut kernel_buf = alloc::vec![0u8; capped];
    let n = match file.lock().read(&mut kernel_buf) {
        Ok(n) => n,
        Err(e) => {
            serial_println!("[SYSCALL] sys_read: read failed: {:?}", e);
            return errno::from_file_error(e);
        }
    };

    if user_ptr::raw_copy_to_user(buf, &kernel_buf[..n]).is_err() {
        return errno::EFAULT;
    }

    serial_println!("[SYSCALL] sys_read: success, read {} bytes", n);
    n as isize
}

pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
    serial_println!(
        "[SYSCALL] sys_write: fd={}, buf=0x{:x}, len={}",
        fd,
        buf as usize,
        len
    );

    if len == 0 {
        return 0;
    }
    if buf.is_null() {
        return errno::EINVAL;
    }

    // Handle stdout/stderr directly (fd 1 and 2)
    if fd == 1 || fd == 2 {
        let kernel_buf = match user_ptr::raw_copy_from_user(buf, len) {
            Ok(bytes) => bytes,
            Err(errno) => return errno,
        };
        crate::serial::write_bytes(&kernel_buf);
        return kernel_buf.len() as isize;
    }

    let file = match file_for_fd(fd, "sys_write") {
        Ok(file) => file,
        Err(errno) => return errno,
    };

    let kernel_buf = match user_ptr::raw_copy_from_user(buf, len) {
        Ok(bytes) => bytes,
        Err(errno) => return errno,
    };

    let n = match file.lock().write(&kernel_buf) {
        Ok(n) => n,
        Err(e) => {
            serial_println!("[SYSCALL] sys_write: write failed: {:?}", e);
            return errno::from_file_error(e);
        }
    };

    serial_println!("[SYSCALL] sys_write: success, wrote {} bytes", n);
    n as isize
}

pub fn sys_open(path: usize, flags: usize) -> isize {
    serial_println!("[SYSCALL] sys_open: path=0x{:x}, flags=0x{:x}", path, flags);

    let path_str = match read_c_string(path) {
        Some(s) => s,
        None => {
            serial_println!("[SYSCALL] sys_open: invalid path pointer");
            return errno::EFAULT;
        }
    };
    serial_println!("[SYSCALL] sys_open: resolved path='{}'", path_str);

    let file: Arc<Mutex<dyn File>> = match crate::fs::vfs::open_file(&path_str) {
        Ok(f) => f,
        Err(_) if (flags & open_flags::O_CREAT) != 0 => {
            match crate::fs::vfs::create_file(&path_str) {
                Ok(f) => f,
                Err(e) => {
                    serial_println!("[SYSCALL] sys_open: create failed: {:?}", e);
                    return errno::from_file_error(e);
                }
            }
        }
        Err(e) => {
            serial_println!("[SYSCALL] sys_open: open failed: {:?}", e);
            return errno::from_file_error(e);
        }
    };

    let fd = match GLOBAL_FD_TABLE.lock().alloc(file) {
        Some(fd) => fd,
        None => {
            serial_println!("[SYSCALL] sys_open: no free fd");
            return errno::ENFILE;
        }
    };

    serial_println!("[SYSCALL] sys_open: success, fd={}, path={}", fd, path_str);
    fd as isize
}

pub fn sys_close(fd: usize) -> isize {
    serial_println!("[SYSCALL] sys_close: fd={}", fd);

    if GLOBAL_FD_TABLE.lock().dealloc(fd) {
        serial_println!("[SYSCALL] sys_close: success");
        0
    } else {
        serial_println!("[SYSCALL] sys_close: invalid fd={}", fd);
        errno::EBADF
    }
}

pub fn sys_mkdir(path: usize) -> isize {
    serial_println!("[SYSCALL] sys_mkdir: path=0x{:x}", path);

    let path_str = match read_c_string(path) {
        Some(s) => s,
        None => {
            serial_println!("[SYSCALL] sys_mkdir: invalid path pointer");
            return -1;
        }
    };

    match crate::fs::vfs::create_dir(&path_str) {
        Ok(()) => {
            serial_println!("[SYSCALL] sys_mkdir: success, created '{}'", path_str);
            0
        }
        Err(e) => {
            serial_println!("[SYSCALL] sys_mkdir: failed: {:?}", e);
            errno::from_file_error(e)
        }
    }
}

// ── Process syscalls ─────────────────────────────────────────────

pub fn sys_exit(exit_code: i32) -> isize {
    let _ = exit_code;
    sys_process_requires_trap_frame("exit")
}

pub fn sys_getpid() -> isize {
    1
}

/// Context-only dispatcher stub for process syscalls that require trap-frame
/// and scheduler context.
///
/// Real user-mode `fork`, `exec`, and `wait` traps are handled in
/// `interrupts::syscall_handler`, where the kernel has the live `TrapFrame`
/// needed by `process::{fork_current, exec_current, wait_current}`. Direct
/// dispatcher tests and kernel-internal calls do not have enough context, so
/// they fail explicitly with `ENOSYS` instead of implying a partial process
/// implementation lives here.
pub fn sys_process_requires_trap_frame(name: &str) -> isize {
    serial_println!(
        "[SYSCALL] sys_{} requires trap-frame process path; direct dispatcher is unsupported",
        name
    );
    errno::ENOSYS
}

pub fn sys_fork() -> isize {
    sys_process_requires_trap_frame("fork")
}

pub fn sys_exec(path: usize) -> isize {
    let _ = path;
    sys_process_requires_trap_frame("exec")
}

pub fn sys_wait(exit_code_ptr: usize) -> isize {
    let _ = exit_code_ptr;
    sys_process_requires_trap_frame("wait")
}

// ── Mount / unmount syscalls ─────────────────────────────────────

pub fn sys_mount(path: usize) -> isize {
    let path_str = match read_c_string(path) {
        Some(s) => s,
        None => return -1,
    };
    serial_println!("[SYSCALL] mount: path={}", path_str);
    let request = match parse_mount_request(&path_str) {
        Ok(request) => request,
        Err(e) => {
            serial_println!("[SYSCALL] mount: invalid request - {}", e);
            return errno::EINVAL;
        }
    };
    let (dev, virtio_backed, slot_change) = match device_for_mount_request(&request) {
        Ok(device) => device,
        Err(e) => {
            serial_println!("[SYSCALL] mount: device selection failed - {}", e);
            return errno::EINVAL;
        }
    };
    let options = effective_mount_options(request.options, virtio_backed);
    let mut mgr = FS_MANAGER.lock();
    match mgr.mount_blkfs_with_options(&request.path, dev, options) {
        Ok(()) => {
            serial_println!("[SYSCALL] mount: {} mounted", request.path);
            0
        }
        Err(e) => {
            rollback_mount_device_slot(slot_change);
            serial_println!("[SYSCALL] mount: failed - {}", e);
            errno::EINVAL
        }
    }
}

pub fn sys_umount(path: usize) -> isize {
    let path_str = match read_c_string(path) {
        Some(s) => s,
        None => return -1,
    };
    serial_println!("[SYSCALL] umount: path={}", path_str);
    let mut mgr = FS_MANAGER.lock();
    match mgr.umount(&path_str) {
        Ok(()) => {
            drop(mgr);
            serial_println!("[SYSCALL] umount: {} unmounted", path_str);
            0
        }
        Err(e) => {
            serial_println!("[SYSCALL] umount: failed - {}", e);
            -1
        }
    }
}

// ── Extended syscalls ──────────────────────────────────────────────

use crate::fs::SeekFrom;

pub fn sys_lseek(fd: usize, offset: isize, whence: usize) -> isize {
    let pos = match whence {
        0 => SeekFrom::Start(offset as usize),
        1 => SeekFrom::Current(offset),
        2 => SeekFrom::End(offset),
        _ => return -1,
    };
    let file = match file_for_fd(fd, "sys_lseek") {
        Ok(file) => file,
        Err(_) => return -1,
    };
    let result = file.lock().seek(pos);
    match result {
        Ok(new_offset) => new_offset as isize,
        Err(_) => -1,
    }
}

pub fn sys_unlink(path: usize) -> isize {
    let path_str = match read_c_string(path) {
        Some(s) => s,
        None => return -1,
    };
    serial_println!("[SYSCALL] unlink: path={}", path_str);
    match crate::fs::remove_file(&path_str) {
        Ok(()) => 0,
        Err(e) => {
            serial_println!("[SYSCALL] unlink: failed - {}", e);
            -1
        }
    }
}

pub fn sys_stat(path: usize, buf: usize) -> isize {
    let path_str = match read_c_string(path) {
        Some(s) => s,
        None => return -1,
    };
    let meta = match crate::fs::stat_path(&path_str) {
        Ok(m) => m,
        Err(e) => {
            serial_println!("[SYSCALL] stat: failed for {} - {}", path_str, e);
            return -1;
        }
    };
    if buf == 0 {
        return -1;
    }
    let st = Stat {
        st_dev: 0,
        st_ino: 0,
        st_mode: meta.mode,
        st_nlink: 1,
        st_uid: 0,
        st_gid: 0,
        st_rdev: 0,
        __pad1: 0,
        st_size: meta.size as u64,
        st_blksize: 512,
        __pad2: 0,
        st_blocks: (meta.size as u64).div_ceil(512),
    };
    if user_ptr::raw_write_value(buf, st).is_err() {
        return -1;
    }
    0
}

pub fn sys_getdents(fd_or_path: usize, buf: usize, len: usize) -> isize {
    if buf == 0 || len == 0 {
        return -1;
    }
    let path_str = match read_c_string(fd_or_path) {
        Some(s) => s,
        None => return -1,
    };
    let entries = match crate::fs::readdir_path(&path_str) {
        Ok(v) => v,
        Err(e) => {
            serial_println!("[SYSCALL] getdents: failed for {} - {}", path_str, e);
            return -1;
        }
    };
    let mut out = alloc::vec::Vec::new();
    for name in &entries {
        let line = name.as_bytes();
        if out.len() + line.len() + 1 > len {
            break;
        }
        out.extend_from_slice(line);
        out.push(b'\n');
    }
    if user_ptr::raw_copy_to_user(buf, &out).is_err() {
        return -1;
    }
    out.len() as isize
}

pub fn sys_dup2(old_fd: usize, new_fd: usize) -> isize {
    let mut fd_table = GLOBAL_FD_TABLE.lock();
    match fd_table.dup2(old_fd, new_fd) {
        Some(fd) => fd as isize,
        None => -1,
    }
}

// ── Pipe syscall ───────────────────────────────────────────────────

use crate::fs::pipe::make_pipe;

pub fn sys_pipe(fds_ptr: usize) -> isize {
    if fds_ptr == 0 {
        return -1;
    }
    let (read_end, write_end) = make_pipe();
    let read_arc = alloc::sync::Arc::new(spin::Mutex::new(read_end));
    let write_arc = alloc::sync::Arc::new(spin::Mutex::new(write_end));
    let mut fd_table = GLOBAL_FD_TABLE.lock();
    let fd0 = match fd_table.alloc(read_arc) {
        Some(fd) => fd as i32,
        None => return -1,
    };
    let fd1 = match fd_table.alloc(write_arc) {
        Some(fd) => fd as i32,
        None => {
            fd_table.dealloc(fd0 as usize);
            return -1;
        }
    };
    drop(fd_table);
    if user_ptr::raw_write_values(fds_ptr, &[fd0, fd1]).is_err() {
        let mut fd_table = GLOBAL_FD_TABLE.lock();
        fd_table.dealloc(fd0 as usize);
        fd_table.dealloc(fd1 as usize);
        return -1;
    }
    0
}

#[cfg(test)]
mod tests {
    use super::*;

    fn clear_mount_devices() {
        SYSCALL_MOUNT_DEVICES.lock().clear();
    }

    fn slot_count() -> usize {
        SYSCALL_MOUNT_DEVICES.lock().len()
    }

    #[test_case]
    fn mount_request_normalizes_slot_path_before_device_selection() {
        let request = parse_mount_request(" ///mnt/?device=dummy&blocks=512&mode=open-only")
            .expect("normalized mount request");
        assert_eq!(request.path.as_str(), "/mnt");
        assert!(request.device == MountDeviceSelector::Dummy { blocks: 512 });
        assert_eq!(request.options.mode, BlkFsMountMode::OpenOnly);

        assert_eq!(
            parse_mount_request("/mnt/data").err(),
            Some("Nested mount paths are not supported")
        );
        assert_eq!(
            parse_mount_request("/").err(),
            Some("Cannot mount over root")
        );
    }

    #[test_case]
    fn mount_request_blocks_option_is_dummy_only_and_order_independent() {
        assert_eq!(
            parse_mount_request("/mnt?device=virtio&blocks=512").err(),
            Some("blocks option requires dummy mount device")
        );
        assert_eq!(
            parse_mount_request("/mnt?blocks=512&device=virtio").err(),
            Some("blocks option requires dummy mount device")
        );

        let request = parse_mount_request("/mnt?blocks=512&device=dummy").expect("dummy request");
        assert!(request.device == MountDeviceSelector::Dummy { blocks: 512 });

        let request = parse_mount_request("/mnt?blocks=640").expect("implicit dummy request");
        assert!(request.device == MountDeviceSelector::Dummy { blocks: 640 });
    }

    #[test_case]
    fn virtio_backed_mounts_do_not_open_or_create_unless_format_is_explicit() {
        assert_eq!(
            effective_mount_options(BlkFsMountOptions::open_or_create(), true).mode,
            BlkFsMountMode::OpenOnly
        );
        assert_eq!(
            effective_mount_options(BlkFsMountOptions::open_only(), true).mode,
            BlkFsMountMode::OpenOnly
        );
        assert_eq!(
            effective_mount_options(BlkFsMountOptions::format(), true).mode,
            BlkFsMountMode::Format
        );
        assert_eq!(
            effective_mount_options(BlkFsMountOptions::open_or_create(), false).mode,
            BlkFsMountMode::OpenOrCreate
        );
    }

    #[test_case]
    fn mount_device_slot_insert_and_replace_changes_can_be_rolled_back() {
        clear_mount_devices();
        let original =
            parse_mount_request("/slot?device=dummy&blocks=512").expect("original request");
        let replacement =
            parse_mount_request("/slot/?device=dummy&blocks=640").expect("replacement request");

        let (_, _, inserted) = device_for_mount_request(&original).expect("insert slot");
        assert_eq!(slot_count(), 1);

        let (_, _, replaced) = device_for_mount_request(&replacement).expect("replace slot");
        assert_eq!(slot_count(), 1);
        {
            let devices = SYSCALL_MOUNT_DEVICES.lock();
            let slot = devices
                .iter()
                .find(|slot| slot.mount_path == "/slot")
                .expect("slot after replacement");
            assert!(slot.selector == replacement.device);
        }

        rollback_mount_device_slot(replaced);
        {
            let devices = SYSCALL_MOUNT_DEVICES.lock();
            let slot = devices
                .iter()
                .find(|slot| slot.mount_path == "/slot")
                .expect("slot after rollback");
            assert!(slot.selector == original.device);
        }

        rollback_mount_device_slot(inserted);
        assert_eq!(slot_count(), 0);
        clear_mount_devices();
    }

    #[test_case]
    fn mount_device_slots_are_retained_for_remount_and_rollback_is_explicit() {
        clear_mount_devices();
        let request = parse_mount_request("/norm?device=dummy&blocks=512").expect("request");
        let (_, _, inserted) = device_for_mount_request(&request).expect("insert slot");
        assert_eq!(slot_count(), 1);

        // sys_umount intentionally keeps this slot so a teaching dummy-backed
        // filesystem survives umount/remount. Failure rollback remains explicit.
        let (_, _, unchanged) = device_for_mount_request(&request).expect("reuse retained slot");
        assert_eq!(slot_count(), 1);
        assert!(matches!(unchanged, MountDeviceSlotChange::Unchanged));

        rollback_mount_device_slot(inserted);
        clear_mount_devices();
    }
}

/// Simplified stat structure (Linux-compatible layout, minimal fields).
#[derive(Clone, Copy)]
#[repr(C, packed)]
struct Stat {
    st_dev: u64,
    st_ino: u64,
    st_mode: u32,
    st_nlink: u32,
    st_uid: u32,
    st_gid: u32,
    st_rdev: u64,
    __pad1: u64,
    st_size: u64,
    st_blksize: u32,
    __pad2: u32,
    st_blocks: u64,
}