Entering User Mode and Coming Back: Mret, Ecall and the System Call

User code can do little by itself. It cannot even reach the timer. So it must be able to ask trusted code for help. And trusted code must be able to send it back to work.

You Will Be Able To

  • Say what the field MPP holds, and what mret does with it.
  • Write the three steps that start an application at user level.
  • Follow a system call from the ecall to the return, and say where the answer travels.
Lesson
S2.30
Time
35 min
Runs on
Your browser
Check
6 questions

S2.14 showed the wall between the levels. A wall with no door is useless. This page is about the two doors.

Before You Start

You need the two levels from S2.14, and what user code cannot do.

You need the entry of a trap and mret from S2.13, and ecall from S2.29.

Five questions this page answers
Question
1What does the field MPP of mstatus hold?
2Which three steps start an application at user level?
3Which cause does an ecall at user level have?
4How does a system call hand over its value, and get its answer?
5What does delegation of a trap mean?

The Idea: Mret Goes Down, a Trap Comes Up

The processor has no instruction that says "go to user level". It needs none. It has mret.

At a trap the processor notes the level it came from. The note is a field of two bits in mstatus, called MPP.

mret reads the note back. It returns to the address in mepc, and to the level in MPP.

Now the trick. Both notes are CSRs, and machine code can write them. It writes "user" into MPP and an address into mepc.

Then it runs mret. The processor returns to a place that never called: the start of the application, at user level.

The way back up is a trap. The application runs an ecall. It lands in the handler, at machine level.

An ecall that asks trusted code for a service is a system call. The application says which service, by a number in a register.

A full system has a supervisor level too. There, machine code can pass chosen traps on to the supervisor. That is delegation.

New Words

New words on this page
WordMeaning
MPPMachine previous privilege: bits 12 and 11 of mstatus. The level the processor was at before the trap.
System callA request from an application to trusted code, made with an ecall.
Service numberThe number that says which service a system call wants. In this lab it is in x17.
DelegationMachine code lets a kind of trap go straight to the handler of the supervisor level.
csrcThe instruction that clears bits of a CSR: every bit that is 1 in the register becomes 0 in the CSR.

The values of MPP are the level numbers: 11 for machine and 00 for user.

One Picture: The Two Doors in Use

One Field Opens the Door Down, One Instruction the Door UpStep through the picture. It follows the level through one system call.
  • Processor
  • Memory
  • Control / FSM
  • Peripheral
One Field Opens the Door Down, One Instruction the Door UpStep through the picture. It follows the level through one system call. component Start-up code machine level component MPP two bits of mstatus:the level to return to component mepc the address toreturn to component Handler machine level: servesthe call component Application user level: value inx10, service numberin x17 1: MPP = 002: mepc = 403: mret: level and PC4: ecall: cause 85: mepc plus 46: mret, back down
  1. component Start-up codemachine level
    • 1: MPP = 00 → MPP
    • 2: mepc = 40 → mepc
  2. component MPPtwo bits of mstatus: the level to return to
    • 3: mret: level and PC → Application
  3. component mepcthe address to return to
    • 6: mret, back down → Application
  4. component Applicationuser level: value in x10, service number in x17
    • 4: ecall: cause 8 → Handler
  5. component Handlermachine level: serves the call
    • 5: mepc plus 4 → mepc
  1. Prepare the door down

    The start-up code writes 00 into MPP: user. It writes the first address of the application into mepc.

  2. mret

    mret loads the level from MPP and the PC from mepc, in one step. The application runs, at user level.

  3. The application asks

    It puts a value into x10 and a service number into x17. Then it runs an ecall.

  4. The door up

    The ecall traps with cause 8. The level becomes machine. MPP takes 00 and mepc the address of the ecall.

  5. Serve, and return

    The handler does the work and leaves the answer in x10. It adds 4 to mepc. Its mret goes back down.

Read the diagram as text
  • Start-up code: machine level
  • MPP: two bits of mstatus: the level to return to
  • mepc: the address to return to
  • Handler: machine level: serves the call
  • Application: user level: value in x10, service number in x17
  • Start-up code → MPP: 1: MPP = 00
  • Start-up code → mepc: 2: mepc = 40
  • MPP → Application: 3: mret: level and PC
  • Application → Handler: 4: ecall: cause 8
  • Handler → mepc: 5: mepc plus 4
  • mepc → Application: 6: mret, back down

Going down is a return to a place that never called. Coming up is a trap that the application asked for.

What a trap and an mret do to the level
EventThe levelMPPThe PC
A trap, from any levelbecomes machinetakes the level before the traptakes the handler address
mrettakes MPPbecomes 00, the lowest leveltakes mepc

These two rows are added to the entry and the return of S2.13. Not checked against the specification.

The Smallest Example, Worked by Hand

Start-up code and an application
Address, in hexInstructionWhat it is for
000addi x5, x0, 128machine level: the handler address
004csrw mtvec, x5
008addi x5, x0, 64where the user code starts
00ccsrw mepc, x5
010lui x5, 0x2bits 12 and 11: the field MPP
014addi x5, x5, -2048
018csrc mstatus, x5MPP = 00: user
01cmretgo down to the user code
040addi x10, x0, 21user code: the value
044addi x17, x0, 1the service number
048ecallask the machine level
04caddi x11, x10, 0the answer came back in x10
050addi x17, x0, 0service 0 does not exist
054ecall
058addi x11, x0, -1never reached

The start-up code is at 00 to 1c. The application starts at 40. The handler is at 80 and is shown in the lab.

After reset the level is machine, and mstatus holds 0000_1800. Bits 12 and 11 are 11: MPP says machine.

The rows at 10 and 14 build the value 0000_1800 in x5. The csrc at 18 clears those two bits. MPP now says user.

The level, MPP and mepc, step by step
After the row atLevelMPPmepcWhat happened
0cM1140mepc is written
18M0040MPP is cleared
1cU0040mret: the application starts at 40
48M0048ecall: a trap from user level
a4U004cmret: back behind the ecall

Before the row at a4, the handler has added 4 to mepc.

At 48 the application has 21 in x10 and 1 in x17. The ecall traps. The handler sees cause 8 and service 1.

Service 1 doubles x10. The handler leaves 42 there. It touches no other register that the application uses.

The Rules

  1. Rule 1: At a trap, MPP takes the level before the trap, and the level becomes machine.

    So the handler can tell where the trap came from.

  2. Rule 2: mret sets the level from MPP and the PC from mepc.

    After it, MPP holds 00. A second mret without a trap would go to user level.

  3. Rule 3: To start an application: write mepc, clear MPP, run mret.

    Three steps of machine code. The order of the first two does not matter.

  4. Rule 4: An ecall at user level has cause 8. At machine level it has cause 11.

    The handler tells a system call from its own ecalls by the cause.

  5. Rule 5: A system call passes a service number and a value in registers, and gets its answer in a register.

    Here: x17 for the number, x10 for the value and the answer. That is a choice of the software.

  6. Rule 6: The handler of a system call returns to mepc plus 4.

    MPP still says user, so its mret goes back down by itself.

Sources for These Rules

The field MPP, what mret does with it, cause 8 for an ecall at user level and the delegation of traps come from the RISC-V privileged specification. That document is not in our library: none of it is checked against it. The real core ap_rv32 v1.0 has machine level only. Its MPP always reads 11 (docs/soc/ap_rv32-blueprint.md, section 5.1), and its ecall has cause 11 (section 7.1), as S2.13 and S2.29 showed on the real core. Every row on this page is printed by the lab, which is a model. The registers x17 and x10 for a system call are the choice of this lab. They follow common practice for RISC-V. Checked in the library: Patterson and Hennessy, Computer Organization and Design (ARM edition), section 4.9, names the call of the operating system from a user program as one kind of exception.

Now Run It

The lab at the end of this page runs the program above on the model. Each row starts with the level: M or U.

Printed by the lab on Icarus. This run is the model alone: the real core ap_rv32 v1.0 has no user level.
M 00000000 | addi x5, x0, 128 | x5 = 00000080
M 00000004 | csrw mtvec, x5 | mtvec = 00000080
M 00000008 | addi x5, x0, 64 | x5 = 00000040
M 0000000c | csrw mepc, x5 | mepc = 00000040
M 00000010 | lui x5, 0x2 | x5 = 00002000
M 00000014 | addi x5, x5, -2048 | x5 = 00001800
M 00000018 | csrc mstatus, x5 | mstatus = 00000000
M 0000001c | mret | next is 00000040, MIE=0, level U
U 00000040 | addi x10, x0, 21 | x10 = 00000015
U 00000044 | addi x17, x0, 1 | x17 = 00000001
U 00000048 | ecall | TRAP mcause=8 mepc=00000048 mtval=00000000, next is 00000080
M 00000080 | csrr x5, mcause | x5 = 00000008
M 00000084 | addi x6, x0, 8 | x6 = 00000008
M 00000088 | bne x5, x6, 0xa8 | not taken
M 0000008c | addi x6, x0, 1 | x6 = 00000001
M 00000090 | bne x17, x6, 0xa8 | not taken
M 00000094 | add x10, x10, x10 | x10 = 0000002a
M 00000098 | csrr x5, mepc | x5 = 00000048
M 0000009c | addi x5, x5, 4 | x5 = 0000004c
M 000000a0 | csrw mepc, x5 | mepc = 0000004c
M 000000a4 | mret | next is 0000004c, MIE=0, level U
U 0000004c | addi x11, x10, 0 | x11 = 0000002a
U 00000050 | addi x17, x0, 0 | x17 = 00000000
U 00000054 | ecall | TRAP mcause=8 mepc=00000054 mtval=00000000, next is 00000080
M 00000080 | csrr x5, mcause | x5 = 00000008
M 00000084 | addi x6, x0, 8 | x6 = 00000008
M 00000088 | bne x5, x6, 0xa8 | not taken
M 0000008c | addi x6, x0, 1 | x6 = 00000001
M 00000090 | bne x17, x6, 0xa8 | taken: next is 000000a8
M 000000a8 | jal x0, 0xa8 | the program stops here
x10=42 x11=42 mcause=8 level=3 mstatus=00000000 instructions=27 traps=2

Rule 3 at work: the rows at 0c, 18 and 1c. mepc takes 40. mstatus goes from 1800 to 0. The mret says "level U".

Rule 4 at work: the row at 48 starts with U and is marked as a trap, with mcause=8. The next row starts with M: the handler.

The handler first checks the cause, at 80 to 88. Then the service number, at 8c and 90. Then it doubles x10, at 94.

Rule 6 at work: the rows at 98 to a4. There mepc goes from 48 to 4c, and the mret says "level U" again.

Rule 5 at work: the row at 4c, back at user level, copies the answer. x11 is 2a in hex: 42.

The second ecall asks for service 0. The handler knows no such service. It jumps to a8 and ends the application there.

The last line: the level is 3, machine. mstatus is 0: MPP holds 00, because the last trap came from user level.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
Go down with mretA second instruction "enter user level"One mechanism for the first entry and for every return. The first entry looks like a return.
Come up only by a trapA call instruction into trusted codeUser code cannot choose where it enters. Every service pays the price of a trap.
The service number in a registerA different trap for each serviceOne cause and one entry. The handler must check the number.
MPP is written by the trapThe handler works out the levelThe return is right without any work. One field more in mstatus.
Delegation is a choice of machine codeEvery trap goes to machine level firstA system call reaches the supervisor at once. One more CSR to set up.

The handler must not trust the application. A service number may be wrong, and a value may be an address the application should not use.

On a chip with a supervisor level, most traps are meant for the operating system. Machine code lists those causes in a CSR.

A listed trap then skips the machine handler. It uses supervisor CSRs with the same roles: an address, a saved PC, a cause.

The Trap: The Level Is Lowered, and the Address Is Forgotten

The start-up code needs three steps. Suppose it clears MPP and runs mret, and never writes mepc.

Start-up code without the write to mepc. The model alone.
M 00000000 | addi x5, x0, 128 | x5 = 00000080
M 00000004 | csrw mtvec, x5 | mtvec = 00000080
M 00000008 | lui x5, 0x2 | x5 = 00002000
M 0000000c | addi x5, x5, -2048 | x5 = 00001800
M 00000010 | csrc mstatus, x5 | mstatus = 00000000
M 00000014 | mret | next is 00000000, MIE=0, level U
U 00000000 | addi x5, x0, 128 | x5 = 00000080
U 00000004 | csrw mtvec, x5 | TRAP mcause=2 mepc=00000004 mtval=30529073, next is 00000080
M 00000080 | csrr x5, mcause | x5 = 00000002
M 00000084 | addi x6, x0, 8 | x6 = 00000008
M 00000088 | bne x5, x6, 0xa8 | taken: next is 000000a8
M 000000a8 | jal x0, 0xa8 | the program stops here
x10=0 x11=0 mcause=2 level=3 mstatus=00000000 instructions=10 traps=1

After reset mepc holds 0. The mret goes there, at user level. The row after it starts with U and has the address 00000000.

So the start-up code runs a second time, now as user code. Its second row writes mtvec. That is refused: cause 2.

The handler sees a cause that is not 8 and ends the "application". The real application at 40 never ran.

The protection worked, and the system is still dead. Lowering the level and choosing the address belong together.

At Scale

This lab1 application, 1 service
A full operating systemhundreds of services, thousands of applications

This section looks ahead. One service and one application are the smallest case. An operating system is the large one.

  1. Every file and every message

    An application reads a file or sends data with a system call. Each one is a trap up and an mret, or its supervisor twin, down. That is common practice.

  2. The handler saves registers

    The handler here uses x5 and x6 without saving them. A real one saves all it uses, on a stack of its own that user code cannot reach.

  3. Arguments are checked

    A service that takes an address must check it against the regions of the application. S3.10 has the regions.

  4. On ap_rv32 today

    Version 1.0 runs everything at machine level. Its software calls functions directly. User level is planned for a later version.

Try It

Run the lab. Find the two rows with an ecall, and the row where the level changes back to U.

Change the first row of the application to i(ADDI, 10, 0, 50). What does the last line show for x10 and x11?

Remove the row with CSRC. The application now runs at machine level. Which cause does its ecall have, and what does the handler do with it?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: M 00000000 | addi x5, x0, 128 | x5 = 00000080 M 00000004 | csrw mtvec, x5 | mtvec = 00000080 M 00000008 | addi x5, x0, 64 | x5 = 00000040 M 0000000c | csrw mepc, x5 | mepc = 00000040 M 00000010 | lui x5, 0x2 | x5 = 00002000 M 00000014 | addi x5, x5, -2048 | x5 = 00001800 M 00000018 | csrc mstatus, x5 | mstatus = 00000000 M 0000001c | mret | next is 00000040, MIE=0, level U U 00000040 | addi x10, x0, 21 | x10 = 00000015 U 00000044 | addi x17, x0, 1 | x17 = 00000001 U 00000048 | ecall | TRAP mcause=8 mepc=00000048 mtval=00000000, next is 00000080 M 00000080 | csrr x5, mcause | x5 = 00000008 M 00000084 | addi x6, x0, 8 | x6 = 00000008 M 00000088 | bne x5, x6, 0xa8 | not taken M 0000008c | addi x6, x0, 1 | x6 = 00000001 M 00000090 | bne x17, x6, 0xa8 | not taken M 00000094 | add x10, x10, x10 | x10 = 0000002a M 00000098 | csrr x5, mepc | x5 = 00000048 M 0000009c | addi x5, x5, 4 | x5 = 0000004c M 000000a0 | csrw mepc, x5 | mepc = 0000004c M 000000a4 | mret | next is 0000004c, MIE=0, level U U 0000004c | addi x11, x10, 0 | x11 = 0000002a U 00000050 | addi x17, x0, 0 | x17 = 00000000 U 00000054 | ecall | TRAP mcause=8 mepc=00000054 mtval=00000000, next is 00000080 M 00000080 | csrr x5, mcause | x5 = 00000008 M 00000084 | addi x6, x0, 8 | x6 = 00000008 M 00000088 | bne x5, x6, 0xa8 | not taken M 0000008c | addi x6, x0, 1 | x6 = 00000001 M 00000090 | bne x17, x6, 0xa8 | taken: next is 000000a8 M 000000a8 | jal x0, 0xa8 | the program stops here x10=42 x11=42 mcause=8 level=3 mstatus=00000000 instructions=27 traps=2

Check Yourself

Predict the outputThe application puts 3 into x10 and calls service 1 twice. Then it calls service 2, which does not exist. What does the last line say?
// Two calls of service 1, then one of a service that does not exist. 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,  128);       // 000: addi x5, x0, 128      machine level: the handler address
    i(CSRW,   5,  0,  MTVEC);     // 004: csrw mtvec, x5
    i(ADDI,   5,  0,  64);        // 008: addi x5, x0, 64      where the user code starts
    i(CSRW,   5,  0,  MEPC);      // 00c: csrw mepc, x5
    i(LUI,    5,  0,  'h2);       // 010: lui x5, 0x2      bits 12 and 11: the field MPP
    i(ADDI,   5,  5,  -2048);     // 014: addi x5, x5, -2048
    i(CSRC,   5,  0,  MSTATUS);   // 018: csrc mstatus, x5      MPP = 00: user
    i(MRET,   0,  0,  0);         // 01c: mret      go down to the user code
    at('h40);
    i(ADDI,   10, 0,  3);         // 040: addi x10, x0, 3
    i(ADDI,   17, 0,  1);         // 044: addi x17, x0, 1
    i(ECALL,  0,  0,  0);         // 048: ecall
    i(ECALL,  0,  0,  0);         // 04c: ecall
    i(ADDI,   17, 0,  2);         // 050: addi x17, x0, 2
    i(ECALL,  0,  0,  0);         // 054: ecall
    i(ADDI,   10, 0,  0);         // 058: addi x10, x0, 0
    at('h80);
    i(CSRR,   5,  0,  MCAUSE);    // 080: csrr x5, mcause      the handler: why?
    i(ADDI,   6,  0,  8);         // 084: addi x6, x0, 8      8: a call from user level
    i(BNE,    5,  6,  'ha8);      // 088: bne x5, x6, 0xa8      anything else: end the program
    i(ADDI,   6,  0,  1);         // 08c: addi x6, x0, 1
    i(BNE,    17, 6,  'ha8);      // 090: bne x17, x6, 0xa8      only service 1 exists
    i(ADD,    10, 10, 10);        // 094: add x10, x10, x10      service 1: double the value
    i(CSRR,   5,  0,  MEPC);      // 098: csrr x5, mepc
    i(ADDI,   5,  5,  4);         // 09c: addi x5, x5, 4      return behind the ecall
    i(CSRW,   5,  0,  MEPC);      // 0a0: csrw mepc, x5
    i(MRET,   0,  0,  0);         // 0a4: mret
    i(JAL,    0,  0,  'ha8);      // 0a8: jal x0, 0xa8      the user program has ended
  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. Its user level is not in ap_rv32 v1.0.
  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, 0 is user
  localparam bit USER = 1;           // 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 = (level == 3) ? "M " : "U ";
    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 = (level == 3) ? "M " : "U ";
    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, level %s", next, mstatus[3], (level == 3) ? "M" : "U");
        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 x11=%0d mcause=%0d level=%0d mstatus=%08h instructions=%0d traps=%0d", x[10], $signed(x[11]), mcause, level, mstatus, steps, traps);
  end
endmodule
ConceptWhat does the field MPP of mstatus hold?
ConceptWhich three steps start an application at user level?
ConceptWhich cause does an ecall at user level have?
ConceptIn this lab, where does the answer of a system call come back?
ConceptWhat does delegation of a trap mean?

Common Mistakes

Wrong Jump to the application with a jal or a jalr.

A jump changes the PC and never the level. The application runs at machine level.

Fix Write mepc, clear MPP and run mret.

Wrong Serve every trap from user code as a system call.

An illegal instruction also lands in the handler. Its registers are not a request.

Fix Check mcause first: 8 is a system call.

Wrong Return from a system call to mepc as it is.

mepc points at the ecall. The application would call again, for ever.

Fix Add 4 to mepc before the mret.

Remember

  • MPP, bits 12 and 11 of mstatus, holds the level before the trap. mret sets the level from it.
  • To start an application: write mepc, clear MPP, run mret.
  • An ecall at user level traps with cause 8. The handler serves it and returns to mepc plus 4.
  • ap_rv32 v1.0 has machine level only: its MPP always reads 11. This page ran on a model.

Practice

Report a problem with this page