1mod context;
16
17use crate::syscall::syscall;
18use crate::task::{exit_current_and_run_next, suspend_current_and_run_next};
19use crate::timer::set_next_trigger;
20use core::arch::global_asm;
21use riscv::interrupt::{Exception, Interrupt, Trap};
22use riscv::register::{mtvec::TrapMode, scause, sie, stval, stvec};
23
24global_asm!(include_str!("trap.S"));
25
26pub fn init() {
28 unsafe extern "C" {
29 safe fn __alltraps();
30 }
31 unsafe {
32 stvec::write(stvec::Stvec::new(
33 linker_symbol_addr!(__alltraps),
34 TrapMode::Direct,
35 ));
36 }
37}
38
39pub fn enable_timer_interrupt() {
41 unsafe {
42 sie::set_stimer();
43 }
44}
45
46#[unsafe(no_mangle)]
47pub fn trap_handler(cx: &mut TrapContext) -> &mut TrapContext {
49 let scause = scause::read(); let stval = stval::read(); let trap: Trap<Interrupt, Exception> = match scause.cause().try_into() {
52 Ok(trap) => trap,
53 Err(_) => panic!(
54 "Unsupported trap {:?}, stval = {:#x}!",
55 scause.cause(),
56 stval
57 ),
58 };
59 match trap {
60 Trap::Exception(Exception::UserEnvCall) => {
61 cx.sepc += 4;
62 cx.x[10] = syscall(cx.x[17], [cx.x[10], cx.x[11], cx.x[12]]) as usize;
63 }
64 Trap::Exception(Exception::StoreFault) | Trap::Exception(Exception::StorePageFault) => {
65 println!(
66 "[kernel] PageFault in application, bad addr = {:#x}, bad instruction = {:#x}, kernel killed it.",
67 stval, cx.sepc
68 );
69 exit_current_and_run_next();
70 }
71 Trap::Exception(Exception::IllegalInstruction) => {
72 println!("[kernel] IllegalInstruction in application, kernel killed it.");
73 exit_current_and_run_next();
74 }
75 Trap::Interrupt(Interrupt::SupervisorTimer) => {
76 set_next_trigger();
77 suspend_current_and_run_next();
78 }
79 _ => {
80 panic!("Unsupported trap {:?}, stval = {:#x}!", trap, stval);
81 }
82 }
83 cx
84}
85
86pub use context::TrapContext;