ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Architecture / ISA > RISC-V 제어 상태 레지스터(CSR)와 하드웨어 트랩/인터럽트 처리 구조RISC-V Control and Status Registers (CSR) and Hardware Trap/Interrupt Handling
Architecture / ISA Advanced RISC-V Privileged ISA / QEMU

RISC-V 제어 상태 레지스터(CSR)와 하드웨어 트랩/인터럽트 처리 구조RISC-V Control and Status Registers (CSR) and Hardware Trap/Interrupt Handling

특권 모드(Machine Mode)에서 mtvec, mepc, mcause, mstatus 제어 상태 레지스터(CSR)를 제어하고 예외 및 인터럽트를 처리하는 아키텍처 원리입니다.Architectural principles for managing Machine-Mode Control and Status Registers (mtvec, mepc, mcause, mstatus) and handling synchronous exceptions and hardware interrupts in RISC-V.

#RISC-V #CSR #Interrupt #OS #Embedded
핵심 개념RISC-V 프로세서의 상태 제어 및 하드웨어 인터럽트 처리는 CSR(Control and Status Register) 전용 원자적 명령어(csrr, csrw, csrrw, csrrs, csrrc)를 통해 이루어집니다. 타이머나 외부 인터럽트가 발생하면 하드웨어가 현재 PC를 mepc에 기록하고 원인을 mcause에 저장한 뒤 트랩 벡터(mtvec) 주소로 점프합니다.
Key ConceptProcessor state management and hardware interrupt handling in RISC-V rely on dedicated atomic CSR (Control and Status Register) instructions (csrr, csrw, csrrw, csrrs, csrrc). When a timer or external interrupt fires, hardware latches the current PC into mepc, records the cause code in mcause, and jumps to the trap vector base address (mtvec).

1. 핵심 Machine-Mode CSR 일람1. Core Machine-Mode CSR Reference

좌우로 밀어서 표 전체 내용을 확인하세요
CSR 이름주소역할
mstatus0x300글로벌 인터럽트 활성화(MIE) 및 이전 특권 모드 상태 보존
mtvec0x305트랩 핸들러의 기본 시작 주소 및 모드(Direct / Vectored) 설정
mepc0x341트랩이 발생한 시점의 명령어 주소(복귀 대상 PC)
mcause0x342트랩 발생 원인 (최상위 인터럽트 비트 + 하위 예외 코드)
mtval0x343잘못된 메모리 접근 주소(Bad Address) 또는 폴트 명령어 비트값
Swipe horizontally to view the full table
CSR NameAddressRole
mstatus0x300Controls global interrupt enable (MIE) and preserves previous privilege mode state
mtvec0x305Holds trap handler base address and mode bits (Direct / Vectored)
mepc0x341Stores the instruction PC at which the trap occurred (return target)
mcause0x342Encodes trap reason (MSB interrupt flag + exception code)
mtval0x343Provides faulting virtual address or offending instruction bits

2. 인터럽트 핸들러 어셈블리 템플릿2. Interrupt Handler Assembly Template

trap_handler.s
.globl trap_handler
.align 4
trap_handler:
    # 1. 컨텍스트 백업 (스택에 작업 레지스터 저장)
    addi sp, sp, -32
    sw   t0, 0(sp)
    sw   t1, 4(sp)

    # 2. 트랩 원인 판별
    csrr t0, mcause           # 트랩 원인 코드 읽기
    bgez t0, handle_exception # 최상위 비트가 0이면 동기식 예외, 1이면 비동기 인터럽트

    # 3. 비동기 인터럽트 처리 수행 (예: 타이머 비교 레지스터 갱신)
    j    trap_exit

handle_exception:
    # 동기식 예외(ecall 등)인 경우 복귀 주소(mepc)를 다음 명령어(+4)로 전진
    csrr t1, mepc
    addi t1, t1, 4
    csrw mepc, t1

trap_exit:
    # 4. 컨텍스트 복원 및 복귀
    lw   t0, 0(sp)
    lw   t1, 4(sp)
    addi sp, sp, 32
    mret                      # mepc 주소로 복귀하며 mstatus.MIE 복원
trap_handler.s
.globl trap_handler
.align 4
trap_handler:
    # 1. Back up context (save working registers onto stack)
    addi sp, sp, -32
    sw   t0, 0(sp)
    sw   t1, 4(sp)

    # 2. Identify trap cause
    csrr t0, mcause           # Read trap cause register
    bgez t0, handle_exception # MSB == 0 indicates synchronous exception; MSB == 1 indicates interrupt

    # 3. Handle asynchronous interrupt (e.g., update timer compare register)
    j    trap_exit

handle_exception:
    # For synchronous exceptions (e.g., ecall), advance mepc to the next instruction (+4)
    csrr t1, mepc
    addi t1, t1, 4
    csrw mepc, t1

trap_exit:
    # 4. Restore context and return from trap
    lw   t0, 0(sp)
    lw   t1, 4(sp)
    addi sp, sp, 32
    mret                      # Return to mepc and restore mstatus.MIE

3. 실무 적용 및 주의사항3. Practical Considerations and Caveats

  • mtvec 주소의 4바이트 정렬 필수: mtvec 레지스터의 하위 2비트(MODE)는 Direct 모드(00)와 Vectored 모드(01)를 구분하는 데 사용되므로, 트랩 핸들러 함수 시작 주소는 반드시 .align 2(4바이트 경계) 이상으로 정렬되어야 합니다.
  • 동기 예외와 비동기 인터럽트의 mepc 처리 차이: 타이머 같은 비동기 인터럽트는 중단된 명령어를 다시 실행해야 하므로 mepc를 그대로 두고 mret를 호출하지만, ecall이나 브레이크포인트 같은 동기식 예외는 무한 루프를 막기 위해 소프트웨어에서 mepc에 4(압축 명령어인 경우 2)를 더해주어야 합니다.
  • 인터럽트 내 C 함수 호출 시 레지스터 백업: 어셈블리 트랩 핸들러 안에서 C 언어로 작성된 ISR 함수를 호출(jal)한다면, ABI 규칙상 모든 Caller-Saved 레지스터(ra, t0~t6, a0~a7)를 스택에 모두 저장하고 복원해야 기존 태스크 문맥이 깨지지 않습니다.
  • 4-Byte Alignment Requirement for mtvec: Because the lowest 2 bits of mtvec encode the vector mode (00 for Direct, 01 for Vectored), the trap handler entry point must be aligned to at least a 4-byte boundary (.align 2).
  • Advancing mepc on Synchronous Exceptions: Asynchronous interrupts return directly to mepc to re-execute the interrupted instruction, whereas synchronous exceptions like ecall require software to increment mepc by 4 (or 2 for compressed RVC instructions) before executing mret to avoid an infinite trap loop.
  • Saving Caller-Saved Registers Before Calling C ISRs: If the assembly trap entry calls (jal) a C handler function, it must save and restore all Caller-Saved registers (ra, t0–t6, a0–a7) on the stack so the interrupted task's context is preserved.

RISC-V의 CSR 기반 트랩 구조는 인터럽트 진입과 복귀 시 하드웨어 개입을 최소화하므로, 핸들러 초입의 컨텍스트 백업과 mepc 보정 규칙을 정확히 구현하는 것이 중요합니다.

RISC-V's CSR trap architecture keeps hardware entry overhead minimal, placing the responsibility for context saving and mepc adjustment on the software trap handler.