Skip to content

Commit

Permalink
fix: illegal instruction delegate context switch error
Browse files Browse the repository at this point in the history
Fix context switch error when delegate illegal instruction to S-Mode.

1. Sepc should be assigned the value of mepc,
2. Assign mstatus::MPP to sstatus::SPP to make sure kernel can know the
correct privilege level before trap.
3. mstatus::MPP update to S-Mode to make sure back to S-Mode when mret
to let kernel handle the exception.

Signed-off-by: tfx2001 <tfx2001@outlook.com>
  • Loading branch information
tfx2001 committed Jul 24, 2024
1 parent 76f380b commit bfff7a8
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/trap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,21 @@ fn boot(mut ctx: FastContext, start_addr: usize, opaque: usize) -> FastResult {
}

#[inline]
fn delegate(ctx: &mut FastContext) {
fn delegate() {
unsafe {
sepc::write(ctx.regs().pc);
sepc::write(mepc::read());
scause::write(mcause::read().bits());
stval::write(mtval::read());
sstatus::clear_sie();
if mstatus::read() & mstatus::MPP == mstatus::MPP_SUPERVISOR {
sstatus::set_spp(sstatus::SPP::Supervisor);
} else {
sstatus::set_spp(sstatus::SPP::User);
}
mstatus::update(|bits| {
*bits &= !mstatus::MPP;
*bits |= mstatus::MPP_SUPERVISOR;
});
mepc::write(stvec::read().address());
}
}
Expand Down Expand Up @@ -132,13 +141,12 @@ pub extern "C" fn fast_handler(
break ctx.restore();
}
T::Exception(E::IllegalInstruction) => {
if mstatus::read() & mstatus::MPP != mstatus::MPP_SUPERVISOR {
panic!("only can handle illegal instruction exception from S-MODE");
if mstatus::read() & mstatus::MPP == mstatus::MPP_MACHINE {
panic!("Illegal instruction exception from M-MODE");
}

ctx.regs().a = [ctx.a0(), a1, a2, a3, a4, a5, a6, a7];
if !illegal_instruction_handler(&mut ctx) {
delegate(&mut ctx);
delegate();
}
break ctx.restore();
}
Expand Down

0 comments on commit bfff7a8

Please sign in to comment.