Causes of a Trap and the Precise Trap in the Pipeline

A pipeline holds five instructions at once. One of them faults. Which ones still finish, which ones vanish, and how does the handler learn what went wrong?

You Will Be Able To

  • Read the cause of an exception from mcause, and the detail from mtval.
  • Say what ecall and ebreak are for, and where their handler returns to.
  • Explain what makes a trap precise, and count what it costs in the five-stage pipeline.
Lesson
S2.29
Time
35 min
Runs on
Your browser
Check
6 questions

S2.13 showed one fault and one handler. A real program can fail in many ways, and it fails in the middle of a pipeline.

Before You Start

You need the trap from S2.13: the entry, mepc, mcause, mtval and mret.

You need the flush and the pipeline grid from S2.10.

Five questions this page answers
Question
1Which number does mcause hold for an illegal instruction, and which for an ecall?
2What does mtval hold for a load at a bad address?
3What are ecall and ebreak for?
4In which stage does ap_rv32 take a trap, and what happens to the instructions behind it?
5How many cycles does a trap cost on ap_rv32?

The Idea: Many Causes, One Exact Place

An instruction can fail in several ways. The word may be no instruction. A load may use an address with no memory. A jump may go to half an instruction.

Each way has its own number in mcause. And mtval holds the detail that the handler will want: the bad word, or the bad address.

Two instructions fail on purpose. One is named ecall: it asks the handler for a service. The other is named ebreak: it stops the program at a chosen place, for a person who wants to look. Neither is an error.

Now the pipeline. When an instruction faults, older instructions are still finishing, and younger ones are already fetched.

The handler must find a clean state. Every instruction before the fault has run completely. The faulting one and all after it have changed nothing.

A trap that keeps this promise is a precise trap. To the handler, it looks as if instructions ran one at a time.

ap_rv32 keeps it with one rule. A trap is taken at one stage only, MEM. That stage is the commit point.

New Words

New words on this page
WordMeaning
ecallEnvironment call: an instruction that traps on purpose, to ask the handler for a service.
DebuggerA tool with which a person stops a program and looks at its registers and memory.
BreakpointA place where a program shall stop, so that a person can look at it.
ebreakAn instruction that traps on purpose, to stop at this place. It is used for a breakpoint.
MisalignedAn address that is not a multiple of the size of the thing at it: 4 for a word or an instruction.
Bus access faultA trap because the memory or the bus refused the address. Short: an access fault.
Precise trapA trap after which every older instruction has finished, and no younger one has changed anything.
Commit pointThe stage after which an instruction can no longer be thrown away. In ap_rv32: MEM.

One Picture: The Fault Travels as a Mark

One Fault Travels to MEM, and Three Instructions Die Behind ItStep through the picture. It follows the faulty word at address 0c through the real pipeline, cycle by cycle.
  • Memory
  • Control / FSM
  • Processor
  • Bus
One Fault Travels to MEM, and Three Instructions Die Behind ItStep through the picture. It follows the faulty word at address 0c through the real pipeline, cycle by cycle. component IF fetch component ID decode: finds theillegal word component EX execute component MEM the commit point component WB write back component Trap CSRs mepc, mcause, mtval,mstatus component PC takes the handleraddress IF/IDID/EX, with a mark:illegalEX/MEM, the marktravelsMEM/WBmepc = 0c, mcause = 2flush IF, ID and EXthe PC takes mtvec:40
  1. component IDdecode: finds the illegal word
    • ID/EX, with a mark: illegal → EX
  2. component EXexecute
    • EX/MEM, the mark travels → MEM
  3. component IFfetch
    • IF/ID → ID
  4. component MEMthe commit point
    • MEM/WB → WB
    • mepc = 0c, mcause = 2 → Trap CSRs
    • flush IF, ID and EX → ID
  5. component WBwrite back
  6. component Trap CSRsmepc, mcause, mtval, mstatus
    • the PC takes mtvec: 40 → PC
  7. component PCtakes the handler address
  1. Cycle 8: found in ID

    The word at 0c is in ID. The decoder says: no instruction. Nothing happens yet. The word gets a mark and moves on.

  2. Cycle 9: in EX

    The marked word is in EX. Behind it, the instructions at 10 and 14 are in ID and IF. The instruction at 08 is ahead, in MEM.

  3. Cycle 10: in MEM, the trap is taken

    The marked word is the oldest that has not finished. Now the trap is taken. The instruction at 08, ahead of it, is in WB and completes.

  4. Cycle 10, at the clock edge

    The CSRs take their values. The instructions at 10, 14 and 18, in EX, ID and IF, become bubbles. The PC takes 40.

  5. Cycle 11: the handler is fetched

    IF holds 40, the first instruction of the handler. ID, EX and MEM hold bubbles: three cycles are lost.

Read the diagram as text
  • IF: fetch
  • ID: decode: finds the illegal word
  • EX: execute
  • MEM: the commit point
  • WB: write back
  • Trap CSRs: mepc, mcause, mtval, mstatus
  • PC: takes the handler address
  • IF → ID: IF/ID
  • ID → EX: ID/EX, with a mark: illegal
  • EX → MEM: EX/MEM, the mark travels
  • MEM → WB: MEM/WB
  • MEM → Trap CSRs: mepc = 0c, mcause = 2
  • MEM → ID: flush IF, ID and EX
  • Trap CSRs → PC: the PC takes mtvec: 40

The fault is found early and acted on late. In between it is only a mark that travels with the instruction.

The causes of exceptions in ap_rv32
mcauseNameRaised bymtval holds
0Instruction address misalignedA taken branch or a jump to an address with bit 1 setThe target address
1Instruction access faultA fetch that the bus refusesThe address of the instruction
2Illegal instructionA word that is no instruction, or a CSR instruction that is not allowedThe word
3BreakpointebreakThe address of the ebreak
4Load address misalignedA load of a word at an address that is not a multiple of 4The address of the data
5Load access faultA load that the bus refusesThe address of the data
6Store address misalignedA store, as for cause 4The address of the data
7Store access faultA store that the bus refusesThe address of the data
11Environment callecall0

The numbers are those of RISC-V, not checked against its specification. Half words follow the same rule with a multiple of 2.

The Smallest Example, Worked by Hand

A program with ten instructions that trap
Address, in hexInstructionWhat it is for
000addi x5, x0, 128
004csrw mtvec, x5
008lui x20, 0x80000x20: the list, at 8000_0000
00clui x8, 0x80001x8: data, at 8000_1000
010lui x9, 0x40000x9: an address with no memory
014ecalla call for the handler
018ebreaka breakpoint
01c.word 0xffffffffnot an instruction
020csrr x11, 0x123a CSR that does not exist
024csrw mhartid, x11a write to a read-only CSR
028lw x11, 2(x8)a word at an address that is not a multiple of 4
02csw x11, 1(x8)the same for a store
030lw x11, 0(x9)a load where no memory is
034sw x11, 0(x9)a store where no memory is
038jalr x1, 2(x9)a jump to an address that is not a multiple of 4
03cjal x0, 0x3cstop

x8 points into data memory, at 8000_1000. x9 holds 4000_0000, where no memory is. The handler, at 80, is below.

Take the load at 28: lw x11, 2(x8). Its address is 8000_1000 plus 2. A word must start at a multiple of 4.

So it traps. Find the row in the table: load address misaligned, cause 4. mtval takes the address, 8000_1002.

Now the load at 30: lw x11, 0(x9). The address 4000_0000 is a multiple of 4. But no memory answers there.

The bus refuses the read. That is cause 5, a load access fault. mtval takes 4000_0000.

And the row at 20: csrr x11, 0x123. No CSR has this address. The word is treated as no instruction: cause 2, and mtval takes the word.

Predict before you run
AddressInstructionmcausemtval
14ecall110
18ebreak30000_0018
28lw x11, 2(x8)48000_1002
30lw x11, 0(x9)54000_0000
38jalr x1, 2(x9)04000_0002

The jump at 38 traps itself, before anything is fetched from the bad target. mepc is 38.

The Rules

  1. Rule 1: mcause names the kind of fault, and mtval gives its detail.

    An address for a fault about an address. The word for an illegal instruction.

  2. Rule 2: ecall and ebreak trap every time, and mepc points at them.

    A handler that serves an ecall returns behind it: mepc plus 4.

  3. Rule 3: A fault is found where it happens, and acted on in MEM.

    An illegal word is found in ID, a bad data address in EX, a refused access in MEM. Until MEM it is a mark.

  4. Rule 4: At the trap, every older instruction finishes.

    The instruction in WB completes. It was before the fault in program order.

  5. Rule 5: At the trap, the three younger instructions are flushed.

    Those in EX, ID and IF become bubbles. The trapping instruction itself writes no register and no memory word.

  6. Rule 6: The oldest fault wins.

    Each fault waits for MEM, so the instruction that comes first in the program traps first.

  7. Rule 7: A trap costs 3 cycles on ap_rv32.

    Three fetched instructions are lost. An mret and a CSR instruction also leave from MEM, and cost 3 each.

Sources for These Rules

Checked in the library: Patterson and Hennessy, Computer Organization and Design (ARM edition), section 4.9. It treats an exception in a pipeline as a control hazard, flushes the instructions behind it, and lets the earliest instruction win. Its pipeline acts in another stage than ours. The cause numbers, the names ecall and ebreak and the contents of mtval come from the RISC-V privileged specification. That document is not in our library: they are not checked against it. For ap_rv32 they are in docs/soc/ap_rv32-blueprint.md, sections 7.1 and 7.2, and its mtval values are a choice of this core. Every pipeline row on this page is recorded from the real core.

Now Run It

The lab at the end of this page runs the program above. Its handler writes each cause to a list, and returns behind the instruction.

The ten rows with a trap and the last two lines of the lab. The lab prints 86 lines. The real core ap_rv32 gave the same 85 trace records.
00000014 | ecall | TRAP mcause=11 mepc=00000014 mtval=00000000, next is 00000080
00000018 | ebreak | TRAP mcause=3 mepc=00000018 mtval=00000018, next is 00000080
0000001c | .word 0xffffffff | TRAP mcause=2 mepc=0000001c mtval=ffffffff, next is 00000080
00000020 | csrr x11, 0x123 | TRAP mcause=2 mepc=00000020 mtval=123025f3, next is 00000080
00000024 | csrw mhartid, x11 | TRAP mcause=2 mepc=00000024 mtval=f1459073, next is 00000080
00000028 | lw x11, 2(x8) | TRAP mcause=4 mepc=00000028 mtval=80001002, next is 00000080
0000002c | sw x11, 1(x8) | TRAP mcause=6 mepc=0000002c mtval=80001001, next is 00000080
00000030 | lw x11, 0(x9) | TRAP mcause=5 mepc=00000030 mtval=40000000, next is 00000080
00000034 | sw x11, 0(x9) | TRAP mcause=7 mepc=00000034 mtval=40000000, next is 00000080
00000038 | jalr x1, 2(x9) | TRAP mcause=0 mepc=00000038 mtval=40000002, next is 00000080
the list: 11 3 2 2 2 4 6 5 7 0
instructions=75 traps=10

Rule 1 at work: compare the rows with your table. The store at 2c has cause 6 and its address in mtval. The word at 1c has cause 2 and the word in mtval.

The two rows at 20 and 24 are CSR instructions that are not allowed. One names a CSR that does not exist. The other writes a read-only one.

Rule 2 at work: the ecall and the ebreak trap like any fault. The last line shows 75 instructions and 10 traps.

Now the pipeline. These rows are not from the lab. They are the stages of the real core ap_rv32, for the program of S2.13.

Recorded from the pipeline view of the real core. Each row is one clock cycle. The faulty word is at 0c, and the handler at 40.
cy | IF  ID  EX  MEM  WB | what happens
 7 | 0c  08  --  --   -- |
 8 | 10  0c  08  --   -- |
 9 | 14  10  0c  08   -- |
10 | 18  14  10  0c   08 | x10=1 MEM: go 40
11 | 40  --  --  --   0c | trap 2
12 | 44  40  --  --   -- |
13 | 48  44  40  --   -- |
14 | 4c  48  44  40   -- | MEM: go 44
15 | 44  --  --  --   40 | x6=2

Rule 3 at work: the word at 0c is in ID in row 8 and in EX in row 9. No note marks it. In row 10 it is in MEM: go 40.

Rule 4 at work: in row 10 the instruction at 08 is in WB. It writes x10 = 1. It was older than the fault.

Rule 5 at work: row 11 has three pairs of dashes. The instructions at 10, 14 and 18 are gone. IF holds 40.

Row 14 shows go 44. The instruction at 40 is a CSR read. On this core every CSR instruction leaves from MEM and fetches again behind itself.

Rule 7 at work: the whole run has 11 trace records and 6 such exits from MEM. It takes 33 cycles: 11 plus 4 plus 18.

Now two faults next to each other. A load at 14 uses an address with no memory. Right behind it, at 18, is a word that is no instruction.

Recorded from the real core. The load is refused by the bus in MEM. The illegal word was found two cycles earlier, in ID.
cy | IF  ID  EX  MEM  WB | what happens
10 | 18  14  10  0c   08 | x20=80000000
11 | 1c  18  14  10   0c | x9=40000000
12 | 20  1c  18  14   10 | x10=1 wait
13 | 20  1c  18  14   10 | MEM: go 80
14 | 80  --  --  --   14 | trap 5
15 | 84  80  --  --   -- |

Rule 6 at work: in row 11 the illegal word is in ID, and found. In row 12 the load is in MEM, and the bus answers with an error. The note says wait.

In row 13 the load traps: cause 5. The illegal word, in EX, is flushed with the rest. It was found first, and it does not win.

The handler returns behind the load. Then the word at 18 is fetched again and traps for itself. The list of this run is 5, then 2.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Act on every fault in one stageAct where the fault is foundFaults are served in program order with no sorting logic. A fault found in ID waits two cycles.
That stage is MEMWB, one stage laterA store writes memory in MEM, so the decision must fall there. One instruction less is flushed.
Flush everything youngerLet fetched instructions finishThe handler sees a clean state. Three fetches are lost.
A number for each causeOne "fault" for allThe handler branches on mcause at once. The numbers are fixed for every RISC-V core.
mtval holds the address or the wordThe handler decodes the instruction at mepcNo decoder in software. One more CSR to write at the entry.
ecall is a trapA jump instruction into the handlerOne mechanism for every way in. The cost of a trap for every service call.

Why must a store wait for the decision? A register write can be held back until WB. A word written to memory, or to a device, cannot be taken back.

The real core shows it. A store right behind a faulty word had not happened when the handler looked. A store right before it had.

The Trap: Returning to an Ecall as If It Were an Interrupt

After an interrupt, a handler returns to mepc as it is. The interrupted instruction never ran, and now it must.

An ecall is different. It did its work by trapping. Returning to it runs it again.

A handler that counts and returns, with no change of mepc. The lab stops the run after 14 steps. The real core gave the same records.
00000000 | addi x5, x0, 128 | x5 = 00000080
00000004 | csrw mtvec, x5 | mtvec = 00000080
00000008 | addi x10, x0, 7 | x10 = 00000007
0000000c | ecall | TRAP mcause=11 mepc=0000000c mtval=00000000, next is 00000080
00000080 | addi x11, x11, 1 | x11 = 00000001
00000084 | mret | next is 0000000c, MIE=0
0000000c | ecall | TRAP mcause=11 mepc=0000000c mtval=00000000, next is 00000080
00000080 | addi x11, x11, 1 | x11 = 00000002
00000084 | mret | next is 0000000c, MIE=0
0000000c | ecall | TRAP mcause=11 mepc=0000000c mtval=00000000, next is 00000080
00000080 | addi x11, x11, 1 | x11 = 00000003
00000084 | mret | next is 0000000c, MIE=0
0000000c | ecall | TRAP mcause=11 mepc=0000000c mtval=00000000, next is 00000080
00000080 | addi x11, x11, 1 | x11 = 00000004
still running after 10 instructions and 4 traps
x10=7 x11=4 instructions=10 traps=4

Read it. Each mret says "next is 0000000c", and the row after it is the ecall again. x11 counts 4 calls. The program made one.

So a handler must look at mcause first. Bit 31 tells it: an interrupt returns to mepc, an ecall to mepc plus 4.

At Scale

ap_rv325 stages: a trap flushes 3 instructions
A wide out-of-order corehundreds of instructions in flight at one time

This section looks ahead. Three flushed instructions are a small price. Larger cores pay more, and need more machinery to stay precise.

  1. Interrupts enter the same way

    An interrupt is attached to an instruction in the pipeline and waits for MEM like a fault. S6.15 measures the delay.

  2. Cores that reorder

    Some cores execute instructions in another order than the program has. They need a buffer that puts results back in order. S2.32 builds one.

  3. A debugger uses ebreak

    To stop a program at a place, a debugger writes an ebreak over the instruction there. That is common practice.

  4. A verification team needs this table

    Each cause, with its mepc and mtval, is a row of a test plan. The real core reports all three for every trap, on a port that S2.16 shows.

Try It

Run the lab. Find the ten rows that are marked as a trap, and compare each with the table of causes.

Change the row at 28 to i(LW, 11, 8, 4). Which cause disappears from the list?

Change the row at 38 to i(JALR, 1, 9, 0). The jump is now legal. Which cause does the list end with, and what is mepc?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: 00000000 | addi x5, x0, 128 | x5 = 00000080 00000004 | csrw mtvec, x5 | mtvec = 00000080 00000008 | lui x20, 0x80000 | x20 = 80000000 0000000c | lui x8, 0x80001 | x8 = 80001000 00000010 | lui x9, 0x40000 | x9 = 40000000 00000014 | ecall | TRAP mcause=11 mepc=00000014 mtval=00000000, next is 00000080 00000080 | csrr x6, mcause | x6 = 0000000b 00000084 | sw x6, 0(x20) | mem[80000000] = 0000000b 00000088 | addi x20, x20, 4 | x20 = 80000004 0000008c | csrr x7, mepc | x7 = 00000014 00000090 | addi x7, x7, 4 | x7 = 00000018 00000094 | csrw mepc, x7 | mepc = 00000018 00000098 | mret | next is 00000018, MIE=0 00000018 | ebreak | TRAP mcause=3 mepc=00000018 mtval=00000018, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000003 00000084 | sw x6, 0(x20) | mem[80000004] = 00000003 00000088 | addi x20, x20, 4 | x20 = 80000008 0000008c | csrr x7, mepc | x7 = 00000018 00000090 | addi x7, x7, 4 | x7 = 0000001c 00000094 | csrw mepc, x7 | mepc = 0000001c 00000098 | mret | next is 0000001c, MIE=0 0000001c | .word 0xffffffff | TRAP mcause=2 mepc=0000001c mtval=ffffffff, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000002 00000084 | sw x6, 0(x20) | mem[80000008] = 00000002 00000088 | addi x20, x20, 4 | x20 = 8000000c 0000008c | csrr x7, mepc | x7 = 0000001c 00000090 | addi x7, x7, 4 | x7 = 00000020 00000094 | csrw mepc, x7 | mepc = 00000020 00000098 | mret | next is 00000020, MIE=0 00000020 | csrr x11, 0x123 | TRAP mcause=2 mepc=00000020 mtval=123025f3, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000002 00000084 | sw x6, 0(x20) | mem[8000000c] = 00000002 00000088 | addi x20, x20, 4 | x20 = 80000010 0000008c | csrr x7, mepc | x7 = 00000020 00000090 | addi x7, x7, 4 | x7 = 00000024 00000094 | csrw mepc, x7 | mepc = 00000024 00000098 | mret | next is 00000024, MIE=0 00000024 | csrw mhartid, x11 | TRAP mcause=2 mepc=00000024 mtval=f1459073, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000002 00000084 | sw x6, 0(x20) | mem[80000010] = 00000002 00000088 | addi x20, x20, 4 | x20 = 80000014 0000008c | csrr x7, mepc | x7 = 00000024 00000090 | addi x7, x7, 4 | x7 = 00000028 00000094 | csrw mepc, x7 | mepc = 00000028 00000098 | mret | next is 00000028, MIE=0 00000028 | lw x11, 2(x8) | TRAP mcause=4 mepc=00000028 mtval=80001002, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000004 00000084 | sw x6, 0(x20) | mem[80000014] = 00000004 00000088 | addi x20, x20, 4 | x20 = 80000018 0000008c | csrr x7, mepc | x7 = 00000028 00000090 | addi x7, x7, 4 | x7 = 0000002c 00000094 | csrw mepc, x7 | mepc = 0000002c 00000098 | mret | next is 0000002c, MIE=0 0000002c | sw x11, 1(x8) | TRAP mcause=6 mepc=0000002c mtval=80001001, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000006 00000084 | sw x6, 0(x20) | mem[80000018] = 00000006 00000088 | addi x20, x20, 4 | x20 = 8000001c 0000008c | csrr x7, mepc | x7 = 0000002c 00000090 | addi x7, x7, 4 | x7 = 00000030 00000094 | csrw mepc, x7 | mepc = 00000030 00000098 | mret | next is 00000030, MIE=0 00000030 | lw x11, 0(x9) | TRAP mcause=5 mepc=00000030 mtval=40000000, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000005 00000084 | sw x6, 0(x20) | mem[8000001c] = 00000005 00000088 | addi x20, x20, 4 | x20 = 80000020 0000008c | csrr x7, mepc | x7 = 00000030 00000090 | addi x7, x7, 4 | x7 = 00000034 00000094 | csrw mepc, x7 | mepc = 00000034 00000098 | mret | next is 00000034, MIE=0 00000034 | sw x11, 0(x9) | TRAP mcause=7 mepc=00000034 mtval=40000000, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000007 00000084 | sw x6, 0(x20) | mem[80000020] = 00000007 00000088 | addi x20, x20, 4 | x20 = 80000024 0000008c | csrr x7, mepc | x7 = 00000034 00000090 | addi x7, x7, 4 | x7 = 00000038 00000094 | csrw mepc, x7 | mepc = 00000038 00000098 | mret | next is 00000038, MIE=0 00000038 | jalr x1, 2(x9) | TRAP mcause=0 mepc=00000038 mtval=40000002, next is 00000080 00000080 | csrr x6, mcause | x6 = 00000000 00000084 | sw x6, 0(x20) | mem[80000024] = 00000000 00000088 | addi x20, x20, 4 | x20 = 80000028 0000008c | csrr x7, mepc | x7 = 00000038 00000090 | addi x7, x7, 4 | x7 = 0000003c 00000094 | csrw mepc, x7 | mepc = 0000003c 00000098 | mret | next is 0000003c, MIE=0 0000003c | jal x0, 0x3c | the program stops here the list: 11 3 2 2 2 4 6 5 7 0 instructions=75 traps=10

Check Yourself

Predict the outputThe program has a store at 8000_1003, a load at 8000_1004, an ebreak and a write to mhartid. The handler lists the cause of each trap. What does the last line say?
// Three instructions that trap. What is the list at the end?
// 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,  128);       // 000: addi x5, x0, 128
    i(CSRW,   5,  0,  MTVEC);     // 004: csrw mtvec, x5
    i(LUI,    20, 0,  'h80000);   // 008: lui x20, 0x80000
    i(LUI,    8,  0,  'h80001);   // 00c: lui x8, 0x80001
    i(SW,     8,  8,  3);         // 010: sw x8, 3(x8)
    i(LW,     11, 8,  4);         // 014: lw x11, 4(x8)
    i(EBREAK, 0,  0,  0);         // 018: ebreak
    i(CSRW,   11, 0,  MHARTID);   // 01c: csrw mhartid, x11
    i(JAL,    0,  0,  'h20);      // 020: jal x0, 0x20
    at('h80);
    i(CSRR,   6,  0,  MCAUSE);    // 080: csrr x6, mcause      the handler: the cause
    i(SW,     6,  20, 0);         // 084: sw x6, 0(x20)      write it to the list
    i(ADDI,   20, 20, 4);         // 088: addi x20, x20, 4
    i(CSRR,   7,  0,  MEPC);      // 08c: csrr x7, mepc
    i(ADDI,   7,  7,  4);         // 090: addi x7, x7, 4
    i(CSRW,   7,  0,  MEPC);      // 094: csrw mepc, x7
    i(MRET,   0,  0,  0);         // 098: 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);
    $write("the list:");  for (int n = 0; n < traps; n++) $write(" %0d", mem[n]);  $display("");
  end
endmodule
ConceptWhich number does mcause hold for an illegal instruction, and which for an ecall on ap_rv32?
ConceptWhat does mtval hold after a load at an address that the bus refuses?
ConceptWhat is ecall for?
ConceptIn which stage does ap_rv32 take a trap, and what happens behind it?
ConceptA program takes one trap, and its handler is four ordinary instructions and an mret. How many cycles do the trap and the mret cost together?

Common Mistakes

Wrong Return to mepc unchanged after an ecall.

mepc points at the ecall. It traps again, for ever.

Fix Add 4 to mepc for an ecall. Leave it for an interrupt.

Wrong Expect the fault that is found first to trap first.

An illegal word is found in ID, two cycles before an older load is refused in MEM.

Fix The oldest instruction traps first: faults are acted on in MEM, in program order.

Wrong Read mtval as an address for every cause.

For an illegal instruction it is the word, and for an ecall it is 0.

Fix Read mcause first. It says what mtval means.

Remember

  • mcause names the fault. mtval holds its detail: an address, or the illegal word.
  • ecall and ebreak trap on purpose. An ecall handler returns to mepc plus 4.
  • A fault travels as a mark and is acted on in MEM. Older instructions finish, and three younger ones are flushed.
  • The oldest fault wins. A trap, an mret and a CSR instruction each cost 3 cycles on ap_rv32.

Practice

Report a problem with this page