---
title: Interrupts and exceptions
heading: Stopping the program to deal with something else
eyebrow: C8 · Lesson 25 · Interrupts and exceptions
xp: 60
---

::: hook
A microcontroller has to notice things: a byte arriving on a serial line, a button press, a timer running out. It could check each one over and over in a loop (polling), but that wastes time and responds late. Instead, devices raise an interrupt. The processor finishes the instruction it's on, remembers where it was, and jumps to a handler; the handler deals with the event and returns, and the main program carries on as if nothing had happened. Here the main program just counts in s1, while a timer interrupts it every 40 or so instructions to count a tick in s0 and flip LED 0.

::: play
- Press Run and watch the PC jump into the handler and back. The control registers show where it came from (mepc) and why (mcause).
- Step slowly around a tick. What's in mepc while the handler runs?
- The handler saves t0 and t1 on the stack before using them. Why, when the main program never called it?
:::
:::

```sim cpu
    la t0, handler
    csrw mtvec, t0      # where interrupts go
    li t0, 0x20000
    li t1, 40
    sw t1, 12(t0)       # TIMECMP = 40: the first tick after 40 instructions
    li t1, 0x80
    csrw mie, t1        # enable the timer interrupt (bit 7 of mie)
    csrsi mstatus, 8    # turn interrupts on (bit 3 of mstatus)
main:
    addi s1, s1, 1      # the main program's own work
    li t2, 6
    blt s0, t2, main    # until 6 ticks have happened
    ebreak

handler:
    addi sp, sp, -16    # save the registers the handler uses
    sw t0, 12(sp)
    sw t1, 8(sp)
    addi s0, s0, 1      # count the tick
    li t0, 0x20000
    lw t1, 0(t0)        # flip LED 0
    xori t1, t1, 1
    sw t1, 0(t0)
    lw t1, 8(t0)        # read the timer
    addi t1, t1, 40
    sw t1, 12(t0)       # the next tick 40 instructions from now
    lw t1, 8(sp)        # restore the registers
    lw t0, 12(sp)
    addi sp, sp, 16
    mret
show: s0, s1
hex: t0
csrs: mtvec, mepc, mcause, mstatus, mie
leds: on
speed: 8
```

::: predict
## The timer interrupt arrives just before `li t2, 6` runs. After the handler's `mret`, which instruction runs next?

- [ ] The handler's first instruction, again
- [x] `li t2, 6`, the instruction that was about to run
- [ ] `blt s0, t2, main`, the one after it
- [ ] The first instruction of the program

::: reveal
`li t2, 6`. On an interrupt the processor saves the address of the instruction that hadn't run yet in mepc, and `mret` jumps back there. The main program loses no instructions and repeats none; it just runs a little later than it would have.
:::
:::

::: nameit
## Traps: interrupts and exceptions

A **trap** moves control to a handler. An **interrupt** comes from outside the instruction stream (a timer, a pin, a peripheral). An **exception** is caused by the instruction itself: an illegal instruction, a bad memory access, or `ecall`, a deliberate request for the operating system or firmware to do something.

**What the processor does** (RISC-V machine mode):

1. Finish the current instruction (for an exception, abandon the faulting one).
2. Save the PC in **mepc**: the next instruction to run for an interrupt, the faulting instruction itself for an exception.
3. Record why in **mcause**. The top bit is 1 for an interrupt; the rest is a cause number. The machine timer interrupt is 0x80000007; `ecall` from machine mode is 11; an illegal instruction is 2.
4. Turn interrupts off (bit MIE of **mstatus** is copied to MPIE, then cleared), so the handler isn't interrupted itself.
5. Jump to the handler's address, in **mtvec**.

`mret` reverses it: the PC comes back from mepc and MIE from MPIE.

**Enabling.** An interrupt is taken only when its own enable bit is set (bit 7 of **mie** for the timer) and the global enable, MIE in mstatus, is on.

**The timer.** This board's TIMER counts instructions (a real chip's counts clock ticks), and the interrupt is pending whenever TIMER ≥ TIMECMP. The handler must move TIMECMP forward, or the interrupt fires again the moment it returns.

**Handlers save everything they touch.** An ordinary function is called at a point the caller chose, and the calling convention says which registers it may change. An interrupt can arrive between any two instructions, when every register might be in use, so a handler must save and restore every register it uses.
:::


::: example
## A timer interrupt is taken just after the instruction at 0x0040 finishes. What are mepc and mcause?

::: solution
1. **mepc.** mepc = 0x0044, the next instruction to run, so nothing is skipped or repeated.
2. **mcause.** mcause = 0x80000007: the top bit marks an interrupt, and 7 is the machine timer.

**Answer:** mepc = 0x0044 and mcause = 0x80000007.
:::
:::

::: example
## An `ecall` at 0x0100 traps. What is mepc, and what must the handler do before `mret`?

::: solution
1. **mepc.** mepc = 0x0100, the `ecall` itself, because it's an exception.
2. **Before `mret`.** The handler must add 4 to mepc, or `mret` returns to the `ecall` and traps again forever.

**Answer:** mepc = 0x0100, and the handler must add 4 to it before `mret`.
:::
:::

::: example
## Entering a handler takes 3 cycles and `mret` 3 more. The handler adjusts sp twice, saves and restores 6 registers, and does 20 cycles of work. How many interrupts a second can a 16 MHz core take, and what does a 50 kHz rate cost it?

::: solution
1. **Cycles per interrupt.**
   $$\begin{aligned} n &= 3 + 1 + 6 + 20 \\ &\quad + 6 + 1 + 3 \\ &= 40\ \text{cycles} \end{aligned}$$
2. **The most interrupts a second.** At 16 MHz that's at most 400,000 interrupts a second, with nothing left for the main program.
3. **The cost at 50 kHz.**
   $$50{,}000 \times 40 = 2 \times 10^6$$
   cycles a second, 12.5% of the core.
4. **Cutting it.** Saving fewer registers (only the ones the handler touches) is the cheapest way to cut it.

**Answer:** at most 400,000 interrupts a second, and a 50 kHz rate costs 12.5% of the core.
:::
:::

::: check
kind: order

## Put the steps of taking a timer interrupt in order.

1. Finish the instruction that's running
2. Save the address of the next instruction in mepc
3. Record the cause in mcause
4. Turn interrupts off
5. Jump to the handler at mtvec
6. Run the handler, then `mret`

::: right
Right. Saving the PC first means the program can resume exactly where it stopped.
:::
:::

::: check
given: p = 100..900 int; let a = 4*p
answer: a + 4
base: 16
width: 4

## An `ecall` at address 0x{a:hex4} traps to a handler. Before its `mret`, what should the handler put in mepc so the program continues after the `ecall`?

::: right
Right: 0x{answer}. For an exception, mepc points at the instruction that caused it, so the handler steps past it.
:::

::: misses
- [a] That's the `ecall` itself. Returning there runs it again, trapping forever.
- [a + 1] Instructions are 4 bytes.
- [any] Not yet. The next instruction is 4 bytes on.
:::
:::

::: check
kind: asm
given: n = -500..500 int
expect: a0 = n + 101

## Finish the handler so it adds 100 to a0 and returns to the instruction after the `ecall`.

```asm starter
    la t0, handler
    csrw mtvec, t0
    li a0, n
    ecall
    addi a0, a0, 1      # runs after the handler returns
    ebreak
handler:
    # add 100 to a0, then return past the ecall
    mret
```

```asm solution
    la t0, handler
    csrw mtvec, t0
    li a0, n
    ecall
    addi a0, a0, 1
    ebreak
handler:
    addi a0, a0, 100
    csrr t1, mepc
    addi t1, t1, 4      # step past the ecall
    csrw mepc, t1
    mret
```

::: right
Right. The starter's `mret` went back to the `ecall` itself, so it trapped again and again. Moving mepc on by 4 fixes it.
:::
:::

::: check
given: f = 1 | 8 | 16 | 48; T = 1 | 5 | 10
answer: 1000*f*T
tolerance: 0

## A timer counts at {f} MHz. For an interrupt every {T} ms, how much should the handler add to TIMECMP each time?

::: right
Right: {answer} counts. {f} million counts a second, for {T} thousandths of a second.
:::

::: misses
- [f*T] MHz times ms: {f} × 10⁶ × {T} × 10⁻³.
- [1000000*f*T] {T} ms is {T} thousandths of a second.
- [any] Not yet. Counts = rate × time.
:::
:::

::: check
given: h = 10..30 int; N = 100 | 200 | 1000
answer: 100*h/N
unit: %
tolerance: 0.5%

## A timer interrupt fires every {N} instructions, and its handler runs {h} of them. What percentage of the processor's time goes to the handler?

::: right
Right: {answer}. Short handlers keep that overhead small, which is why they usually just record the event and leave the rest of the work to the main program.
:::

::: misses
- [100*h/(N - h)] Measure against all {N} instructions, handler included.
- [any] Not yet. {h} out of every {N} instructions.
:::
:::

::: check
kind: choice

## Why must an interrupt handler save every register it uses, when an ordinary function only has to save the s registers and ra?

- [ ] Handlers run faster that way
- [x] The interrupted code didn't call the handler, so it expects every register to be unchanged
- [ ] The processor saves the t registers automatically
- [ ] The calling convention doesn't allow handlers to use t registers

::: right
Right. A call happens where the caller decided and the convention lets it expect t and a registers to change. An interrupt can land between any two instructions.
:::

::: misses
- [1] Saving costs time; it's needed for correctness.
- [3] RISC-V saves only the PC (in mepc) and the interrupt enable.
- [4] It may use them, as long as it puts them back.
:::
:::

::: check
kind: parts
given: e = 3 | 5; s = 4 | 6 | 10; w = 20 | 50; f = 16 | 48; r = 10 | 50

## Entry takes {e} cycles and `mret` 3. A handler adjusts sp twice, saves and restores {s} registers and does {w} cycles of work, at {f} MHz.

::: part
answer: e + 2 + 2*s + w + 3
tolerance: 0

### How many cycles does each interrupt cost?

::: misses
- [e + s + w + 3] Each register is saved and restored: two instructions.
- [any] Entry, sp twice, saves, work, restores, mret.
:::
:::

::: part
answer: r*1000*(e + 2 + 2*s + w + 3)/(f*1e6)*100
unit: %
tolerance: 0.5%

### What share of the core does a {r} kHz interrupt rate use?

::: misses
- [any] Rate × cycles ÷ clock.
:::
:::
:::

::: check
kind: parts
given: c = 3 | 7 | 11

## The cause code is {c}.

::: part
answer: 2^31 + c
tolerance: 0
base: 16
width: 8

### What's mcause for a machine-mode interrupt with that code?

::: misses
- [c] Interrupts set the top bit.
- [any] $2^{31} + c$.
:::
:::

::: part
answer: c
tolerance: 0

### And for an exception with the same code?

::: misses
- [any] Exceptions leave the top bit clear.
:::
:::
:::

::: explain
## Why is responding to a button with an interrupt better than checking the button in a polling loop?

::: model
A polling loop has to check the button over and over, using processor time even when nothing happens, and it only notices a press when it next gets round to checking, so the response is late by up to one trip round the loop (and a short press between checks can be missed entirely). With an interrupt the hardware watches the pin, and the processor is told within a few instructions of the press. Between events the processor can do other work, or sleep and save power, which matters on battery-powered devices.
:::
:::

::: practice

::: check
given: p = 50..900 int; let a = 4*p
answer: a + 4
base: 16
width: 4

## `ecall` at 0x{a:hex4}. mepc for the handler to return past it?

::: misses
- [a] That re-runs the `ecall`.
- [any] Add 4.
:::
:::

::: check
given: f = 2 | 12 | 32; T = 2 | 20 | 100
answer: 1000*f*T
tolerance: 0

## {f} MHz timer, a tick every {T} ms. TIMECMP step?

::: misses
- [f*T] Times 1000: MHz × ms.
- [any] Rate × time.
:::
:::

::: check
given: h = 12..40 int; N = 400 | 500 | 2000
answer: 100*h/N
unit: %
tolerance: 0.5%

## A {h}-instruction handler every {N} instructions. Share of time?

::: misses
- [any] {h} / {N}.
:::
:::
:::
