Files
FPGA-Core/Tutorial/phase-09-csrs-traps/phase-09.md
T
imple b008b37d49 Add phase-by-phase tutorial notes
Add a Tutorial tree that mirrors the roadmap from Phase 0 through Linux bring-up.
Each phase and subphase gets a short learning note with consistent sections for
context, goals, new concepts, mental model, learning tasks, pitfalls, tooling,
testing, and references.

The tutorial material is intentionally explanatory rather than implementation
code. It gives a systems-oriented learner enough FPGA, SystemVerilog, RISC-V,
firmware, and Linux bring-up context to approach each roadmap phase without
turning the notes into copy-paste RTL.
2026-04-28 12:11:23 +02:00

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`.
- 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/