Skip to main content

os/syscall/
mod.rs

1/*
2 * ============================================
3 * 系统调用模块
4 * ============================================
5 * 功能:提供用户态程序与内核交互的接口
6 *
7 * 系统调用机制:
8 * - 用户态通过 ecall 指令触发系统调用
9 * - 系统调用号通过 a7 寄存器传递
10 * - 参数通过 a0-a5 寄存器传递(最多6个参数)
11 * - 返回值通过 a0 寄存器返回
12 *
13 * 支持的系统调用:
14 * - sys_write: 写入数据到文件描述符
15 * - sys_exit: 退出进程
16 * - sys_getpid: 获取当前进程ID
17 * ============================================
18 */
19
20pub mod syscall_impl;
21pub mod user_ptr;
22
23use crate::{errno, serial_println};
24
25/// 系统调用号定义
26/// 兼容Linux RISC-V系统调用号
27#[repr(usize)]
28#[derive(Debug, Copy, Clone, PartialEq, Eq)]
29pub enum SyscallId {
30    // 文件系统系统调用(第7章)(任务点12-1,已提供)
31    Mkdir = 34,  // sys_mkdir - 创建目录
32    Mount = 40,  // sys_mount - 挂载文件系统
33    Umount = 39, // sys_umount - 卸载文件系统
34    Open = 56,   // sys_open - 打开/创建文件
35    Close = 57,  // sys_close - 关闭文件描述符
36    Read = 63,   // sys_read - 从文件读取
37    Write = 64,  // sys_write - 写入文件
38
39    // Extended system calls (G5)
40    Unlink = 35,   // sys_unlink - 删除文件
41    Lseek = 62,    // sys_lseek - 文件定位
42    Getdents = 78, // sys_getdents - 读取目录项
43    Stat = 1038,   // sys_stat - 获取文件状态
44    Dup2 = 1041,   // sys_dup2 - 复制文件描述符
45    Pipe = 59,     // sys_pipe - 创建管道
46
47    // 进程系统调用(第6章)
48    Exit = 93,    // sys_exit - 退出进程
49    GetPid = 172, // sys_getpid - 获取进程ID
50    Fork = 220,   // sys_fork - 复制进程
51    Exec = 221,   // sys_exec - 替换进程映像
52    Wait = 260,   // sys_wait - 等待子进程
53    Unknown = 9999,
54}
55
56impl From<usize> for SyscallId {
57    fn from(id: usize) -> Self {
58        match id {
59            // 文件系统系统调用
60            34 => SyscallId::Mkdir,
61            39 => SyscallId::Umount,
62            40 => SyscallId::Mount,
63            56 => SyscallId::Open,
64            57 => SyscallId::Close,
65            63 => SyscallId::Read,
66            64 => SyscallId::Write,
67
68            // Extended system calls (G5)
69            35 => SyscallId::Unlink,
70            62 => SyscallId::Lseek,
71            78 => SyscallId::Getdents,
72            1038 => SyscallId::Stat,
73            1041 => SyscallId::Dup2,
74            59 => SyscallId::Pipe,
75
76            // 进程系统调用
77            93 => SyscallId::Exit,
78            172 => SyscallId::GetPid,
79            220 => SyscallId::Fork,
80            221 => SyscallId::Exec,
81            260 => SyscallId::Wait,
82            _ => SyscallId::Unknown,
83        }
84    }
85}
86
87impl SyscallId {
88    /// Returns true for process-control syscalls that must be dispatched from
89    /// the live user trap frame instead of the context-only dispatcher.
90    ///
91    /// These calls mutate the current process, scheduler state, or saved user
92    /// registers. `syscall_dispatcher()` only receives a copied
93    /// [`SyscallContext`], so it intentionally returns `ENOSYS` for this set.
94    /// Real user-mode traps enter through [`syscall_trap_dispatcher()`].
95    pub const fn requires_live_trap_frame(self) -> bool {
96        match self {
97            SyscallId::Exit | SyscallId::Fork | SyscallId::Exec | SyscallId::Wait => true,
98            SyscallId::Mkdir
99            | SyscallId::Mount
100            | SyscallId::Umount
101            | SyscallId::Open
102            | SyscallId::Close
103            | SyscallId::Read
104            | SyscallId::Write
105            | SyscallId::Unlink
106            | SyscallId::Lseek
107            | SyscallId::Getdents
108            | SyscallId::Stat
109            | SyscallId::Dup2
110            | SyscallId::Pipe
111            | SyscallId::GetPid
112            | SyscallId::Unknown => false,
113        }
114    }
115
116    pub const fn process_name(self) -> Option<&'static str> {
117        match self {
118            SyscallId::Exit => Some("exit"),
119            SyscallId::Fork => Some("fork"),
120            SyscallId::Exec => Some("exec"),
121            SyscallId::Wait => Some("wait"),
122            _ => None,
123        }
124    }
125}
126
127/// 系统调用上下文
128///
129/// 保存系统调用时的寄存器状态
130#[derive(Debug, Clone, Copy)]
131pub struct SyscallContext {
132    /// 系统调用号 (a7)
133    pub syscall_id: usize,
134    /// 参数0 (a0)
135    pub arg0: usize,
136    /// 参数1 (a1)
137    pub arg1: usize,
138    /// 参数2 (a2)
139    pub arg2: usize,
140    /// 参数3 (a3)
141    pub arg3: usize,
142    /// 参数4 (a4)
143    pub arg4: usize,
144    /// 参数5 (a5)
145    pub arg5: usize,
146    /// 系统调用发生时的 PC
147    pub sepc: usize,
148}
149
150impl SyscallContext {
151    /// Build from trap frame (used when trap comes from real user mode).
152    pub fn from_trap_frame(tf: &crate::interrupts::TrapFrame) -> Self {
153        Self {
154            syscall_id: tf.x[17], // a7
155            arg0: tf.x[10],       // a0
156            arg1: tf.x[11],       // a1
157            arg2: tf.x[12],       // a2
158            arg3: tf.x[13],       // a3
159            arg4: tf.x[14],       // a4
160            arg5: tf.x[15],       // a5
161            sepc: tf.sepc,
162        }
163    }
164
165    /// 从寄存器创建系统调用上下文(仅用于内核态直接调用测试)
166    ///
167    /// # Safety
168    ///
169    /// The current CPU registers must contain a valid syscall ABI snapshot.
170    /// This helper is intended only for controlled kernel self-tests.
171    pub unsafe fn from_registers() -> Self {
172        let syscall_id: usize;
173        let arg0: usize;
174        let arg1: usize;
175        let arg2: usize;
176        let arg3: usize;
177        let arg4: usize;
178        let arg5: usize;
179
180        core::arch::asm!(
181            "mv {0}, a7",  // 读取系统调用号
182            "mv {1}, a0",  // 读取参数
183            "mv {2}, a1",
184            "mv {3}, a2",
185            "mv {4}, a3",
186            "mv {5}, a4",
187            "mv {6}, a5",
188            out(reg) syscall_id,
189            out(reg) arg0,
190            out(reg) arg1,
191            out(reg) arg2,
192            out(reg) arg3,
193            out(reg) arg4,
194            out(reg) arg5,
195        );
196
197        let sepc = riscv::register::sepc::read();
198
199        Self {
200            syscall_id,
201            arg0,
202            arg1,
203            arg2,
204            arg3,
205            arg4,
206            arg5,
207            sepc,
208        }
209    }
210
211    /// 设置返回值
212    ///
213    /// # Safety
214    /// 必须在系统调用处理完成后调用
215    pub unsafe fn set_return_value(&self, ret: isize) {
216        core::arch::asm!(
217            "mv a0, {0}",
218            in(reg) ret,
219        );
220    }
221}
222
223/// 系统调用分发器
224///
225/// # 参数
226/// - `context`: 系统调用上下文
227///
228/// # 返回
229/// 系统调用返回值(通过 a0 寄存器)
230pub fn syscall_dispatcher(context: &SyscallContext) -> isize {
231    let syscall_id = SyscallId::from(context.syscall_id);
232
233    // 可视化输出:显示系统调用信息 (compile-time gated)
234    #[cfg(feature = "verbose_syscall")]
235    print_syscall_entry(context, syscall_id);
236
237    let result = match syscall_id {
238        // 文件系统系统调用
239        SyscallId::Read => syscall_impl::sys_read(context.arg0, context.arg1, context.arg2),
240        SyscallId::Write => {
241            syscall_impl::sys_write(context.arg0, context.arg1 as *const u8, context.arg2)
242        }
243        SyscallId::Open => syscall_impl::sys_open(context.arg0, context.arg1),
244        SyscallId::Close => syscall_impl::sys_close(context.arg0),
245        SyscallId::Mkdir => syscall_impl::sys_mkdir(context.arg0),
246        SyscallId::Mount => syscall_impl::sys_mount(context.arg0),
247        SyscallId::Umount => syscall_impl::sys_umount(context.arg0),
248
249        // Extended system calls (G5)
250        SyscallId::Lseek => {
251            syscall_impl::sys_lseek(context.arg0, context.arg1 as isize, context.arg2)
252        }
253        SyscallId::Unlink => syscall_impl::sys_unlink(context.arg0),
254        SyscallId::Stat => syscall_impl::sys_stat(context.arg0, context.arg1),
255        SyscallId::Getdents => syscall_impl::sys_getdents(context.arg0, context.arg1, context.arg2),
256        SyscallId::Dup2 => syscall_impl::sys_dup2(context.arg0, context.arg1),
257        SyscallId::Pipe => syscall_impl::sys_pipe(context.arg0),
258
259        // Trap-frame-only process syscalls.
260        //
261        // `exit/fork/exec/wait` need live user registers and scheduler state.
262        // Real user-mode traps go through `syscall_trap_dispatcher()` below.
263        // This context-only dispatcher fails explicitly so unit tests and
264        // kernel-internal direct calls do not accidentally exercise a fake
265        // process path.
266        SyscallId::Exit => syscall_impl::sys_exit(context.arg0 as i32),
267        SyscallId::GetPid => syscall_impl::sys_getpid(),
268        SyscallId::Fork => syscall_impl::sys_process_requires_trap_frame("fork"),
269        SyscallId::Exec => syscall_impl::sys_process_requires_trap_frame("exec"),
270        SyscallId::Wait => syscall_impl::sys_process_requires_trap_frame("wait"),
271        SyscallId::Unknown => {
272            serial_println!(
273                "[SYSCALL] Unknown syscall: {} (syscall_id={})",
274                context.syscall_id,
275                context.syscall_id
276            );
277            errno::ENOSYS
278        }
279    };
280
281    // 可视化输出:显示返回结果 (compile-time gated)
282    #[cfg(feature = "verbose_syscall")]
283    print_syscall_exit(syscall_id, result);
284
285    result
286}
287
288/// Dispatch a syscall from a real user-mode trap frame.
289///
290/// This is the only path that implements `exit`, `fork`, `exec`, and `wait`
291/// because those syscalls need access to the live saved registers (`a0`, `a7`,
292/// `sepc`) and the current process/scheduler context. `interrupts.rs` should
293/// delegate user ecall handling here rather than duplicating process syscall
294/// routing beside the context-only dispatcher.
295pub fn syscall_trap_dispatcher(tf: &mut crate::interrupts::TrapFrame) {
296    let syscall_id_raw = tf.x[17]; // a7
297    let sid = SyscallId::from(syscall_id_raw);
298
299    match sid {
300        SyscallId::Exit => {
301            let exit_code = tf.x[10] as i32; // a0
302            crate::process::exit_current_and_switch(tf, exit_code);
303        }
304        SyscallId::Fork => {
305            let child_pid = crate::process::fork_current(tf);
306            tf.x[10] = child_pid as usize;
307            tf.sepc = tf.sepc.wrapping_add(4);
308        }
309        SyscallId::Wait => {
310            let exit_code_ptr = tf.x[10]; // a0
311            let child_pid = crate::process::wait_current(tf, exit_code_ptr);
312            tf.x[10] = child_pid as usize;
313            tf.sepc = tf.sepc.wrapping_add(4);
314        }
315        SyscallId::Exec => {
316            let path_ptr = tf.x[10]; // a0
317            let path = syscall_impl::read_c_string(path_ptr);
318            let ret = match path {
319                Some(ref s) => crate::process::exec_current_into_trap_frame(tf, s),
320                None => -1isize,
321            };
322            if ret != 0 {
323                tf.x[10] = ret as usize;
324                tf.sepc = tf.sepc.wrapping_add(4);
325            }
326        }
327        _ => {
328            let context = SyscallContext::from_trap_frame(tf);
329            let result = syscall_dispatcher(&context);
330            tf.x[10] = result as usize;
331            tf.sepc = tf.sepc.wrapping_add(4);
332        }
333    }
334}
335
336/// 打印系统调用入口信息(可视化)
337#[allow(dead_code)]
338fn print_syscall_entry(context: &SyscallContext, syscall_id: SyscallId) {
339    serial_println!("\n╔════════════════════════════════════════╗");
340    serial_println!("║     系统调用追踪                       ║");
341    serial_println!("╠════════════════════════════════════════╣");
342    serial_println!("║ 调用号: {:?} ({})", syscall_id, context.syscall_id);
343    serial_println!("║ PC: {:#x}", context.sepc);
344    serial_println!("╠════════════════════════════════════════╣");
345    serial_println!("║ 参数:                                  ║");
346    serial_println!("║   a0 (arg0) = {:#x}", context.arg0);
347    serial_println!("║   a1 (arg1) = {:#x}", context.arg1);
348    serial_println!("║   a2 (arg2) = {:#x}", context.arg2);
349    serial_println!("╠════════════════════════════════════════╣");
350}
351
352/// 打印系统调用返回信息(可视化)
353#[allow(dead_code)]
354fn print_syscall_exit(syscall_id: SyscallId, result: isize) {
355    serial_println!("║ 调用号: {:?}", syscall_id);
356    serial_println!("║ 返回值: {} ({:#x})", result, result as usize);
357    serial_println!("╚════════════════════════════════════════╝\n");
358}
359
360// ============================================
361// 用于测试的简化版系统调用函数
362// ============================================
363
364// PTA exercise placeholder — students fill in their sys_write() implementation here
365// STUDENT_CODE_HERE
366
367/// 简化的系统调用接口(用于内核测试)
368pub fn test_syscall(syscall_id: usize, arg0: usize, arg1: usize, arg2: usize) -> isize {
369    let context = SyscallContext {
370        syscall_id,
371        arg0,
372        arg1,
373        arg2,
374        arg3: 0,
375        arg4: 0,
376        arg5: 0,
377        sepc: 0,
378    };
379    syscall_dispatcher(&context)
380}