Interrupt Handlers in C
A chip test that never takes an interrupt never tests the interrupt path. Follow one GPIO edge through ap_plic, the entry stub, the dispatcher and a handler in C, cycle by cycle. Then learn the rules for data the handler shares with main.
You Will Be Able To
- Trace one interrupt from the device to mret: request, pending, trap, stub, claim, handler, complete.
- Explain why the entry stub saves exactly the caller-saved registers.
- Write a handler that clears its device's condition and shares data with main safely.
- Recognise a wait loop that the compiler has turned into a loop with no load.
- Lesson
- V0.5
- Time
- 28 min
- Runs on
- Your browser
- Check
- 5 questions
Your test waits for a button press through an interrupt. The bench pulses the pin, the handler runs, and the test still hangs until its cycle limit. Nothing is wrong with the chip. The handler and main never agreed on how to share one variable.
- Peripheral
- Processor
- Interrupt
- Data
- Cycle 276: the request
The board pulsed pad IO8. GPIO saw the rising edge and raised its request, and ap_plic marked source 2 pending.
- Cycle 282: the trap
ap_plic raised the core's external interrupt. The core stopped main between two instructions and jumped to mtvec.
- The entry stub
The stub knows nothing about C. It moves sp down 64 bytes and saves the 16 registers that a C call may change.
- Cycle 373: the claim
The dispatcher reads CLAIM. ap_plic answers 2, the pending source with the highest priority, and clears its pending bit.
- Cycle 394: your handler
The dispatcher calls the function in slot 2 of its table. The handler clears GPIO's edge flag, then counts.
- Cycles 405 to 460: complete and return
The dispatcher writes 2 back to CLAIM, the stub restores the registers, and mret resumes main where it stopped.
Read the diagram as text
- GPIO: pin 8 rising edge: request
- ap_plic: source 2: pending, claim, complete
- Core: takes the trap, jumps to mtvec
- Entry stub: trap.S: saves 16 registers
- Dispatcher: irq.c: claim, call, complete
- Your handler: on_edge(): clear, count
- GPIO → ap_plic: request
- ap_plic → Core: external interrupt
- Core → Entry stub: pc = mtvec
- Entry stub → Dispatcher: call
- Dispatcher → ap_plic: claim, complete
- Dispatcher → Your handler: table[2]()
One interrupt of the lab, on ap_soc v1.5. Cycles of clk_sys from the end of reset.
Before You Start
Read Before main and A Register Is an Address first. The interrupt path of the chip is drawn in The Interrupt Path.
| Question | |
|---|---|
| 1 | Why must a chip test take real interrupts? |
| 2 | What does the entry stub do before any C runs? |
| 3 | What do claim and complete tell ap_plic? |
| 4 | What must a handler do before it returns? |
| 5 | How do main and a handler share a variable safely? |
The Idea: The Device Decides When
A test can learn about an event in two ways. It can poll: read the status register again and again. Or it can let the device interrupt it. Polling is simpler, and for a block bench it is enough.
At chip level, polling skips the very thing under test. An interrupt crosses four boundaries: the device's request wire, the controller ap_plic, the core's trap logic, and the software that answers. A wire on the wrong input, a missing enable or a handler that never completes are all chip bugs. Only a test that takes the interrupt can find them.
The difficulty is that an interrupt can arrive between any two instructions of main. The handler borrows the core, runs, and gives it back. So two rules follow. Main must find every register as it left it, and the data the two share must survive being interrupted halfway.
New Words
| Word | Meaning |
|---|---|
| Interrupt handler | The C function that answers one source: here on_edge() for GPIO. |
| Entry stub | The assembly at mtvec (the kit's trap.S) that saves registers, calls C, restores them and runs mret. |
| Caller-saved register | A register a C function may change without restoring it: ra, t0 to t6 and a0 to a7 on RISC-V. |
| Dispatch table | An array of handler pointers, one per source number; irq_enable() fills a slot. |
| Claim and complete | Reading ap_plic CLAIM gives the source to serve; writing it back says the service is done. |
| Shared variable | A variable that main and a handler both use. |
| Critical section | A few instructions run with interrupts masked, so no handler can run in between. |
The Smallest Example: The Stub's 64 Bytes
Why does the stub save 16 registers, and not all 31? The RISC-V calling rules split the registers in two. A C function must restore s0 to s11 if it uses them; it may change the others freely. The handler is a C function, so it already protects s0 to s11. Only the caller-saved ones are at risk.
So the stub saves ra, t0 to t6 and a0 to a7: 16 registers of 4 bytes, 64 bytes of stack. Work out the frame by hand. The stub moves sp down by 64 and stores the registers in order, each 4 bytes above the last.
| Register | Offset | Address |
|---|---|---|
| ra | sp + 0 | 0x8000_FFB0 |
| t0 | sp + 4 | 0x8000_FFB4 |
| a0 | sp + 32 | 0x8000_FFD0 |
| a7 | sp + 60 | 0x8000_FFEC |
Four of the sixteen rows. The register order is the kit's (tools/soc/fwkit/trap.S).
Claim, Table, Complete
One core interrupt line serves every source, so the dispatcher must ask who called. It reads CLAIM. ap_plic answers with the number of the pending source of highest priority, and clears that pending bit. The dispatcher calls slot 2 of its table, which irq_enable(GPIO_IRQ, on_edge) filled.
static void on_edge(void)
{
gpio_ack(1u << 8); /* clear the device's condition first */
edges = edges + 1;
}
Look at the order inside on_edge(). It clears GPIO's edge flag first. A device keeps its request up until software clears the cause. Suppose the handler returned without clearing it. The dispatcher would complete, ap_plic would see the request still up, and the core would come straight back: an interrupt storm.
After the handler returns, the dispatcher writes the source number back to CLAIM. That is complete: ap_plic may now forward source 2 again.
The Rules
Rule 1: Clear the device's condition in the handler.
Otherwise its request stays up and the same interrupt comes back at once.
Rule 2: Complete every claim.
Until it does, ap_plic will not forward that source again; the kit's dispatcher does it for you.
Rule 3: Mark shared variables volatile.
Otherwise main may read one once and never again.
Rule 4: Give each shared variable one writer, or a critical section.
A read-modify-write in main that a handler can interrupt loses the handler's update.
Rule 5: Keep handlers short.
While one runs, interrupts are masked and every other source waits.
Sources for These Rules
The kit: tools/soc/fwkit/trap.S, irq.c, irq.h (docs/soc-verification-plan.md section 3.3).
Claim and complete: RISC-V PLIC specification, chapters 8 and 9 (RV-PLIC in the reference library). The ap_plic numbers: facts sections 1 and 27.9.
Caller-saved and callee-saved registers: the RISC-V calling convention (psABI). Not in the reference library; common practice.
Now Run It: Three Edges on the Chip
The lab program asks the board to pulse pad IO8 three times, with TB_EVENT 5. Each time it waits for on_edge() to count. It ran on the chip bench with the retire trace on.
282 | 80000368 | lw a5, -1976(gp) | trap, mcause = 8000000b
286 | 80000090 | addi sp, sp, -64 | x2 = 8000ffb0
287 | 80000094 | sw ra, 0(sp) | mem[8000ffb0] = 80000368
342 | 800000d0 | sw a7, 60(sp) | mem[8000ffec] = 00000000
282 | 80000368 | lw a5, -1976(gp) | trap, mcause = 8000000b
373 | 800001e4 | lw s1, 4(s0) | x9 = 00000002, read mem[0c200004] = 00000002
394 | 80000304 | sw a4, 36(a5) | mem[10001024] = 00000100
373 | 800001e4 | lw s1, 4(s0) | x9 = 00000002, read mem[0c200004] = 00000002
460 | 80000120 | mret |
460 | 80000120 | mret |Walk them. At cycle 282 the lw of main's wait loop shows a trap with mcause 8000000b. That is an external interrupt, so the lw did not complete. Four cycles later the stub moves sp down 64 bytes, and 16 stores follow, ra first and a7 last.
At cycle 373 the dispatcher reads CLAIM at 0c200004 and gets 2: source 2, GPIO. At cycle 394 the handler writes 0x100 to GPIO STATUS, clearing pin 8's flag: rule 1. At cycle 405 the dispatcher writes 2 back to CLAIM: rule 2. mret retires at cycle 460, and main repeats its lw.
From the request to mret took 184 cycles, most of it saving and restoring registers. The run took 3 interrupts, all from GPIO, and printed edges=00000003.
Why It Is Built This Way
The stub could save all 31 registers; it would be simpler and slower. It could save none and let each handler be written in assembly; that is fast and hard to get right. The kit saves exactly what C may change, so handlers are plain C and nothing is saved twice.
The table could be a switch statement inside the dispatcher. A table lets each test register its own handler with one call, and leaves the kit's files untouched. Every chip test that uses interrupts runs the same stub, so it is verified once and trusted.
The Trap: A Wait Loop with No Load
Now the hang from the opening. Change one word of the lab: declare edges without volatile. Here is the wait loop as the compiler built each version.
plain: 80000368: lw a5,-1976(gp)
8000036c: beq a5,s0,8000036c <main+0x54>
volatile: 80000368: lw a5,-1976(gp)
8000036c: beq a5,s0,80000368 <main+0x50>In the plain version, the beq jumps to itself. The load sits before the loop, so main tests a copy that can never change. On the chip, the handler ran (1 interrupt taken) and counted, and main spun until the cycle limit of 60,008. The volatile version jumps back to the lw.
There is a second, quieter trap in the rules: two writers. If main does count = count - 1 while a handler does count = count + 1, an interrupt between main's load and store loses one update. It happens rarely, so it passes most runs. The practice problems of this page give you a handler to write and a lost update to find.
At Scale
This section looks ahead. The lab has one source and one handler.
Priorities and nesting
With many sources, ap_plic priorities decide who is claimed first. Some kits re-enable interrupts inside a handler, so a more urgent one can nest.
Latency budgets
Chip plans give some interrupts a deadline in cycles. Module V5 measures handler latency against the core's reference model.
An operating system
A real product hands interrupts to an operating system's drivers. The path through the chip is the same; more software sits on top.
Try It
Run the slice: it computes the stub's frame from its register list.
Compare the a0 and a7 rows with the recorded trace: the stub stored them at 8000ffd0 and 8000ffec.
Remove t6 from the list. Predict which offset a7 gets, then run.
sp: 8000fff0 -> 8000ffb0 (64 bytes) ra at sp + 0 = 8000ffb0 t0 at sp + 4 = 8000ffb4 t1 at sp + 8 = 8000ffb8 t2 at sp + 12 = 8000ffbc t3 at sp + 16 = 8000ffc0 t4 at sp + 20 = 8000ffc4 t5 at sp + 24 = 8000ffc8 t6 at sp + 28 = 8000ffcc a0 at sp + 32 = 8000ffd0 a1 at sp + 36 = 8000ffd4 a2 at sp + 40 = 8000ffd8 a3 at sp + 44 = 8000ffdc a4 at sp + 48 = 8000ffe0 a5 at sp + 52 = 8000ffe4 a6 at sp + 56 = 8000ffe8 a7 at sp + 60 = 8000ffecCheck Yourself
Common Mistakes
Wrong Return from a handler without clearing the device's flag.
The request stays up; the same interrupt arrives again at once.
Fix Clear the cause first: write 1 to GPIO STATUS for the pin, or read UART0 RXDATA.
Wrong Share a plain variable between main and a handler.
The compiler may load it once and test the copy for ever.
Fix Declare shared variables volatile.
Wrong Let main and a handler both update one counter.
An interrupt between main's load and store loses the handler's update.
Fix Give each variable one writer, or mask interrupts around main's update.
Wrong Poll a device in a chip test that is meant to test its interrupt.
The request wire, ap_plic and the handler are never exercised.
Fix Take the interrupt and check that the bench saw it, for example in ext_gpio.
Remember
- Only a test that takes the interrupt checks the wire, ap_plic, the trap and the software together.
- The entry stub saves the 16 caller-saved registers; C saves the rest.
- Claim tells software which source; complete lets ap_plic forward it again.
- A handler clears its device's condition before it returns.
- Shared variables are volatile, and each has one writer or a critical section.