53 lines
1.8 KiB
Markdown
53 lines
1.8 KiB
Markdown
# Phase 9 - CSRs + M-Mode Trap Handling
|
|
|
|
## Context
|
|
|
|
This phase adds architectural control registers and the mechanism for exceptions and
|
|
interrupts. The CPU stops merely halting on faults and starts transferring control to
|
|
software handlers.
|
|
|
|
## Goals
|
|
|
|
- Implement key machine-mode CSRs.
|
|
- Implement CSR instructions and `mret`.
|
|
- Add trap entry for illegal instructions, breakpoints, ecalls, and access faults.
|
|
|
|
## New Concepts
|
|
|
|
- CSR: control and status register, special architectural register accessed by CSR instructions.
|
|
- Trap: synchronous exception or asynchronous interrupt that redirects execution.
|
|
- `mepc`: CSR holding PC to return to after a trap.
|
|
- `mcause`: CSR describing why the trap occurred.
|
|
- `mtvec`: CSR holding trap handler address.
|
|
- `mret`: instruction returning from machine-mode trap.
|
|
|
|
## How To Think About It
|
|
|
|
Traps are controlled context switches within the CPU. Hardware records enough state for
|
|
software to inspect the cause, handle it, and resume or terminate.
|
|
|
|
## Learning Tasks
|
|
|
|
- Draw the exact state updates on trap entry.
|
|
- Write a table of each exception source and its `mcause`, then compare it with
|
|
the trap-cause decisions in the roadmap.
|
|
- Understand which PC is saved for each exception type.
|
|
|
|
## Pitfalls
|
|
|
|
- Saving the wrong PC in `mepc`.
|
|
- Updating architectural state for a faulting instruction that should not retire.
|
|
- Treating all exceptions as illegal instructions.
|
|
|
|
## Tooling And Testing
|
|
|
|
- Create tiny programs that intentionally trigger one exception at a time.
|
|
- Inspect CSR values after trap entry in simulation.
|
|
- Test `mret` returning to a known instruction address.
|
|
|
|
## References
|
|
|
|
- RISC-V privileged architecture spec: https://riscv.org/technical/specifications/
|
|
- RISC-V CSR instruction semantics: https://riscv.org/technical/specifications/
|
|
- RISC-V educational trap handling notes: https://osblog.stephenmarz.com/
|