Privilege Levels: Machine, Supervisor and User

A trap handler is only safe if no other code can move it. So far, any instruction could write mtvec. A processor needs a way to say: this code may, and that code may not.

You Will Be Able To

  • Say why a processor has privilege levels, and name the three of RISC-V.
  • List what code at user level cannot do, and what happens when it tries.
  • Read from the address of a CSR which level may use it, and whether it can be written.
Lesson
S2.14
Time
30 min
Runs on
Your browser
Check
6 questions

One wrong write to mtvec, and every later trap goes to the wrong place. On a chip that runs code from many authors, that write must be impossible for most of them.

Before You Start

You need the trap from S2.13: mtvec, mepc, mcause, the handler and mret.

You need cause 2, the illegal instruction, from S2.29.

Five questions this page answers
Question
1Why does a processor have more than one privilege level?
2Which three levels does RISC-V name, and which has the most rights?
3What happens when user code reads or writes a machine CSR?
4How does the address of a CSR say which level may use it?
5Which levels does ap_rv32 v1.0 have?

The Idea: Trusted Code and Other Code

Some code keeps the system alive. It sets up the handler, the timer and the memory. A fault in it stops everything.

Other code is an application. It may be new, or wrong, or written by someone else. A fault in it should stop only itself.

A right that some code has and other code lacks is a privilege.

So the processor keeps a small number beside the PC: the privilege level. It says how much the running code may do.

The highest level is the machine level. Code there may run every instruction and use every CSR. After reset the processor is always at this level.

The lowest is the user level. Code there may run ordinary instructions. It may not touch the registers that control the processor.

Between them RISC-V names a supervisor level, for the core of an operating system. A small chip can leave it out.

What if user code tries a forbidden thing? The processor does not do it. It takes a trap, and the handler at machine level decides.

One thing must be said plainly. The real core of this track, ap_rv32 v1.0, has machine level only. This page uses a model with a user level.

New Words

New words on this page
WordMeaning
Privilege levelA number the processor keeps, which says what the running code is allowed to do.
Machine levelLevel 3, the highest, written M. Every instruction and every CSR is allowed. Also called machine mode.
Supervisor levelLevel 1, written S, for an operating system. Named here, and not in our model.
User levelLevel 0, the lowest, written U. For applications. Also called user mode.
Privileged instructionAn instruction that only a high enough level may execute, such as mret.
Operating systemThe software that starts applications, serves them, and ends one that fails.
mhartidA read-only machine CSR. It holds the number of this processor in the chip.

The letter m in mtvec, mepc and mstatus says: a CSR of the machine level.

One Picture: Two Floors and Two Doors

Two Floors and Two DoorsStep through the picture. The machine level is the upper floor. The user level is the lower one. There are exactly two doors.
  • Processor
  • Control / FSM
  • Memory
  • Peripheral
Two Floors and Two DoorsStep through the picture. The machine level is the upper floor. The user level is the lower one. There are exactly two doors. component Start-up code machine level: runsfirst after reset component Trap handler machine level: the onlyway in from below component Machine CSRs mtvec, mepc, mstatusand the rest component Application user level: ordinaryinstructions only door down: mretdoor up: a trapdoor down again: mretreads and writesno access: it traps
  1. component Start-up codemachine level: runs first after reset
    • door down: mret → Application
  2. component Machine CSRsmtvec, mepc, mstatus and the rest
  3. component Applicationuser level: ordinary instructions only
    • door up: a trap → Trap handler
    • no access: it traps → Machine CSRs
  4. component Trap handlermachine level: the only way in from below
    • door down again: mret → Application
    • reads and writes → Machine CSRs
  1. After reset: upstairs

    The processor starts at machine level. The start-up code may run every instruction and use every CSR. It installs the handler.

  2. The door down

    The start-up code runs an mret that lowers the level. The application starts, at user level.

  3. What the application cannot reach

    It adds, loads, stores and branches as before. A machine CSR is closed to it. So is mret.

  4. The door up

    A trap is the only way up. It always lands in the handler, at the address that machine code chose.

  5. And down again

    The handler decides what happens. If the application may go on, an mret takes it back down.

Read the diagram as text
  • Start-up code: machine level: runs first after reset
  • Trap handler: machine level: the only way in from below
  • Machine CSRs: mtvec, mepc, mstatus and the rest
  • Application: user level: ordinary instructions only
  • Start-up code → Application: door down: mret
  • Application → Trap handler: door up: a trap
  • Trap handler → Application: door down again: mret
  • Trap handler → Machine CSRs: reads and writes
  • Application → Machine CSRs: no access: it traps

User code cannot choose where it enters the upper floor. That one fact is the whole protection.

The three levels of RISC-V
LevelNumberWho runs thereIn ap_rv32 v1.0In the model of this page
Machine3Start-up code and the trap handleryes: the only levelyes
Supervisor1The core of an operating systemnono
User0Applicationsnoyes

The numbers are those of RISC-V, not checked against its specification. The number 2 is not used.

The Smallest Example, Worked by Hand

How does the processor know that a CSR belongs to the machine level? The answer is in the address of the CSR. It has 12 bits.

Two fields in every CSR address
BitsMeaningExample: mstatus, 300 in hexExample: mhartid, f14 in hex
11 and 1011: the CSR is read-only. Anything else: it can be written00: can be written11: read-only
9 and 8The lowest level that may use the CSR11: machine only11: machine only

The address 300 in hex is 0011 0000 0000 in binary. The address f14 is 1111 0001 0100.

The user code of the lab
Address, in hexInstructionWhat it is for
040addi x10, x0, 1user code: ordinary work is allowed
044sw x10, 256(x20)so is memory, in this model
048csrr x11, mstatusread a machine CSR
04ccsrw mtvec, x10move the handler
050mretan instruction of the machine level
054csrr x12, mhartideven a read-only one
058addi x10, x10, 1
05cjal x0, 0x5cstop

It starts at 40 in hex, at user level. Four of its rows are not allowed.

Take the row at 48: csrr x11, mstatus. The CSR address is 300. Bits 9 and 8 say 3: machine only. The level is 0.

So the read is refused. The processor takes a trap with cause 2: for user code, this instruction does not exist.

The row at 4c writes mtvec, at 305. The same two bits, the same answer. The handler address stays as it was.

The row at 50 is an mret. It is a privileged instruction of the machine level. At user level it traps too.

The row at 54 only reads mhartid. A read harms nothing, one might think. But bits 9 and 8 say 3 again, and it traps.

The Rules

  1. Rule 1: After reset the level is machine.

    The first code that runs is trusted. It sets everything up before it lets other code in.

  2. Rule 2: At machine level, every instruction and every CSR is allowed.

    Memory is another matter. A later page, S3.10, adds rules for memory, called PMP entries. PMP is short for physical memory protection. An unlocked entry does not bind machine level. A locked one binds every level until the next reset: see Which PMP Entry Wins.

  3. Rule 3: A CSR may be used only at the level in bits 9 and 8 of its address, or above.

    Below that level, a read and a write both trap with cause 2.

  4. Rule 4: A CSR with 11 in bits 11 and 10 of its address is read-only.

    A write traps with cause 2 at every level, machine too.

  5. Rule 5: mret is a privileged instruction.

    At user level it traps with cause 2.

  6. Rule 6: A refused instruction changes nothing.

    No register, no CSR. The trap goes to the handler at machine level, with mepc at the instruction.

Sources for These Rules

The three levels, their numbers, the rule for CSR addresses and the illegal-instruction trap 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 (docs/soc/ap_rv32-blueprint.md, sections 5.1 and 14: user mode is a later stage). So no row on this page comes from the real core. Every row is printed by the lab, which is a model. Checked in the library: Patterson and Hennessy, Computer Organization and Design (ARM edition), section 4.9. It says that an operating system ends a program after an instruction the processor cannot decode. Read-only CSR addresses, bits 11 and 10 at 11, are in the blueprint, section 5.2.

Now Run It

The lab at the end of this page is the model with a user level. Each row starts with M or U: the level the instruction ran at.

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 | lui x20, 0x80000 | x20 = 80000000
M 00000004 | addi x5, x0, 128 | x5 = 00000080
M 00000008 | csrw mtvec, x5 | mtvec = 00000080
M 0000000c | addi x5, x0, 64 | x5 = 00000040
M 00000010 | csrw mepc, x5 | mepc = 00000040
M 00000014 | lui x5, 0x2 | x5 = 00002000
M 00000018 | addi x5, x5, -2048 | x5 = 00001800
M 0000001c | csrc mstatus, x5 | mstatus = 00000000
M 00000020 | mret | next is 00000040, MIE=0, level U
U 00000040 | addi x10, x0, 1 | x10 = 00000001
U 00000044 | sw x10, 256(x20) | mem[80000100] = 00000001
U 00000048 | csrr x11, mstatus | TRAP mcause=2 mepc=00000048 mtval=300025f3, next is 00000080
M 00000080 | csrr x6, mcause | x6 = 00000002
M 00000084 | sw x6, 0(x20) | mem[80000000] = 00000002
M 00000088 | addi x20, x20, 4 | x20 = 80000004
M 0000008c | csrr x7, mepc | x7 = 00000048
M 00000090 | addi x7, x7, 4 | x7 = 0000004c
M 00000094 | csrw mepc, x7 | mepc = 0000004c
M 00000098 | mret | next is 0000004c, MIE=0, level U
U 0000004c | csrw mtvec, x10 | TRAP mcause=2 mepc=0000004c mtval=30551073, next is 00000080
M 00000080 | csrr x6, mcause | x6 = 00000002
M 00000084 | sw x6, 0(x20) | mem[80000004] = 00000002
M 00000088 | addi x20, x20, 4 | x20 = 80000008
M 0000008c | csrr x7, mepc | x7 = 0000004c
M 00000090 | addi x7, x7, 4 | x7 = 00000050
M 00000094 | csrw mepc, x7 | mepc = 00000050
M 00000098 | mret | next is 00000050, MIE=0, level U
U 00000050 | mret | TRAP mcause=2 mepc=00000050 mtval=30200073, next is 00000080
M 00000080 | csrr x6, mcause | x6 = 00000002
M 00000084 | sw x6, 0(x20) | mem[80000008] = 00000002
M 00000088 | addi x20, x20, 4 | x20 = 8000000c
M 0000008c | csrr x7, mepc | x7 = 00000050
M 00000090 | addi x7, x7, 4 | x7 = 00000054
M 00000094 | csrw mepc, x7 | mepc = 00000054
M 00000098 | mret | next is 00000054, MIE=0, level U
U 00000054 | csrr x12, mhartid | TRAP mcause=2 mepc=00000054 mtval=f1402673, next is 00000080
M 00000080 | csrr x6, mcause | x6 = 00000002
M 00000084 | sw x6, 0(x20) | mem[8000000c] = 00000002
M 00000088 | addi x20, x20, 4 | x20 = 80000010
M 0000008c | csrr x7, mepc | x7 = 00000054
M 00000090 | addi x7, x7, 4 | x7 = 00000058
M 00000094 | csrw mepc, x7 | mepc = 00000058
M 00000098 | mret | next is 00000058, MIE=0, level U
U 00000058 | addi x10, x10, 1 | x10 = 00000002
U 0000005c | jal x0, 0x5c | the program stops here
the list: 2 2 2 2
x10=2 x11=00000000 mtvec=00000080 instructions=40 traps=4

The first nine rows start with M. They are the start-up code. Its last row, the mret, says "level U". S2.30 explains how.

Rule 2 and its limit: the rows at 40 and 44 start with U. An addi and a store. Both work as at machine level.

Rule 3 at work: the row at 48 is marked as a trap, with mcause=2. x11 was not written. The last line shows it still at 0.

After each trap come seven rows that start with M: the handler. It notes the cause, steps over the instruction and returns.

Rule 3 again at 4c: the write to mtvec traps. The last line shows mtvec at 80, where the start-up code put it.

Rule 5 at work: the row at 50 is an mret at user level. It traps. Its mtval holds the word of the mret itself.

The last lines: four traps, and the list holds cause 2 four times. The user code changed nothing it should not.

Why It Is Built This Way

Design choiceThe alternativeWhat the choice buys, and costs
The level is kept by the processorEach program promises to behaveA wrong program cannot break the promise. A few bits of state, and checks in the decoder.
A forbidden instruction trapsIt is silently ignoredTrusted code learns of the attempt and can end the program, or do the work for it.
The level is in the CSR addressA table of rights for each CSRTwo bits to compare. The address map of the CSRs is fixed by it.
Reads are refused as well as writesLet user code read everythingAn application cannot learn the state of the system. Counters that it may read get addresses of their own.
Three levels are defined, and a chip may build fewerEvery chip builds all threeA small controller pays for one level only. Software must know which levels exist.

CSRs are only half of the protection. User code can still load and store anywhere, in this model. Limits on memory are a second mechanism.

RISC-V has such a mechanism. PMP is short for physical memory protection. It is taught later, on S3.10 and S3.25.

The Trap: Code That Only Looks Like User Code

The level is not a property of the code. It is a state of the processor. The same instructions can run at either level.

Suppose the start-up code jumps to the application and forgets to lower the level first.

The same application, started with the level unchanged. Every row begins with M. The model alone.
M 00000000 | lui x20, 0x80000 | x20 = 80000000
M 00000004 | addi x5, x0, 128 | x5 = 00000080
M 00000008 | csrw mtvec, x5 | mtvec = 00000080
M 0000000c | addi x5, x0, 64 | x5 = 00000040
M 00000010 | csrw mepc, x5 | mepc = 00000040
M 00000014 | mret | next is 00000040, MIE=0, level M
M 00000040 | addi x10, x0, 1 | x10 = 00000001
M 00000044 | sw x10, 256(x20) | mem[80000100] = 00000001
M 00000048 | csrr x11, mstatus | x11 = 00000080
M 0000004c | csrw mtvec, x10 | mtvec = 00000001
M 00000050 | addi x10, x10, 1 | x10 = 00000002
M 00000054 | jal x0, 0x54 | the program stops here
the list:
x10=2 x11=00000080 mtvec=00000001 instructions=11 traps=0

Read the rows at 48 and 4c. The read of mstatus works. The write to mtvec works too: the handler address is now 1.

No trap, no message. The application ran to its end. The next fault in this system will jump to a wrong address.

So "it ran without a trap" proves nothing. A test of protection must try the forbidden thing and must see the trap.

At Scale

ap_rv32 v1.01 level: machine
A core that runs a full operating system3 levels: machine, supervisor and user

This section looks ahead. Two floors are the smallest building. Larger systems add floors, and walls inside them.

  1. The supervisor level

    A full operating system runs its core at supervisor level and its applications at user level. Machine level keeps a small layer below both. S2.30 says how traps are passed on.

  2. Memory needs its own protection

    Levels protect CSRs and instructions. Regions of memory are protected by PMP, on S3.10.

  3. The bus can carry the level

    A bus has a signal that says whether an access is privileged. A device can refuse an access from user code.

  4. Security builds on levels

    A level is the first of several separations in a chip. S9.5 puts them together.

Try It

Run the lab. Find the four rows that start with U and are marked as a trap.

Change the row at 54 to i(CSRR, 12, 0, 'hc00). The model has no CSR at that address. What does the row print, and why is the cause the same?

Remove the row with CSRC from the start-up code. Which letter do the rows of the application start with now, and what does mtvec hold at the end?

RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: M 00000000 | lui x20, 0x80000 | x20 = 80000000 M 00000004 | addi x5, x0, 128 | x5 = 00000080 M 00000008 | csrw mtvec, x5 | mtvec = 00000080 M 0000000c | addi x5, x0, 64 | x5 = 00000040 M 00000010 | csrw mepc, x5 | mepc = 00000040 M 00000014 | lui x5, 0x2 | x5 = 00002000 M 00000018 | addi x5, x5, -2048 | x5 = 00001800 M 0000001c | csrc mstatus, x5 | mstatus = 00000000 M 00000020 | mret | next is 00000040, MIE=0, level U U 00000040 | addi x10, x0, 1 | x10 = 00000001 U 00000044 | sw x10, 256(x20) | mem[80000100] = 00000001 U 00000048 | csrr x11, mstatus | TRAP mcause=2 mepc=00000048 mtval=300025f3, next is 00000080 M 00000080 | csrr x6, mcause | x6 = 00000002 M 00000084 | sw x6, 0(x20) | mem[80000000] = 00000002 M 00000088 | addi x20, x20, 4 | x20 = 80000004 M 0000008c | csrr x7, mepc | x7 = 00000048 M 00000090 | addi x7, x7, 4 | x7 = 0000004c M 00000094 | csrw mepc, x7 | mepc = 0000004c M 00000098 | mret | next is 0000004c, MIE=0, level U U 0000004c | csrw mtvec, x10 | TRAP mcause=2 mepc=0000004c mtval=30551073, next is 00000080 M 00000080 | csrr x6, mcause | x6 = 00000002 M 00000084 | sw x6, 0(x20) | mem[80000004] = 00000002 M 00000088 | addi x20, x20, 4 | x20 = 80000008 M 0000008c | csrr x7, mepc | x7 = 0000004c M 00000090 | addi x7, x7, 4 | x7 = 00000050 M 00000094 | csrw mepc, x7 | mepc = 00000050 M 00000098 | mret | next is 00000050, MIE=0, level U U 00000050 | mret | TRAP mcause=2 mepc=00000050 mtval=30200073, next is 00000080 M 00000080 | csrr x6, mcause | x6 = 00000002 M 00000084 | sw x6, 0(x20) | mem[80000008] = 00000002 M 00000088 | addi x20, x20, 4 | x20 = 8000000c M 0000008c | csrr x7, mepc | x7 = 00000050 M 00000090 | addi x7, x7, 4 | x7 = 00000054 M 00000094 | csrw mepc, x7 | mepc = 00000054 M 00000098 | mret | next is 00000054, MIE=0, level U U 00000054 | csrr x12, mhartid | TRAP mcause=2 mepc=00000054 mtval=f1402673, next is 00000080 M 00000080 | csrr x6, mcause | x6 = 00000002 M 00000084 | sw x6, 0(x20) | mem[8000000c] = 00000002 M 00000088 | addi x20, x20, 4 | x20 = 80000010 M 0000008c | csrr x7, mepc | x7 = 00000054 M 00000090 | addi x7, x7, 4 | x7 = 00000058 M 00000094 | csrw mepc, x7 | mepc = 00000058 M 00000098 | mret | next is 00000058, MIE=0, level U U 00000058 | addi x10, x10, 1 | x10 = 00000002 U 0000005c | jal x0, 0x5c | the program stops here the list: 2 2 2 2 x10=2 x11=00000000 mtvec=00000080 instructions=40 traps=4

Check Yourself

Predict the outputUser code writes mscratch, adds 3 to x10, runs an ebreak and reads mepc. The handler lists each cause and returns behind the instruction. What does the last line say?
// User code with three instructions that are not allowed. What is the list?
// 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(LUI,    20, 0,  'h80000);    // 000: lui x20, 0x80000
    i(ADDI,   5,  0,  128);        // 004: addi x5, x0, 128      machine level: the handler address
    i(CSRW,   5,  0,  MTVEC);      // 008: csrw mtvec, x5
    i(ADDI,   5,  0,  64);         // 00c: addi x5, x0, 64      where the user code starts
    i(CSRW,   5,  0,  MEPC);       // 010: csrw mepc, x5
    i(LUI,    5,  0,  'h2);        // 014: lui x5, 0x2      bits 12 and 11: the field MPP
    i(ADDI,   5,  5,  -2048);      // 018: addi x5, x5, -2048
    i(CSRC,   5,  0,  MSTATUS);    // 01c: csrc mstatus, x5      MPP = 00: user
    i(MRET,   0,  0,  0);          // 020: mret      go down to the user code
    at('h40);
    i(CSRW,   10, 0,  MSCRATCH);   // 040: csrw mscratch, x10
    i(ADDI,   10, 10, 3);          // 044: addi x10, x10, 3
    i(EBREAK, 0,  0,  0);          // 048: ebreak
    i(CSRR,   11, 0,  MEPC);       // 04c: csrr x11, mepc
    i(JAL,    0,  0,  'h50);       // 050: jal x0, 0x50
    at('h80);
    i(CSRR,   6,  0,  MCAUSE);     // 080: csrr x6, mcause      the handler, at machine level
    i(SW,     6,  20, 0);          // 084: sw x6, 0(x20)
    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. 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);
    $write("the list:");  for (int n = 0; n < traps; n++) $write(" %0d", mem[n]);  $display("");
  end
endmodule
ConceptWhy does a processor have more than one privilege level?
ConceptWhich three levels does RISC-V name, from the most rights to the fewest?
ConceptUser code runs csrw mtvec, x10. What happens?
ConceptA CSR has the address 305 in hex. What do bits 9 and 8 of it say?
ConceptWhich levels does the real core ap_rv32 v1.0 have?

Common Mistakes

Wrong Think of user code as code at certain addresses.

The level is a state of the processor. Any code runs at the level the processor is in.

Fix Lower the level before the application starts, and test that it is lowered.

Wrong Expect that user code may at least read a machine CSR.

Bits 9 and 8 of the address apply to reads and writes alike.

Fix A value that applications need gets a CSR address of its own, or a service of the handler.

Wrong Say that ap_rv32 has a user level.

Version 1.0 has machine level only. The user level here is a model.

Fix Name the level of evidence: the model, or the real core.

Remember

  • The processor keeps a privilege level. Machine is 3 and may use every instruction and CSR. User is 0. Supervisor, 1, lies between.
  • Bits 9 and 8 of a CSR address give the lowest level that may use it. Bits 11 and 10 at 11 mean read-only.
  • A forbidden CSR access or an mret at user level traps with cause 2, and changes nothing.
  • ap_rv32 v1.0 has machine level only. The user level on this page is a model.

Practice

Report a problem with this page