Skip to main content

os/trap/
mod.rs

1//! Trap handling functionality
2//!
3//! For rCore, we have a single trap entry point, namely `__alltraps`. At
4//! initialization in [`init()`], we set the `stvec` CSR to point to it.
5//!
6//! All traps go through `__alltraps`, which is defined in `trap.S`. The
7//! assembly language code does just enough work restore the kernel space
8//! context, ensuring that Rust code safely runs, and transfers control to
9//! [`trap_handler()`].
10//!
11//! It then calls different functionality based on what exactly the exception
12//! was. For example, timer interrupts trigger task preemption, and syscalls go
13//! to [`syscall()`].
14
15mod context;
16
17use crate::batch::run_next_app;
18use crate::syscall::syscall;
19use core::arch::global_asm;
20use riscv::interrupt::{Exception, Interrupt, Trap};
21use riscv::register::{mtvec::TrapMode, scause, stval, stvec};
22
23global_asm!(include_str!("trap.S"));
24
25/// initialize CSR `stvec` as the entry of `__alltraps`
26pub fn init() {
27    unsafe extern "C" {
28        safe fn __alltraps();
29    }
30    unsafe {
31        stvec::write(stvec::Stvec::new(
32            linker_symbol_addr!(__alltraps),
33            TrapMode::Direct,
34        ));
35    }
36}
37
38#[unsafe(no_mangle)]
39/// handle an interrupt, exception, or system call from user space
40pub fn trap_handler(cx: &mut TrapContext) -> &mut TrapContext {
41    let scause = scause::read(); // get trap cause
42    let stval = stval::read(); // get extra value
43    let trap: Trap<Interrupt, Exception> = match scause.cause().try_into() {
44        Ok(trap) => trap,
45        Err(_) => panic!(
46            "Unsupported trap {:?}, stval = {:#x}!",
47            scause.cause(),
48            stval
49        ),
50    };
51    match trap {
52        Trap::Exception(Exception::UserEnvCall) => {
53            cx.sepc += 4;
54            cx.x[10] = syscall(cx.x[17], [cx.x[10], cx.x[11], cx.x[12]]) as usize;
55        }
56        Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StorePageFault) => {
57            println!("[kernel] PageFault in application, kernel killed it.");
58            run_next_app();
59        }
60        Trap::Exception(Exception::IllegalInstruction) => {
61            println!("[kernel] IllegalInstruction in application, kernel killed it.");
62            run_next_app();
63        }
64        _ => {
65            panic!("Unsupported trap {:?}, stval = {:#x}!", trap, stval);
66        }
67    }
68    cx
69}
70
71pub use context::TrapContext;