ahrightos-kernel 0.1.0

RISC-V 64 Rust teaching kernel for AhRightOS.
Documentation
/*
 * ============================================
 * 系统调用模块
 * ============================================
 * 功能:提供用户态程序与内核交互的接口
 *
 * 系统调用机制:
 * - 用户态通过 ecall 指令触发系统调用
 * - 系统调用号通过 a7 寄存器传递
 * - 参数通过 a0-a5 寄存器传递(最多6个参数)
 * - 返回值通过 a0 寄存器返回
 *
 * 支持的系统调用:
 * - sys_write: 写入数据到文件描述符
 * - sys_exit: 退出进程
 * - sys_getpid: 获取当前进程ID
 * ============================================
 */

pub mod syscall_impl;
pub mod user_ptr;

use crate::{errno, serial_println};

/// 系统调用号定义
/// 兼容Linux RISC-V系统调用号
#[repr(usize)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum SyscallId {
    // 文件系统系统调用(第7章)(任务点12-1,已提供)
    Mkdir = 34,  // sys_mkdir - 创建目录
    Mount = 40,  // sys_mount - 挂载文件系统
    Umount = 39, // sys_umount - 卸载文件系统
    Open = 56,   // sys_open - 打开/创建文件
    Close = 57,  // sys_close - 关闭文件描述符
    Read = 63,   // sys_read - 从文件读取
    Write = 64,  // sys_write - 写入文件

    // Extended system calls (G5)
    Unlink = 35,   // sys_unlink - 删除文件
    Lseek = 62,    // sys_lseek - 文件定位
    Getdents = 78, // sys_getdents - 读取目录项
    Stat = 1038,   // sys_stat - 获取文件状态
    Dup2 = 1041,   // sys_dup2 - 复制文件描述符
    Pipe = 59,     // sys_pipe - 创建管道

    // 进程系统调用(第6章)
    Exit = 93,    // sys_exit - 退出进程
    GetPid = 172, // sys_getpid - 获取进程ID
    Fork = 220,   // sys_fork - 复制进程
    Exec = 221,   // sys_exec - 替换进程映像
    Wait = 260,   // sys_wait - 等待子进程
    Unknown = 9999,
}

impl From<usize> for SyscallId {
    fn from(id: usize) -> Self {
        match id {
            // 文件系统系统调用
            34 => SyscallId::Mkdir,
            39 => SyscallId::Umount,
            40 => SyscallId::Mount,
            56 => SyscallId::Open,
            57 => SyscallId::Close,
            63 => SyscallId::Read,
            64 => SyscallId::Write,

            // Extended system calls (G5)
            35 => SyscallId::Unlink,
            62 => SyscallId::Lseek,
            78 => SyscallId::Getdents,
            1038 => SyscallId::Stat,
            1041 => SyscallId::Dup2,
            59 => SyscallId::Pipe,

            // 进程系统调用
            93 => SyscallId::Exit,
            172 => SyscallId::GetPid,
            220 => SyscallId::Fork,
            221 => SyscallId::Exec,
            260 => SyscallId::Wait,
            _ => SyscallId::Unknown,
        }
    }
}

impl SyscallId {
    /// Returns true for process-control syscalls that must be dispatched from
    /// the live user trap frame instead of the context-only dispatcher.
    ///
    /// These calls mutate the current process, scheduler state, or saved user
    /// registers. `syscall_dispatcher()` only receives a copied
    /// [`SyscallContext`], so it intentionally returns `ENOSYS` for this set.
    /// Real user-mode traps enter through [`syscall_trap_dispatcher()`].
    pub const fn requires_live_trap_frame(self) -> bool {
        match self {
            SyscallId::Exit | SyscallId::Fork | SyscallId::Exec | SyscallId::Wait => true,
            SyscallId::Mkdir
            | SyscallId::Mount
            | SyscallId::Umount
            | SyscallId::Open
            | SyscallId::Close
            | SyscallId::Read
            | SyscallId::Write
            | SyscallId::Unlink
            | SyscallId::Lseek
            | SyscallId::Getdents
            | SyscallId::Stat
            | SyscallId::Dup2
            | SyscallId::Pipe
            | SyscallId::GetPid
            | SyscallId::Unknown => false,
        }
    }

    pub const fn process_name(self) -> Option<&'static str> {
        match self {
            SyscallId::Exit => Some("exit"),
            SyscallId::Fork => Some("fork"),
            SyscallId::Exec => Some("exec"),
            SyscallId::Wait => Some("wait"),
            _ => None,
        }
    }
}

/// 系统调用上下文
///
/// 保存系统调用时的寄存器状态
#[derive(Debug, Clone, Copy)]
pub struct SyscallContext {
    /// 系统调用号 (a7)
    pub syscall_id: usize,
    /// 参数0 (a0)
    pub arg0: usize,
    /// 参数1 (a1)
    pub arg1: usize,
    /// 参数2 (a2)
    pub arg2: usize,
    /// 参数3 (a3)
    pub arg3: usize,
    /// 参数4 (a4)
    pub arg4: usize,
    /// 参数5 (a5)
    pub arg5: usize,
    /// 系统调用发生时的 PC
    pub sepc: usize,
}

impl SyscallContext {
    /// Build from trap frame (used when trap comes from real user mode).
    pub fn from_trap_frame(tf: &crate::interrupts::TrapFrame) -> Self {
        Self {
            syscall_id: tf.x[17], // a7
            arg0: tf.x[10],       // a0
            arg1: tf.x[11],       // a1
            arg2: tf.x[12],       // a2
            arg3: tf.x[13],       // a3
            arg4: tf.x[14],       // a4
            arg5: tf.x[15],       // a5
            sepc: tf.sepc,
        }
    }

    /// 从寄存器创建系统调用上下文(仅用于内核态直接调用测试)
    ///
    /// # Safety
    ///
    /// The current CPU registers must contain a valid syscall ABI snapshot.
    /// This helper is intended only for controlled kernel self-tests.
    pub unsafe fn from_registers() -> Self {
        let syscall_id: usize;
        let arg0: usize;
        let arg1: usize;
        let arg2: usize;
        let arg3: usize;
        let arg4: usize;
        let arg5: usize;

        core::arch::asm!(
            "mv {0}, a7",  // 读取系统调用号
            "mv {1}, a0",  // 读取参数
            "mv {2}, a1",
            "mv {3}, a2",
            "mv {4}, a3",
            "mv {5}, a4",
            "mv {6}, a5",
            out(reg) syscall_id,
            out(reg) arg0,
            out(reg) arg1,
            out(reg) arg2,
            out(reg) arg3,
            out(reg) arg4,
            out(reg) arg5,
        );

        let sepc = riscv::register::sepc::read();

        Self {
            syscall_id,
            arg0,
            arg1,
            arg2,
            arg3,
            arg4,
            arg5,
            sepc,
        }
    }

    /// 设置返回值
    ///
    /// # Safety
    /// 必须在系统调用处理完成后调用
    pub unsafe fn set_return_value(&self, ret: isize) {
        core::arch::asm!(
            "mv a0, {0}",
            in(reg) ret,
        );
    }
}

/// 系统调用分发器
///
/// # 参数
/// - `context`: 系统调用上下文
///
/// # 返回
/// 系统调用返回值(通过 a0 寄存器)
pub fn syscall_dispatcher(context: &SyscallContext) -> isize {
    let syscall_id = SyscallId::from(context.syscall_id);

    // 可视化输出:显示系统调用信息 (compile-time gated)
    #[cfg(feature = "verbose_syscall")]
    print_syscall_entry(context, syscall_id);

    let result = match syscall_id {
        // 文件系统系统调用
        SyscallId::Read => syscall_impl::sys_read(context.arg0, context.arg1, context.arg2),
        SyscallId::Write => {
            syscall_impl::sys_write(context.arg0, context.arg1 as *const u8, context.arg2)
        }
        SyscallId::Open => syscall_impl::sys_open(context.arg0, context.arg1),
        SyscallId::Close => syscall_impl::sys_close(context.arg0),
        SyscallId::Mkdir => syscall_impl::sys_mkdir(context.arg0),
        SyscallId::Mount => syscall_impl::sys_mount(context.arg0),
        SyscallId::Umount => syscall_impl::sys_umount(context.arg0),

        // Extended system calls (G5)
        SyscallId::Lseek => {
            syscall_impl::sys_lseek(context.arg0, context.arg1 as isize, context.arg2)
        }
        SyscallId::Unlink => syscall_impl::sys_unlink(context.arg0),
        SyscallId::Stat => syscall_impl::sys_stat(context.arg0, context.arg1),
        SyscallId::Getdents => syscall_impl::sys_getdents(context.arg0, context.arg1, context.arg2),
        SyscallId::Dup2 => syscall_impl::sys_dup2(context.arg0, context.arg1),
        SyscallId::Pipe => syscall_impl::sys_pipe(context.arg0),

        // Trap-frame-only process syscalls.
        //
        // `exit/fork/exec/wait` need live user registers and scheduler state.
        // Real user-mode traps go through `syscall_trap_dispatcher()` below.
        // This context-only dispatcher fails explicitly so unit tests and
        // kernel-internal direct calls do not accidentally exercise a fake
        // process path.
        SyscallId::Exit => syscall_impl::sys_exit(context.arg0 as i32),
        SyscallId::GetPid => syscall_impl::sys_getpid(),
        SyscallId::Fork => syscall_impl::sys_process_requires_trap_frame("fork"),
        SyscallId::Exec => syscall_impl::sys_process_requires_trap_frame("exec"),
        SyscallId::Wait => syscall_impl::sys_process_requires_trap_frame("wait"),
        SyscallId::Unknown => {
            serial_println!(
                "[SYSCALL] Unknown syscall: {} (syscall_id={})",
                context.syscall_id,
                context.syscall_id
            );
            errno::ENOSYS
        }
    };

    // 可视化输出:显示返回结果 (compile-time gated)
    #[cfg(feature = "verbose_syscall")]
    print_syscall_exit(syscall_id, result);

    result
}

/// Dispatch a syscall from a real user-mode trap frame.
///
/// This is the only path that implements `exit`, `fork`, `exec`, and `wait`
/// because those syscalls need access to the live saved registers (`a0`, `a7`,
/// `sepc`) and the current process/scheduler context. `interrupts.rs` should
/// delegate user ecall handling here rather than duplicating process syscall
/// routing beside the context-only dispatcher.
pub fn syscall_trap_dispatcher(tf: &mut crate::interrupts::TrapFrame) {
    let syscall_id_raw = tf.x[17]; // a7
    let sid = SyscallId::from(syscall_id_raw);

    match sid {
        SyscallId::Exit => {
            let exit_code = tf.x[10] as i32; // a0
            crate::process::exit_current_and_switch(tf, exit_code);
        }
        SyscallId::Fork => {
            let child_pid = crate::process::fork_current(tf);
            tf.x[10] = child_pid as usize;
            tf.sepc = tf.sepc.wrapping_add(4);
        }
        SyscallId::Wait => {
            let exit_code_ptr = tf.x[10]; // a0
            let child_pid = crate::process::wait_current(tf, exit_code_ptr);
            tf.x[10] = child_pid as usize;
            tf.sepc = tf.sepc.wrapping_add(4);
        }
        SyscallId::Exec => {
            let path_ptr = tf.x[10]; // a0
            let path = syscall_impl::read_c_string(path_ptr);
            let ret = match path {
                Some(ref s) => crate::process::exec_current_into_trap_frame(tf, s),
                None => -1isize,
            };
            if ret != 0 {
                tf.x[10] = ret as usize;
                tf.sepc = tf.sepc.wrapping_add(4);
            }
        }
        _ => {
            let context = SyscallContext::from_trap_frame(tf);
            let result = syscall_dispatcher(&context);
            tf.x[10] = result as usize;
            tf.sepc = tf.sepc.wrapping_add(4);
        }
    }
}

/// 打印系统调用入口信息(可视化)
#[allow(dead_code)]
fn print_syscall_entry(context: &SyscallContext, syscall_id: SyscallId) {
    serial_println!("\n╔════════════════════════════════════════╗");
    serial_println!("║     系统调用追踪                       ║");
    serial_println!("╠════════════════════════════════════════╣");
    serial_println!("║ 调用号: {:?} ({})", syscall_id, context.syscall_id);
    serial_println!("║ PC: {:#x}", context.sepc);
    serial_println!("╠════════════════════════════════════════╣");
    serial_println!("║ 参数:                                  ║");
    serial_println!("║   a0 (arg0) = {:#x}", context.arg0);
    serial_println!("║   a1 (arg1) = {:#x}", context.arg1);
    serial_println!("║   a2 (arg2) = {:#x}", context.arg2);
    serial_println!("╠════════════════════════════════════════╣");
}

/// 打印系统调用返回信息(可视化)
#[allow(dead_code)]
fn print_syscall_exit(syscall_id: SyscallId, result: isize) {
    serial_println!("║ 调用号: {:?}", syscall_id);
    serial_println!("║ 返回值: {} ({:#x})", result, result as usize);
    serial_println!("╚════════════════════════════════════════╝\n");
}

// ============================================
// 用于测试的简化版系统调用函数
// ============================================

// PTA exercise placeholder — students fill in their sys_write() implementation here
// STUDENT_CODE_HERE

/// 简化的系统调用接口(用于内核测试)
pub fn test_syscall(syscall_id: usize, arg0: usize, arg1: usize, arg2: usize) -> isize {
    let context = SyscallContext {
        syscall_id,
        arg0,
        arg1,
        arg2,
        arg3: 0,
        arg4: 0,
        arg5: 0,
        sepc: 0,
    };
    syscall_dispatcher(&context)
}