4

I'm writing an operating system (supervisor mode) in Rust for RISC-V in my free time. I'm trying to handle trap now.

I'm trapping correctly in direct mode, but when executing the sret instruction, I'm going directly back to my trap handler, without going back to the address stored in sepc.

Here my trap handler code (yes, I do not save any register for now):

csrr a0, sepc
csrr a1, scause
addi a0, a0, 4
csrw sepc, a0

sret

My reasoning is as follows:

  • sepc contain the address of where the trap occurred so we add it +4 to jump to the next one when we go back.
  • If I did any real work I would need to read scause so put the value in a1.
  • sret should get back to the code running before the trap.

After sret when we immediately go back to the trap handler, scause value is the same as the first time.

I'm writing to 0x0 to test my trap_handler and scause value is 7 which makes sense (see Table 4.2 - page 56).

What's going on?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Skallwar
  • 73
  • 2
  • 5
  • Which machine are you using? emulator or hardware, or maybe fpga? also which config of cpu are you using? extensions and so on. Hand-made ISA based or existed like rocket for exmaple? If you have RV64 machine, try to look mstatus bit number 22 - TSR. It should be have equal to one. If it not, then you may have problems with supervisor mode. Also TSR hardwired to zero if machine not support supervisor, page 23 of your paper. – Alexy Khilaev Oct 14 '21 at 10:58
  • Hmm...What firmware (M-Mode) software are you using? One guess is that it has set the mstatus.TSR bit and is bouncing you back into your S-Mode trap handler. I'm not sure why it would be doing that though. I assume that on every iteration of the trap loop, sepc is being incremented by 4? Are you completely sure that it is never going back to the location in sepc and somehow looping back? Without seeing your other code, I am not sure. – Echelon X-Ray Dec 14 '21 at 01:35
  • Also, I do not think that mstatus.TSR is needed for S-Mode. Per the notes in the spec, it looks like it is needed for H-Mode emulation in M-Mode firmware when hardware support is not implemented. But I doubt you are worried about that in your personal project. – Echelon X-Ray Dec 14 '21 at 01:42

0 Answers0