OS & Hardware
When returning from an interrupt or exception handler, why is a dedicated return instruction (such as RISC-V's sret or mret) used instead of an ordinary function return?
- AThe dedicated instruction is shorter
- BTo restore the mode and interrupt state along with the return address
- CAn ordinary return cannot find the return address from inside a handler
Show answer and explanation
Answer: B. To restore the mode and interrupt state along with the return address
When an exception or interrupt occurs, the CPU saves the return address along with the previous operating mode and interrupt-enable state in dedicated registers, then enters privileged mode. On return, all of these must be restored together, dropping back to user mode before resuming the original instruction; otherwise execution could continue with privileges. A dedicated return instruction does this atomically in one instruction. Instruction length is not the reason, and the return address is available from the saved register.
- A. Instruction length is not the reason.
- B. Correct. Mode and interrupt state must be restored at the same time.
- C. The return address is saved in a dedicated register and is known.