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.

One Interrupt, from Pad to MretStep through one GPIO edge on the chip. The cycle numbers are measured on our bench (riscv64-unknown-elf-gcc 14.2.0, -Os).
  • Peripheral
  • Processor
  • Interrupt
  • Data
One Interrupt, From Pad to mretStep through one GPIO edge on the chip. The cycle numbers are measured on our bench (riscv64-unknown-elf-gcc 14.2.0, -Os). peripheral GPIO pin 8 rising edge:request peripheral ap_plic source 2: pending,claim, complete processor Core takes the trap, jumpsto mtvec processor Entry stub trap.S: saves 16registers processor Dispatcher irq.c: claim, call,complete processor Your handler on_edge(): clear,count requestexternal interruptpc = mtveccallclaim, completetable[2]()
  1. peripheral GPIOpin 8 rising edge: request
    • request → ap_plic
  2. peripheral ap_plicsource 2: pending, claim, complete
    • external interrupt → Core
  3. processor Coretakes the trap, jumps to mtvec
    • pc = mtvec → Entry stub
  4. processor Entry stubtrap.S: saves 16 registers
    • call → Dispatcher
  5. processor Dispatcherirq.c: claim, call, complete
    • claim, complete → ap_plic
    • table[2]() → Your handler
  6. processor Your handleron_edge(): clear, count
  1. 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.

  2. Cycle 282: the trap

    ap_plic raised the core's external interrupt. The core stopped main between two instructions and jumped to mtvec.

  3. 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.

  4. Cycle 373: the claim

    The dispatcher reads CLAIM. ap_plic answers 2, the pending source with the highest priority, and clears its pending bit.

  5. Cycle 394: your handler

    The dispatcher calls the function in slot 2 of its table. The handler clears GPIO's edge flag, then counts.

  6. 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.

Five questions this page answers
Question
1Why must a chip test take real interrupts?
2What does the entry stub do before any C runs?
3What do claim and complete tell ap_plic?
4What must a handler do before it returns?
5How 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

New words on this page
WordMeaning
Interrupt handlerThe C function that answers one source: here on_edge() for GPIO.
Entry stubThe assembly at mtvec (the kit's trap.S) that saves registers, calls C, restores them and runs mret.
Caller-saved registerA register a C function may change without restoring it: ra, t0 to t6 and a0 to a7 on RISC-V.
Dispatch tableAn array of handler pointers, one per source number; irq_enable() fills a slot.
Claim and completeReading ap_plic CLAIM gives the source to serve; writing it back says the service is done.
Shared variableA variable that main and a handler both use.
Critical sectionA 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.

The frame, if the interrupt finds sp = 0x8000_FFF0
RegisterOffsetAddress
rasp + 00x8000_FFB0
t0sp + 40x8000_FFB4
a0sp + 320x8000_FFD0
a7sp + 600x8000_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.

The lab's handler. The full program is in the lab file of this page.
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

  1. Rule 1: Clear the device's condition in the handler.

    Otherwise its request stays up and the same interrupt comes back at once.

  2. Rule 2: Complete every claim.

    Until it does, ap_plic will not forward that source again; the kit's dispatcher does it for you.

  3. Rule 3: Mark shared variables volatile.

    Otherwise main may read one once and never again.

  4. 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.

  5. 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.

Selected rows around the first interrupt, measured on our bench (soc_tb on Verilator 5.052 2026-09-05; riscv64-unknown-elf-gcc 14.2.0, -Os). A probe on the wires saw GPIO's request rise at cycle 276.
  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.

From the listings apcc wrote (riscv64-unknown-elf-gcc 14.2.0, -Os).
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

ap_soc~12 blocks
Phone-class SoChundreds of blocks

This section looks ahead. The lab has one source and one handler.

  1. 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.

  2. Latency budgets

    Chip plans give some interrupts a deadline in cycles. Module V5 measures handler latency against the core's reference model.

  3. 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.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 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 = 8000ffec

Check Yourself

Predict the outputAn interrupt arrives while sp = 0x8000_FF80. What is the last line the slice prints?
// The frame of the kit's entry stub: it moves sp down by 64 bytes and stores the caller-saved
// registers in this order. C functions keep s0 to s11 themselves, so the stub leaves them alone.
module tb;
  localparam int N = 16;
  string       name [N];
  logic [31:0] sp_before = 32'h8000ff80, sp_after;
  initial begin
    name[0] = "ra";
    name[1] = "t0";
    name[2] = "t1";
    name[3] = "t2";
    name[4] = "t3";
    name[5] = "t4";
    name[6] = "t5";
    name[7] = "t6";
    name[8] = "a0";
    name[9] = "a1";
    name[10] = "a2";
    name[11] = "a3";
    name[12] = "a4";
    name[13] = "a5";
    name[14] = "a6";
    name[15] = "a7";
    sp_after = sp_before - 32'd64;
    $display("sp: %h -> %h (64 bytes)", sp_before, sp_after);
    for (int i = 0; i < N; i++) $display("%-2s at sp + %0d = %h", name[i], 4 * i, sp_after + 32'(4 * i));
  end
endmodule
ConceptWhy does the entry stub not save s0 to s11?
ConceptWhat does reading ap_plic CLAIM do?
ConceptA handler returns without clearing GPIO's flag. What happens?
Conceptmain waits with while (edges == i) { }, and edges is not volatile. On the chip, the handler ran. Why did main hang?

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.

Practice

Report a problem with this page