Interrupt Entry and Return

A request has passed both gates. The processor now does four things that no instruction asked for, and one instruction at the end of the handler undoes them.

You Will Be Able To

  • List what the processor saves and changes by itself when it takes an interrupt.
  • Work out the entry address in direct mode and in vectored mode.
  • Explain what a handler must save before it lets a second interrupt in.
Lesson
S6.14
Time
26 min
Runs on
Your browser
Check
6 questions

A handler worked for months. Then someone allowed a more urgent interrupt to break into it. Now the board hangs once a day, deep inside that handler. The new code looks correct, and yet one register was written twice.

Before You Start

You need S0.8: the forced jump, the saved PC and the return. You need the enable bits: the two gates, the global enable MIE, a masked request, and the word CSR.

You also need hexadecimal numbers, to add a small number to an address.

Five questions this page answers
Question
1What does the processor do by itself when it takes an interrupt?
2Where does the PC go: in direct mode, and in vectored mode?
3What does the return instruction undo?
4Why does the processor close the global enable at entry?
5What must a handler do before it lets a second interrupt in?

The Idea: One Action in, One Instruction Out

S0.8 gave the outline on a teaching processor. Save the PC, force the PC to a fixed address, and return with one instruction. A real processor does the same, and adds three things that the teaching processor did not need.

First, it writes down why it jumped. A chip has many reasons for a forced jump, and the handler must be able to ask which one this is. So the processor records a cause code.

Second, it closes the global enable. The saved PC lives in one register. A second interrupt, taken a moment later, would write that register again, and the first way back would be gone. So the processor shuts the gate by itself, in the same action, and remembers how the gate stood before.

Third, software chooses where the jump goes. It writes an address into a register, once, at start-up. The processor can use that address in two ways. It can be the one entry for every cause. Or it can be the start of a table with a slot for each cause.

The return is one instruction. It puts the saved PC back and gives the global enable its old value. Everything else that the handler changed is the handler's duty to put back.

New Words

New words on this page
WordMeaning
Cause codeA small number that names the reason for a forced jump. Each kind of interrupt has one.
Entry addressThe address that a forced jump puts into the PC.
Direct modeEvery forced jump goes to one address. The handler there reads the cause and decides what to do.
Vectored modeEach kind of interrupt jumps to a place of its own in a table.
Handler tableA row of slots in memory, one for each cause code. Also called a vector table.
Slot of a handler tableFour bytes: room for one instruction, which is usually a jump to the real handler.
Nested interruptAn interrupt taken while the handler of another one is still running.
Outer handler and inner handlerOf two nested interrupts: the handler that was broken into, and the one that broke in.
The RISC-V names this page uses
NameWhat it is
mepcThe CSR that holds the saved PC.
mcauseThe CSR that holds the cause. Bit 31 is 1 for an interrupt and 0 for an exception. The low bits hold the cause code.
mtvecThe CSR that software loads with the entry address. Its two lowest bits choose the mode: 0 is direct, 1 is vectored.
MPIEA bit of mstatus. At entry it takes the old value of MIE.
mretThe return instruction of machine mode.
Cause codes 3, 7 and 11The machine software, timer and external interrupts. They are the bit numbers of the last page.

RISC-V facts, from the privileged specification of RISC-V. Our reference library does not hold that document, so these names are not checked against it.

One Picture: Save, Record, Close, Jump, Return

What the Processor Does by Itself, and What Undoes ItStep through the picture. It follows one timer interrupt in, and back out.
  • Processor
  • Memory
  • Control / FSM
  • Bus
  • Peripheral
What the Processor Does by Itself, and What Undoes ItStep through the picture. It follows one timer interrupt in, and back out. component PC the address of thenext instruction component mepc the saved PC component mcause why the jump was made component MIE and MPIE the global enable, andits saved value component Handler table starts at theaddress in mtvec component Timer handler ends with mret 1: save the PC2: record the cause3: MIE to MPIE, thenMIE = 04: jump to a slotthe slot leads to thehandlermret: the saved PCmret: MPIE back toMIE
  1. component PCthe address of the next instruction
    • 1: save the PC → mepc
    • 2: record the cause → mcause
    • 3: MIE to MPIE, then MIE = 0 → MIE and MPIE
    • 4: jump to a slot → Handler table
  2. component mepcthe saved PC
    • mret: the saved PC → PC
  3. component mcausewhy the jump was made
  4. component MIE and MPIEthe global enable, and its saved value
    • mret: MPIE back to MIE → PC
  5. component Handler tablestarts at the address in mtvec
    • the slot leads to the handler → Timer handler
  6. component Timer handlerends with mret
  1. A request has passed both gates

    The main program is about to run the instruction at 0x84. The processor takes the timer interrupt in place of that instruction.

  2. Save the PC

    The processor copies 0x84 into mepc. That instruction has not run yet, so it is the right place to carry on.

  3. Record the cause

    It writes the cause into mcause. The top bit is 1 for an interrupt. The low bits hold the code of the kind: 7 for the timer.

  4. Close the gate

    It copies MIE into MPIE and then clears MIE. No second interrupt can be taken now, and the old value is kept.

  5. Jump

    It forces the PC to the slot of the timer in the handler table. From here on, ordinary instructions run: the handler.

  6. The return

    The last instruction of the handler is mret. It copies mepc into the PC and MPIE into MIE. The main program runs the instruction at 0x84.

Read the diagram as text
  • PC: the address of the next instruction
  • mepc: the saved PC
  • mcause: why the jump was made
  • MIE and MPIE: the global enable, and its saved value
  • Handler table: starts at the address in mtvec
  • Timer handler: ends with mret
  • PC → mepc: 1: save the PC
  • PC → mcause: 2: record the cause
  • PC → MIE and MPIE: 3: MIE to MPIE, then MIE = 0
  • PC → Handler table: 4: jump to a slot
  • Handler table → Timer handler: the slot leads to the handler
  • mepc → PC: mret: the saved PC
  • MIE and MPIE → PC: mret: MPIE back to MIE

Steps 2 to 5 take no instruction. The processor does them as one action, between two instructions.

The Smallest Example, Worked by Hand

Software has written 0x100 into mtvec, with vectored mode. The main program is about to run the instruction at 0x84 when the timer interrupt is taken. The slot of the timer is 0x100 + 4 × 7 = 0x11c.

One timer interrupt, in and out
MomentPCmepcmcauseMIEMPIE
Before0x841
After entry0x11c0x840x8000000701
After one handler instruction0x1200x840x8000000701
After mret0x840x840x8000000711

In direct mode the second row would have PC = 0x100, and nothing else would differ.

Now the outer handler lets a second interrupt in. At 0x120 it sets MIE to 1. A software interrupt is pending and enabled, so it is taken at once. Its slot is 0x100 + 4 × 3 = 0x10c.

A second interrupt inside the first
MomentPCmepcWhat it means
Outer handler opens the gate0x1200x84the way back to the main program
Entry of the inner interrupt0x10c0x120the way back to the outer handler: 0x84 is gone from mepc
Inner mret0x1200x120the outer handler carries on
Outer mret, with no copy kept0x1200x120back into the outer handler, for ever
Outer mret, after mepc is put back from a copy0x840x84the main program carries on

There is one mepc. The inner entry used it, as it must. Only a copy that the outer handler made beforehand can bring 0x84 back.

The Rules

  1. Rule 1: At entry the processor saves the PC in mepc.

    It is the address of the instruction that was about to run. For an interrupt, the return goes exactly there.

  2. Rule 2: It records the cause in mcause.

    The top bit says interrupt or exception. The low bits hold the cause code.

  3. Rule 3: It copies MIE into MPIE and clears MIE.

    So a handler starts with the global enable closed.

  4. Rule 4: It jumps to the address in mtvec, or to a slot.

    In direct mode every cause enters at that address. In vectored mode an interrupt enters at that address plus four times its cause code.

  5. Rule 5: mret copies mepc into the PC and MPIE into MIE.

    It undoes rules 1 and 3. It restores nothing else.

  6. Rule 6: A handler that sets MIE must first save mepc, and restore it before mret.

    A nested entry overwrites mepc, mcause and MPIE. The handler also closes MIE again while it restores them.

Sources for These Rules

The textbook "Computer Organization and Design" by Patterson and Hennessy, section 4.9. It covers the saved address, the recorded cause, and one entry address against a table of them.

The six rules and every name in the table of RISC-V names are RISC-V facts. They are stated from common knowledge of the privileged specification of RISC-V. Our reference library does not hold that document, so none of them is checked against it.

In vectored mode an exception still enters at the address in mtvec. That is also a RISC-V fact, not checked.

The addresses 0x84, 0x100 and 0x120 are choices of this page.

Now Run It

The lab at the end of this page is the second hand table as test code. A task named enter does what the processor does at entry. A task named mret does what that instruction does. No real processor is in the lab.

Printed by the lab on Icarus. The outer handler keeps a copy of mepc before it opens the gate.
main           pc=00000084 MIE=1
entry timer    mepc=00000084 mcause=80000007 MIE=0 MPIE=1 pc=0000011c
entry software mepc=00000120 mcause=80000003 MIE=0 MPIE=1 pc=0000010c
mret  software pc=00000120 MIE=1
mret  timer    pc=00000084 MIE=1
the main program carries on at 00000084

Rules 1 to 4 at work, all in the row "entry timer". There mepc holds 0x84 and mcause holds 0x80000007. MIE is 0 with MPIE at 1, and the PC is 0x11c.

Rule 6 at work: in the row "entry software", mepc is 0x120. The value 0x84 is no longer in any CSR. Rule 5 at work: the inner mret returns to 0x120.

The last two rows are the proof. The outer mret returns to 0x84, because the handler put its copy back first.

This lab leaves things out. It runs no instructions, so it saves no general registers. S0.8 showed why a handler must: the processor saves only the PC.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
The processor closes the gate at entrySoftware closes it with the first instructionA second interrupt cannot slip in before that instruction. Every handler starts masked, wanted or not.
One saved PC, in a registerThe processor pushes each saved PC into memoryEntry needs no memory access, so it is quick. Nesting is left to software.
A table of slotsOne entry addressNo instructions are spent on finding the cause. The table takes memory, and each slot holds only one instruction.
One entry addressA table of slotsOne handler, easy to place and to debug. It must read the cause and branch, on every interrupt.

The Trap: The Handler That Never Returned

Back to the board that hangs once a day. The timer handler was changed to set MIE early, so that a more urgent interrupt could break in. Nobody added the copy. Here is the same lab with that one line taken out:

The same lab with SAVE_FIRST = 0: the outer handler opens the gate without a copy of mepc.
main           pc=00000084 MIE=1
entry timer    mepc=00000084 mcause=80000007 MIE=0 MPIE=1 pc=0000011c
entry software mepc=00000120 mcause=80000003 MIE=0 MPIE=1 pc=0000010c
mret  software pc=00000120 MIE=1
mret  timer    pc=00000120 MIE=1
LOST: pc=00000120 is inside the timer handler

The first four rows are the same as before. The fifth is the bug: the outer mret goes to 0x120, an address inside the handler. From there the handler runs to its mret again, and again.

It fails only when the second interrupt arrives inside the first handler, which is why it took a day. On every other run, mepc still held 0x84 at the outer mret, and the missing copy did no harm.

A smaller trap is the slot. It holds an instruction, not an address. Put the address of the handler there, and the processor runs that number as if it were an instruction.

At Scale

This page2 handlers, 1 copy
Firmware of a productdozens of handlers, a stack of copies

This section looks ahead. Real firmware wraps these rules in a few lines that every handler shares.

  1. A stack of copies

    Each handler that may be broken into keeps its copies in memory, one set above the other. It takes them back in reverse order.

  2. General registers

    The same code saves every register that the handler will use, and restores them before mret.

  3. Exceptions

    An exception uses the same registers. Its handler often returns to the instruction after the one that failed, so it changes mepc first.

  4. How long entry takes

    Interrupt Latency counts the clock edges from the event to the first instruction of the handler.

Try It

Run the lab. Check each row against the two hand tables.

Set VECTORED to 0. Predict the PC in both entry rows, and the mepc of the inner entry.

Set SAVE_FIRST to 0. Find the first row that differs, and say which rule was broken.

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: main pc=00000084 MIE=1 entry timer mepc=00000084 mcause=80000007 MIE=0 MPIE=1 pc=0000011c entry software mepc=00000120 mcause=80000003 MIE=0 MPIE=1 pc=0000010c mret software pc=00000120 MIE=1 mret timer pc=00000084 MIE=1 the main program carries on at 00000084

Check Yourself

Predict the outputThis run uses direct mode. Which row does the lab print for the entry of the software interrupt?
// Entry and return. Test code stands in for the processor: it keeps the PC and the machine registers.
module tb;
  localparam BASE = 32'h0000_0100;      // the address that software wrote into mtvec
  localparam VECTORED = 0;                // 1: a slot for each kind of interrupt. 0: one address for all
  localparam TIMER = 7, SOFTWARE = 3;   // the cause codes of two kinds of interrupt
  localparam TIMER_SLOT    = 32'h0000_011c;   // slot 7 of the handler table
  localparam SOFTWARE_SLOT = 32'h0000_010c;   // slot 3 of the handler table
  localparam SAVE_FIRST = 1;              // 1: the outer handler keeps a copy of mepc before it opens the gate

  logic [31:0] pc = 32'h0000_0084;      // the main program is about to run the instruction at 0x84
  logic [31:0] mepc = 0, mcause = 0;    // the saved PC, and the reason for the jump
  logic mie = 1, mpie = 0;              // the global enable, and the place that keeps its old value
  logic [31:0] copy = 0;                // one word that the outer handler owns

  // What the processor does when it takes an interrupt. No instruction does this: it is hardware.
  task automatic enter(input string kind, input int code, input logic [31:0] slot);
    mepc   = pc;                        // 1. save the PC
    mcause = 32'h8000_0000 | code;      // 2. record the cause. The top bit says: an interrupt
    mpie   = mie;                       // 3. keep the old global enable ...
    mie    = 0;                         //    ... and close the gate
    pc     = VECTORED ? slot : BASE;    // 4. jump
    $display("entry %-8s mepc=%08h mcause=%08h MIE=%b MPIE=%b pc=%08h", kind, mepc, mcause, mie, mpie, pc);
  endtask

  // What the instruction mret does.
  task automatic mret(input string kind);
    pc  = mepc;                         // back to the saved PC
    mie = mpie;                         // the global enable gets its old value back
    $display("mret  %-8s pc=%08h MIE=%b", kind, pc, mie);
  endtask

  initial begin
    $display("main           pc=%08h MIE=%b", pc, mie);
    enter("timer", TIMER, TIMER_SLOT);
    pc = pc + 4;                        // the timer handler has run one instruction
    if (SAVE_FIRST) copy = mepc;        // keep a copy of the way back
    mie = 1;                            // the handler opens the gate for something more urgent
    enter("software", SOFTWARE, SOFTWARE_SLOT);
    mret("software");                   // the inner handler is done
    mie = 0;                            // the outer handler closes the gate again ...
    if (SAVE_FIRST) mepc = copy;        // ... and puts its own way back in place
    mret("timer");
    if (pc == 32'h0000_0084) $display("the main program carries on at %08h", pc);
    else                     $display("LOST: pc=%08h is inside the timer handler", pc);
  end
endmodule
ConceptWhat does the processor do by itself when it takes an interrupt?
Conceptmtvec holds 0x200 with vectored mode. Where does a timer interrupt, cause code 7, enter?
ConceptWhat does mret undo?
ConceptWhy does the processor close the global enable at entry?
ConceptWhat must a handler do before it sets MIE?

Common Mistakes

Wrong Set MIE inside a handler without saving mepc first.

A nested entry overwrites the only saved PC.

Fix Save mepc, then open the gate. Close it and restore mepc before mret.

Wrong Put the address of a handler into a slot of the table.

The processor runs the content of a slot as an instruction.

Fix Put a jump instruction into the slot.

Wrong Add 4 to mepc before returning from an interrupt.

mepc already holds the instruction that has not run. Adding 4 skips it.

Fix Return to mepc as it was saved.

Remember

  • At entry the processor saves the PC in mepc, records the cause in mcause, closes MIE and jumps.
  • Direct mode: one entry address. Vectored mode: the address in mtvec plus four times the cause code.
  • mret puts back the PC and the global enable, and nothing else.
  • There is one mepc. Save it before a second interrupt may be taken.

Practice

Report a problem with this page