Traps: Exceptions, Interrupts and the Machine CSRs

A word in the program is no instruction. The processor cannot run it, and it must not go on as if nothing happened. It needs a safe way out, and a way back.

You Will Be Able To

  • Tell an exception from an interrupt, and say what both have in common.
  • Name the five machine CSRs of a trap, and say what each holds after one.
  • Follow a trap from its entry to mret, and say who does each step: hardware or software.
Lesson
S2.13
Time
35 min
Runs on
Your browser
Check
6 questions

Until now every instruction did its work, and the next one followed. Now one cannot. What the processor does next is fixed in five registers.

Before You Start

You need the illegal instruction from S2.22: the decoder knows when a word is no instruction.

It helps to know interrupts from S0.8. The entry of an interrupt is taught later, on S6.14. This page does not repeat it.

Five questions this page answers
Question
1What is the difference between an exception and an interrupt?
2Which register holds the address of the instruction that failed?
3Which register tells the handler why it was called?
4What does the processor do by itself when a trap is taken?
5What does mret do, and who decides where it returns to?

The Idea: Stop, Write Down What Happened, Jump

Sometimes the processor must leave the program. It jumps to other code that deals with the event. This forced jump is a processor trap, or trap for short.

A trap has one of two origins. The first is the instruction itself: it cannot be executed. That is an exception.

The second is a signal from outside, such as a timer. It has nothing to do with the instruction. That is an interrupt.

An exception is synchronous: run the program again, and it happens at the same instruction. An interrupt is asynchronous: it can arrive at any instruction.

Both use the same mechanism. The processor writes down where it was, and why. Then it jumps to a fixed address.

The code at that address is the handler. It is ordinary software. It looks at what was written down, and acts.

The notes are kept in special registers beside x0 to x31. Such a register is a CSR: a control and status register.

The handler ends with an instruction named mret. It jumps back to the address that was written down.

New Words

New words on this page
WordMeaning
Processor trapA forced jump to the handler, made by the processor and not by a jump instruction. Here: a trap.
ExceptionA trap caused by the instruction that is being executed. It is synchronous.
InterruptA trap caused by a signal from outside the program. It is asynchronous.
Synchronous, asynchronousTied to one instruction of the program, or arriving at any time.
HandlerThe software that the processor jumps to when it takes a trap.
CSRControl and status register: a register of the processor that is not one of x0 to x31.
mtvecThe CSR with the address of the handler. Software writes it once, early.
mepcThe CSR with the address of the instruction that trapped.
mcauseThe CSR with the reason, as a number. Bit 31 is 1 for an interrupt.
mtvalThe CSR with one more detail of the fault: here, the word that was no instruction.
MIEMachine interrupt enable: one bit. Interrupts are taken only while it is 1.
MPIEMachine previous interrupt enable: one bit. It keeps what MIE held before the trap.
mstatusThe CSR that holds MIE, at bit 3, and MPIE, at bit 7.
csrr, csrwThe instructions that copy a CSR into a register, and a register into a CSR.
mretThe instruction that ends a handler: the PC takes mepc, and MIE takes MPIE.

The letter m in each name stands for machine. S2.14 explains why the names carry it.

One Picture: What the Processor Writes Down

Five Registers Catch One FaultStep through the picture. It follows the word at address 0c, which is no instruction, into the handler and back.
  • Processor
  • Memory
  • Control / FSM
  • Bus
  • Peripheral
Five Registers Catch One FaultStep through the picture. It follows the word at address 0c, which is no instruction, into the handler and back. component PC holds 0c: the wordthat cannot run component mepc where it happened component mcause why: a number component mtval one more detail of thefault component mstatus the bits MIE andMPIE component mtvec holds 40: the addressof the handler component Handler software at 40, endswith mret 1: mepc takes 0c2: mcause takes 23: mtval takes theword4: MPIE takes MIE,MIE = 05: the PC takes 40the handler runsmret: the PC takesmepc
  1. component PCholds 0c: the word that cannot run
    • 1: mepc takes 0c → mepc
    • 2: mcause takes 2 → mcause
    • 3: mtval takes the word → mtval
    • 4: MPIE takes MIE, MIE = 0 → mstatus
  2. component mepcwhere it happened
    • mret: the PC takes mepc → PC
  3. component mcausewhy: a number
  4. component mtvalone more detail of the fault
  5. component mstatusthe bits MIE and MPIE
  6. component mtvecholds 40: the address of the handler
    • 5: the PC takes 40 → PC
    • the handler runs → Handler
  7. component Handlersoftware at 40, ends with mret
  1. The fault

    The PC holds 0c. The word there is 0000_0000. The decoder says: this is no instruction.

  2. Three registers record it

    mepc takes the address 0c. mcause takes the number 2. mtval takes the word itself.

  3. The interrupt enable closes

    MPIE keeps the old value of MIE. Then MIE becomes 0. No interrupt can disturb the first steps of the handler.

  4. The jump

    The PC takes the address in mtvec, 40. All five steps happen in one clock edge.

  5. The handler, then mret

    The handler reads mcause and decides. Its last instruction, mret, puts mepc into the PC. MIE takes MPIE back.

Read the diagram as text
  • PC: holds 0c: the word that cannot run
  • mepc: where it happened
  • mcause: why: a number
  • mtval: one more detail of the fault
  • mstatus: the bits MIE and MPIE
  • mtvec: holds 40: the address of the handler
  • Handler: software at 40, ends with mret
  • PC → mepc: 1: mepc takes 0c
  • PC → mcause: 2: mcause takes 2
  • PC → mtval: 3: mtval takes the word
  • PC → mstatus: 4: MPIE takes MIE, MIE = 0
  • mtvec → PC: 5: the PC takes 40
  • mtvec → Handler: the handler runs
  • mepc → PC: mret: the PC takes mepc

The entry is done by hardware, in one step. Everything after it is software, until mret.

Exception or interrupt
EventKindWhy
A word that is no instructionExceptionThe instruction itself is the cause.
A load from an address with no memoryExceptionThe same instruction fails every time.
The instruction ecallExceptionThe program asks for the handler on purpose.
The timer reaches its compare valueInterruptThe program did nothing to cause it at this instruction.
A byte arrives at the UARTInterruptIt comes from outside, at any time.

Some books use the word exception for both kinds. RISC-V calls the jump a trap and keeps the two words apart.

The Smallest Example, Worked by Hand

The program
Address, in hexInstructionWhat it is for
000addi x5, x0, 64the address of the handler
004csrw mtvec, x5tell the processor where it is
008addi x10, x0, 1
00c.word 0x00000000not an instruction
010addi x10, x10, 1
014jal x0, 0x14stop
040csrr x6, mcausethe handler: why did we come here?
044csrr x7, mepcwhere did it happen?
048addi x7, x7, 4the instruction behind it
04ccsrw mepc, x7
050mretgo back

The first two instructions install the handler. The word at 0c is the fault. The handler is at 40.

Follow it. The first two instructions put 40 into mtvec. The third puts 1 into x10.

At 0c the processor finds a word that is no instruction. It takes a trap.

The five CSRs before and after the entry
CSRBeforeAfterWho wrote it
mtvec0000_00400000_0040The program, at address 04
mepc0000_00000000_000cThe processor: the address of the fault
mcause0000_00000000_0002The processor: 2 means illegal instruction
mtval0000_00000000_0000The processor: the word itself, which is 0 here
mstatus0000_18000000_1800The processor: MPIE takes MIE, which was 0

The PC takes 40. Nothing else changes: no register x1 to x31, and no memory word.

Now the handler runs. It reads mcause into x6 and mepc into x7. It adds 4 to x7 and writes it back to mepc.

Why add 4? Because mepc points at the faulty word. A return to 0c would meet the same fault again.

Then mret puts mepc, now 10, into the PC. The program goes on behind the fault.

The Rules

  1. Rule 1: An exception belongs to one instruction. An interrupt belongs to none.

    So mepc of an exception is the instruction that failed. For an interrupt it is the one that was about to run.

  2. Rule 2: At the entry, mepc takes the address, mcause the reason and mtval the detail.

    All three in one clock edge. The instruction that trapped changes nothing else.

  3. Rule 3: At the entry, MPIE takes MIE, and MIE becomes 0.

    Interrupts are closed until software opens them again, or until mret.

  4. Rule 4: At the entry, the PC takes the address in mtvec.

    An exception always goes to this one address. Interrupts can also use a handler table, with one address for each cause: see S6.14.

  5. Rule 5: mret puts mepc into the PC. MIE takes MPIE, and MPIE becomes 1.

    It undoes the entry. It does not look at mcause.

  6. Rule 6: The handler decides where mret returns to.

    Behind an instruction that cannot run, it adds 4 to mepc. After an interrupt it changes nothing.

Sources for These Rules

Checked in the library: Patterson and Hennessy, Computer Organization and Design (ARM edition), section 4.9. It has the two kinds of event, the saved address, the cause register and the handler at a fixed address. Its processor uses other register names. Harris and Harris, Digital Design and Computer Architecture (ARM edition), section 6.6.3, has exceptions for another processor. The RISC-V names, bit positions and cause numbers come from the RISC-V privileged specification. That document is not in our library: they are not checked against it. They are checked against the real core: docs/soc/ap_rv32-blueprint.md, sections 5 and 7. Every row on this page was also given by the real core ap_rv32.

Now Run It

The lab at the end of this page is a small model of a processor with traps. It runs the program above.

Printed by the lab on Icarus. The real core ap_rv32 ran the same program, and every row agrees with its trace.
00000000 | addi x5, x0, 64 | x5 = 00000040
00000004 | csrw mtvec, x5 | mtvec = 00000040
00000008 | addi x10, x0, 1 | x10 = 00000001
0000000c | .word 0x00000000 | TRAP mcause=2 mepc=0000000c mtval=00000000, next is 00000040
00000040 | csrr x6, mcause | x6 = 00000002
00000044 | csrr x7, mepc | x7 = 0000000c
00000048 | addi x7, x7, 4 | x7 = 00000010
0000004c | csrw mepc, x7 | mepc = 00000010
00000050 | mret | next is 00000010, MIE=0
00000010 | addi x10, x10, 1 | x10 = 00000002
00000014 | jal x0, 0x14 | the program stops here
x6=2 x7=00000010 x10=2 instructions=9 traps=1

Rule 2 at work: read the row at 0000000c. It is marked as a trap, with mcause 2 and mepc 0000000c. The word was 0, so mtval is 0.

Rule 4 at work: the same row ends with "next is 00000040". The next row is the first instruction of the handler.

The handler: the row at 40 reads mcause, and x6 becomes 2. The rows at 44 to 4c move mepc from 0c to 10.

Rule 5 at work: the row at 50 is mret. It says "next is 00000010". The row after it is the instruction behind the fault.

The last line counts 9 instructions and 1 trap. The faulty word is not counted as an instruction: it never ran.

Now the two bits of mstatus. The next program opens MIE first, then calls the handler with ecall.

The second lab. Also equal to the trace of the real core, where mstatus is one field of every record.
00000000 | addi x5, x0, 64 | x5 = 00000040
00000004 | csrw mtvec, x5 | mtvec = 00000040
00000008 | addi x5, x0, 8 | x5 = 00000008
0000000c | csrs mstatus, x5 | mstatus = 00001808
00000010 | ecall | TRAP mcause=11 mepc=00000010 mtval=00000000, next is 00000040
00000040 | csrr x8, mstatus | x8 = 00001880
00000044 | csrr x6, mcause | x6 = 0000000b
00000048 | csrr x7, mepc | x7 = 00000010
0000004c | addi x7, x7, 4 | x7 = 00000014
00000050 | csrw mepc, x7 | mepc = 00000014
00000054 | mret | next is 00000014, MIE=1
00000014 | csrr x11, mstatus | x11 = 00001888
00000018 | jal x0, 0x18 | the program stops here
x8=00001880 x11=00001888 x6=11 instructions=11 traps=1

Before the trap, mstatus is 0000_1808: bit 3, MIE, is 1. Inside the handler x8 reads 0000_1880.

Rule 3 at work: bit 3 went to 0, and bit 7, MPIE, took the 1. After mret, x11 reads 0000_1888: MIE is back.

The 18 in front is a field of two bits that is always 11 on this core. S2.14 and S2.30 explain it.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Save the PC in a CSRSave it on the stack, as some processors doNo memory access at the entry, so the entry cannot fail. One level only: S6.14 shows the cost.
One handler address for every exceptionAn address for each causeOne register. The handler must read mcause and branch.
The cause as a number in mcauseThe handler works it out from the instructionA read of one CSR. The numbers must be agreed by everybody.
The handler changes mepcThe processor always returns behind the instructionSoftware can also repeat the instruction, after it repaired the cause.
Close MIE at the entryLeave interrupts openThe first instructions of the handler cannot be interrupted before mepc is safe.

Why does software get so much to do? Because the right answer differs. One fault ends a program, and another is repaired and repeated.

The Trap: No Handler Was Installed

After reset mtvec holds 0. Suppose the program forgets to write it, and then meets a fault.

The processor does what the rules say. It jumps to the address in mtvec. That is address 0: the start of the program.

A program of four rows with no handler. The lab stops it after 12 steps. The real core gave the same 12 records.
00000000 | addi x10, x10, 1 | x10 = 00000001
00000004 | .word 0x00000000 | TRAP mcause=2 mepc=00000004 mtval=00000000, next is 00000000
00000000 | addi x10, x10, 1 | x10 = 00000002
00000004 | .word 0x00000000 | TRAP mcause=2 mepc=00000004 mtval=00000000, next is 00000000
00000000 | addi x10, x10, 1 | x10 = 00000003
00000004 | .word 0x00000000 | TRAP mcause=2 mepc=00000004 mtval=00000000, next is 00000000
00000000 | addi x10, x10, 1 | x10 = 00000004
00000004 | .word 0x00000000 | TRAP mcause=2 mepc=00000004 mtval=00000000, next is 00000000
00000000 | addi x10, x10, 1 | x10 = 00000005
00000004 | .word 0x00000000 | TRAP mcause=2 mepc=00000004 mtval=00000000, next is 00000000
00000000 | addi x10, x10, 1 | x10 = 00000006
00000004 | .word 0x00000000 | TRAP mcause=2 mepc=00000004 mtval=00000000, next is 00000000
still running after 6 instructions and 6 traps
x10=6 mepc=00000004 mcause=2 instructions=6 traps=6

Read the rows. The program runs its first instruction, traps at 04, and starts again at 00. And again.

Nothing looks broken. x10 counts up, and the fault is never reported. The row at 08 is never reached.

So the first work of start-up code is to write mtvec. A fault before that write restarts the program without a word.

At Scale

This lab1 fault, a handler of 5 instructions
ap_rv329 causes of exception and 3 interrupts, one handler address

This section looks ahead. One fault and five registers are the whole mechanism. Larger systems build much on it.

  1. Interrupts use the same five registers

    S6.4 has the enable bits and S6.14 the entry with a handler table. S6.15 measures the delay.

  2. The other causes

    S2.29 goes through the causes of ap_rv32 one by one, with ecall and ebreak. It also shows the trap inside the pipeline.

  3. A handler must save what it uses

    The handler here overwrites x6 and x7. A real one saves every register it touches, as a called function does on its stack frame.

  4. An operating system lives here

    In a large system the handler belongs to the operating system. A program that faults is ended, and the others go on. That is common practice.

Try It

Run the lab. Find the row that is marked as a trap, and the row with mret.

Change the faulty row to i(WORD, 0, 0, 32'hffffffff). Which value on the row of the trap changes?

Remove the row with ADDI 7, 7, 4 from the handler. What does the lab print now, and why does it never stop by itself?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 00000000 | addi x5, x0, 64 | x5 = 00000040 00000004 | csrw mtvec, x5 | mtvec = 00000040 00000008 | addi x10, x0, 1 | x10 = 00000001 0000000c | .word 0x00000000 | TRAP mcause=2 mepc=0000000c mtval=00000000, next is 00000040 00000040 | csrr x6, mcause | x6 = 00000002 00000044 | csrr x7, mepc | x7 = 0000000c 00000048 | addi x7, x7, 4 | x7 = 00000010 0000004c | csrw mepc, x7 | mepc = 00000010 00000050 | mret | next is 00000010, MIE=0 00000010 | addi x10, x10, 1 | x10 = 00000002 00000014 | jal x0, 0x14 | the program stops here x6=2 x7=00000010 x10=2 instructions=9 traps=1

Check Yourself

Predict the outputThe program adds 5 to x10 three times. Two rows in between trap, and the handler adds 100 each time. What does the last line say?
// Two faults in one program. What does the last line say?
// The program is the task at the top. Each row is one instruction: i(kind, a, b, c).
// The comment beside a row is its address and the same instruction in assembly.
module tb;
  task automatic the_program();
    i(ADDI,   5,  0,  64);             // 000: addi x5, x0, 64
    i(CSRW,   5,  0,  MTVEC);          // 004: csrw mtvec, x5
    i(ADDI,   10, 0,  5);              // 008: addi x10, x0, 5
    i(WORD,   0,  0,  32'hffffffff);   // 00c: .word 0xffffffff
    i(ADDI,   10, 10, 5);              // 010: addi x10, x10, 5
    i(ECALL,  0,  0,  0);              // 014: ecall
    i(ADDI,   10, 10, 5);              // 018: addi x10, x10, 5
    i(JAL,    0,  0,  'h1c);           // 01c: jal x0, 0x1c
    at('h40);
    i(ADDI,   10, 10, 100);            // 040: addi x10, x10, 100      the handler counts in hundreds
    i(CSRR,   6,  0,  MCAUSE);         // 044: csrr x6, mcause
    i(CSRR,   7,  0,  MEPC);           // 048: csrr x7, mepc
    i(ADDI,   7,  7,  4);              // 04c: addi x7, x7, 4
    i(CSRW,   7,  0,  MEPC);           // 050: csrw mepc, x7
    i(MRET,   0,  0,  0);              // 054: mret
  endtask

  // ---- From here down: a small model of a RISC-V processor with traps, as test code. ----
  // It is a model beside the real core ap_rv32, not a part of it.
  localparam int LUI = 0, ADDI = 1, ANDI = 2, ORI = 3, SLLI = 4, SRLI = 5, ADD = 6, SUB = 7, AND = 8, OR = 9, LW = 10, SW = 11,
                 BEQ = 12, BNE = 13, BLT = 14, BGE = 15, JAL = 16, JALR = 17, CSRR = 18, CSRW = 19, CSRS = 20, CSRC = 21, MRET = 22, ECALL = 23, EBREAK = 24, WORD = 25;
  localparam int MSTATUS = 'h300, MISA = 'h301, MTVEC = 'h305, MSCRATCH = 'h340, MEPC = 'h341, MCAUSE = 'h342, MTVAL = 'h343, MIP = 'h344, MIMPID = 'hf13, MHARTID = 'hf14;
  int kind [0:1023], fa [0:1023], fb [0:1023];   // the program: one row for each instruction
  logic [31:0] fc [0:1023];
  int here = 0;                                   // the address of the next row
  task automatic at(input int address);           // the rows that follow start at this address
    here = address;
  endtask
  task automatic i(input int k, input int a, input int b, input logic [31:0] c);   // add one row to the program
    if (here < 4096) begin kind[here >> 2] = k; fa[here >> 2] = a; fb[here >> 2] = b; fc[here >> 2] = c; end
    here += 4;
  endtask
  logic [31:0] x [0:31];             // the 32 registers
  logic [31:0] pc;                   // the address of the next instruction
  logic [31:0] mem [0:16383];        // 64 KiB of data memory, from address 8000_0000 up
  logic [31:0] mstatus, mtvec, mscratch, mepc, mcause, mtval;   // the machine CSRs of this model
  logic [1:0]  level;                // the privilege level: 3 is machine (the only one here)
  localparam bit USER = 0;           // 1: the model has a user level. ap_rv32 v1.0 has none
  logic [31:0] reset_pc = 0;         // the address of the first instruction: the input reset_vector of a core
  logic [31:0] hart_value = 0;       // what mhartid reads: the input hart_id of a core
  logic [31:0] mip_value = 0;        // what mip reads: the three interrupt inputs of a core, at bits 11, 7 and 3
  int   steps, traps;
  bit   stopped;
  function automatic string cn(input logic [11:0] a);   // the name of a CSR
    case (a)
      MSTATUS: return "mstatus";  MTVEC: return "mtvec";  MSCRATCH: return "mscratch";  MEPC: return "mepc";
      MCAUSE: return "mcause";  MTVAL: return "mtval";  MHARTID: return "mhartid";
      MISA: return "misa";  MIP: return "mip";  MIMPID: return "mimpid";
      default: return $sformatf("0x%0h", a);
    endcase
  endfunction
  function automatic string nm(input int k);            // the name of a kind of instruction
    case (k)
      0: return "lui"; 1: return "addi"; 2: return "andi"; 3: return "ori"; 4: return "slli"; 5: return "srli"; 
      6: return "add"; 7: return "sub"; 8: return "and"; 9: return "or"; 10: return "lw"; 11: return "sw"; 
      12: return "beq"; 13: return "bne"; 14: return "blt"; 15: return "bge"; 16: return "jal"; 17: return "jalr"; 
      18: return "csrr"; 19: return "csrw"; 20: return "csrs"; 21: return "csrc"; 22: return "mret"; 23: return "ecall"; 
      24: return "ebreak"; 25: return "word"; 
      default: return "?";
    endcase
  endfunction
  function automatic bit csr_exists(input logic [11:0] a);
    return a == MSTATUS || a == MTVEC || a == MSCRATCH || a == MEPC || a == MCAUSE || a == MTVAL || a == MHARTID || a == MISA || a == MIP || a == MIMPID;
  endfunction
  function automatic logic [31:0] csr_value(input logic [11:0] a);
    case (a)
      MSTATUS: return mstatus;  MTVEC: return mtvec;  MSCRATCH: return mscratch;  MEPC: return mepc;
      MCAUSE: return mcause;  MTVAL: return mtval;
      MISA: return 32'h4000_0100;  MIMPID: return 32'h0001_0000;   // what this core is: 32 bits, base set I; version 1.0
      MIP: return mip_value;
      default: return hart_value;                       // mhartid
    endcase
  endfunction
  task automatic csr_store(input logic [11:0] a, input logic [31:0] v);   // each CSR keeps only its writable bits
    case (a)
      MSTATUS: begin
        mstatus[3] = v[3];  mstatus[7] = v[7];                             // MIE and MPIE
        if (USER && (v[12:11] == 2'b00 || v[12:11] == 2'b11)) mstatus[12:11] = v[12:11];   // MPP: user or machine
      end
      MTVEC:    mtvec = v & 32'hffff_fffd;                                 // bit 1 always reads 0
      MSCRATCH: mscratch = v;
      MEPC:     mepc = v & 32'hffff_fffc;                                  // an instruction address: bits 1:0 read 0
      MCAUSE:   mcause = v;
      MTVAL:    mtval = v;
      default: ;
    endcase
  endtask
  // The entry of a trap: what the processor does by itself, in one step.
  task automatic take_trap(input logic [31:0] cause, input logic [31:0] tval, input string text);
    string lv;
    lv = "";
    mepc = pc & 32'hffff_fffc;  mcause = cause;  mtval = tval;
    mstatus[7] = mstatus[3];  mstatus[3] = 1'b0;                           // MPIE takes MIE, MIE closes
    if (USER) begin mstatus[12:11] = level;  level = 2'd3; end             // MPP takes the level, the level is machine
    $display("%s%08h | %s | TRAP mcause=%0d mepc=%08h mtval=%08h, next is %08h", lv, pc, text, cause, mepc, mtval, mtvec & 32'hffff_fffc);
    pc = mtvec & 32'hffff_fffc;  traps++;
  endtask
  // One instruction: read the row at the PC, do what it says or take a trap, and print one line.
  task automatic step();
    int k, a, b;
    logic [31:0] c, r1, r2, res, next, ad, word;
    string text, effect, lv;
    bit writes, take, done;
    lv = "";
    done = 0;  writes = 1;  res = 0;  effect = "";  next = pc + 4;
    if (pc >= 32'h1000) begin take_trap(1, pc, "(no memory here)");  done = 1;  k = WORD;  a = 0;  b = 0;  c = 0; end
    else begin k = kind[pc >> 2];  a = fa[pc >> 2];  b = fb[pc >> 2];  c = fc[pc >> 2]; end
    r1 = x[b[4:0]];  r2 = x[c[4:0]];
    if (!done) case (k)
      LUI:  begin res = c << 12;  text = $sformatf("lui x%0d, 0x%0h", a, c); end
      ADDI: res = r1 + c;
      ANDI: res = r1 & c;
      ORI:  res = r1 | c;
      SLLI: res = r1 << c[4:0];
      SRLI: res = r1 >> c[4:0];
      ADD:  res = r1 + r2;
      SUB:  res = r1 - r2;
      AND:  res = r1 & r2;
      OR:   res = r1 | r2;
      LW, SW: begin
        ad = r1 + c;
        text = $sformatf("%s x%0d, %0d(x%0d)", nm(k), a, $signed(c), b);
        if (ad[1:0] != 0) begin take_trap(k == LW ? 4 : 6, ad, text);  done = 1; end
        else if (ad < 32'h8000_0000 || ad > 32'h8000_fffc) begin take_trap(k == LW ? 5 : 7, ad, text);  done = 1; end
        else if (k == LW) begin res = mem[ad[15:2]];  effect = $sformatf(" from mem[%08h]", ad); end
        else begin mem[ad[15:2]] = x[a[4:0]];  writes = 0;  effect = $sformatf("mem[%08h] = %08h", ad, x[a[4:0]]); end
      end
      BEQ, BNE, BLT, BGE: begin
        r1 = x[a[4:0]];  r2 = x[b[4:0]];  writes = 0;
        case (k)
          BEQ: take = (r1 == r2);
          BNE: take = (r1 != r2);
          BLT: take = ($signed(r1) < $signed(r2));
          default: take = ($signed(r1) >= $signed(r2));
        endcase
        text = $sformatf("%s x%0d, x%0d, 0x%0h", nm(k), a, b, c);
        if (take && c[1:0] != 0) begin take_trap(0, c, text);  done = 1; end
        else if (take) begin next = c;  effect = $sformatf("taken: next is %08h", next); end
        else effect = "not taken";
      end
      JAL, JALR: begin
        res = pc + 4;
        if (k == JAL) begin next = c;  text = $sformatf("jal x%0d, 0x%0h", a, c); end
        else begin next = (r1 + c) & ~32'd1;  text = $sformatf("jalr x%0d, %0d(x%0d)", a, $signed(c), b); end
        if (next[1:0] != 0) begin take_trap(0, next, text);  done = 1; end
        else if (k == JAL && next == pc) begin
          $display("%s%08h | %s | the program stops here", lv, pc, text);
          stopped = 1;  done = 1;
        end
      end
      CSRR, CSRW, CSRS, CSRC: begin
        word = {c[11:0], (k == CSRR) ? 5'd0 : a[4:0], (k == CSRW) ? 3'd1 : (k == CSRC) ? 3'd3 : 3'd2, (k == CSRR) ? a[4:0] : 5'd0, 7'h73};
        if (k == CSRR) text = $sformatf("csrr x%0d, %s", a, cn(c[11:0]));
        else text = $sformatf("%s %s, x%0d", nm(k), cn(c[11:0]), a);
        // Illegal: the CSR does not exist, or it is read-only and would be written, or the level is too low.
        if (!csr_exists(c[11:0]) || (k != CSRR && c[11:10] == 2'b11) || level < c[9:8]) begin take_trap(2, word, text);  done = 1; end
        else if (k == CSRR) res = csr_value(c[11:0]);
        else begin
          writes = 0;
          case (k)
            CSRW:    csr_store(c[11:0], x[a[4:0]]);
            CSRS:    csr_store(c[11:0], csr_value(c[11:0]) | x[a[4:0]]);
            default: csr_store(c[11:0], csr_value(c[11:0]) & ~x[a[4:0]]);
          endcase
          effect = $sformatf("%s = %08h", cn(c[11:0]), csr_value(c[11:0]));
        end
      end
      MRET: begin
        text = "mret";
        if (level != 2'd3) begin take_trap(2, 32'h3020_0073, text);  done = 1; end
        else begin
          writes = 0;  next = mepc;
          mstatus[3] = mstatus[7];  mstatus[7] = 1'b1;                     // MIE takes MPIE back
          if (USER) begin level = mstatus[12:11];  mstatus[12:11] = 2'b00; end
          effect = $sformatf("next is %08h, MIE=%0d", next, mstatus[3]);
        end
      end
      ECALL:  begin take_trap((level == 2'd3) ? 11 : 8, 0, "ecall");  done = 1; end
      EBREAK: begin take_trap(3, pc, "ebreak");  done = 1; end
      default: begin take_trap(2, c, $sformatf(".word 0x%08h", c));  done = 1; end
    endcase
    if (k >= ADDI && k <= SRLI) text = $sformatf("%s x%0d, x%0d, %0d", nm(k), a, b, $signed(c));
    if (k >= ADD && k <= OR)    text = $sformatf("%s x%0d, x%0d, x%0d", nm(k), a, b, c[4:0]);
    if (!done) begin
      if (writes) begin
        if (a[4:0] != 0) x[a[4:0]] = res;                    // register 0 is never written
        effect = {$sformatf("x%0d = %08h", a, x[a[4:0]]), effect};
        if (k == JAL || k == JALR) effect = {effect, $sformatf(", next is %08h", next)};
      end
      $display("%s%08h | %s | %s", lv, pc, text, effect);
      pc = next;  steps++;
    end
  endtask
  task automatic power_on();
    for (int n = 0; n < 32; n++) x[n] = 0;
    for (int n = 0; n < 16384; n++) mem[n] = 0;
    mstatus = 32'h0000_1800;  mtvec = 0;  mscratch = 0;  mepc = 0;  mcause = 0;  mtval = 0;   // the values after reset
    level = 2'd3;  pc = reset_pc;  steps = 0;  traps = 0;  stopped = 0;
  endtask
  task automatic run();
    while (!stopped && steps + traps < 400) step();
  endtask
  initial begin
    for (int n = 0; n < 1024; n++) begin kind[n] = WORD; fa[n] = 0; fb[n] = 0; fc[n] = 0; end   // empty memory reads as 0
    the_program();
    power_on();
    run();
    if (!stopped) $display("still running after %0d instructions and %0d traps", steps, traps);
    $display("x10=%0d x6=%0d traps=%0d", x[10], x[6], traps);
  end
endmodule
ConceptWhat is the difference between an exception and an interrupt?
ConceptWhich register holds the address of the instruction that failed?
ConceptWhich register tells the handler why it was called?
ConceptWhat does the processor do by itself when a trap is taken?
ConceptWho decides where mret returns to?

Common Mistakes

Wrong Return from an exception without changing mepc.

mepc points at the instruction that failed. It fails again, for ever.

Fix Add 4 to mepc, or repair the cause first.

Wrong Expect the processor to save x1 to x31 at a trap.

It saves the PC and one status bit, and nothing more.

Fix The handler saves every register that it uses.

Wrong Write mtvec late in the start-up code.

A fault before the write jumps to address 0 and restarts the program.

Fix Write mtvec in the first instructions.

Remember

  • A trap is a forced jump. An exception comes from the instruction, an interrupt from outside.
  • At the entry the processor writes mepc, mcause and mtval, moves MIE to MPIE, and jumps to mtvec.
  • mret jumps to mepc and gives MIE back. The handler decides whether mepc is changed first.
  • mtvec is 0 after reset. Write it before anything can fault.

Practice

Report a problem with this page