3. Privilege

Privilege: RISC-V modes and x86 rings Left: RISC-V's three modes M, S and U in a column with V equal to 0, and beside S and U the dashed guest modes VS and VU with V equal to 1, which the hypervisor extension adds. A trap climbs or stays level, mret and sret descend, and reset starts in M. Right: x86's four rings, ring 0 to ring 3 with the current privilege level named CPL, and below them the two VMX operations, root and non-root, as a second axis. RISC-V V = 0 V = 1 M machine S / HS supervisor U user VS guest kernel VU guest process H extension chapters 18 to 19 a trap climbs or stays level mret and sret descend reset starts in M x86 the other dialect ring 0 CPL 0, kernel ring 1 CPL 1 ring 2 CPL 2 ring 3 CPL 3, user VMX adds a second axis root non-root

Why this layer exists

A hart (chapter 2’s hardware thread) is always executing in exactly one privilege mode, a piece of hart state that decides three things about the next instruction: which instructions it may execute, which control and status registers it may name, and which memory it may touch. This board’s hart has three modes. U-mode (user) is for applications, the least privileged. S-mode (supervisor) is for an operating-system kernel. M-mode (machine) is the most privileged: the mode the hart is in at reset, the one that can do anything, and the one firmware runs in. The privileged specification states the intent in one sentence: “User-mode (U-mode) and supervisor-mode (S-mode) are intended for conventional application and operating system usage respectively.” Every isolation story in this book is this state, moved. User processes in chapter 7 are U-mode refused a page and a register. Nested paging in chapter 19 is a hypervisor refusing a guest’s access to a page. The guest entry that chapter 19 builds is this chapter’s drop one rung lower: an instruction that changes the mode and the program counter together, so that the next fetch is a different kind of fetch.

Chapter 2 argued from outside that a kernel is not a process: no loader, no exit path, no stack it did not make. This chapter shows what is inside that argument. A kernel is code that the hart lets execute instructions and name registers that a process’s code cannot, because the hart is in a different mode when it runs. M-mode must also configure one piece of memory protection, PMP (physical memory protection), before any lower mode can run at all. The lab drops from M to S and proves that the hart left M by having it execute an instruction that only M may; the exercises show what tells S from U.

Mechanism

Three modes, and what they are for

The specification gives each mode a two-bit encoding and reserves one:

Level Encoding Name Abbreviation
0 00 User/Application U
1 01 Supervisor S
2 10 Reserved
3 11 Machine M

These encodings reappear in the privilege fields of mstatus (below) and, with 10 meaning the hypervisor level, in the CSR numbering scheme (the CSR section below). A hart need not have all three. The specification’s own table of combinations is M alone (“simple embedded systems”), M and U (“secure embedded systems”), or M, S and U (“systems running Unix-like operating systems”); it says “The machine level has the highest privileges and is the only mandatory privilege level for a RISC-V hardware platform”, and that code in M-mode “is usually inherently trusted, as it has low-level access to the machine implementation.” This hart has all three; misa, below, says so.

The three powers a mode grants are three kinds of check:

  • Instructions. Some instructions exist only above U-mode. mret is an M-mode instruction, sret an S-mode one, and a CSR instruction naming a register above the current mode traps.
  • Registers. The control and status registers (CSRs, defined in the CSR section below) are partitioned by mode, and the partition is part of each register’s number.
  • Memory. M-mode sees physical addresses with no PMP checks by default. S-mode and U-mode see only what M-mode’s PMP and S-mode’s page tables (chapter 4) allow. The checks are made on every access.

Reset fixes the starting point. The specification’s Reset section: “Upon reset, a hart’s privilege mode is set to M.” Chapter 2 saw that this holds on this board. Everything in this book that runs lower than M-mode gets there from M-mode, by an instruction that M-mode executes, which is why this chapter belongs before chapters 4 to 6: they all run in S.

On a system with firmware, M-mode belongs to the firmware. With QEMU’s default boot, OpenSBI (chapter 2) runs in M and enters the kernel in S. With -bios none, ember has no one to hand M-mode to, so it is also its own firmware: a small M-mode part, the shim of this chapter, and an S-mode part, the kernel proper. That split is the same in every RISC-V system that runs an S-mode kernel. What differs is who writes the M-mode half.

Traps: how the mode changes

Three words recur from here on, and the specification defines them in its introduction to Volume I: “We use the term exception to refer to an unusual condition occurring at run time associated with an instruction in the current RISC-V hart. We use the term interrupt to refer to an external asynchronous event that may cause a RISC-V hart to experience an unexpected transfer of control. We use the term trap to refer to the transfer of control to a trap handler caused by either an exception or an interrupt.” An exception is caused by the instruction being executed (an illegal instruction, a load from an address the hardware refuses, an ecall the program meant to execute); it is synchronous with the instruction stream. An interrupt is caused by something else (a timer reaching its deadline, a device raising a line) and arrives between instructions. A trap is what the hart does about either: it stops fetching in order and starts at a handler’s address. Chapter 5 builds the interrupt side and the ecall side; chapter 4 uses all three words.

A trap changes the mode, and the direction is constrained. The specification’s Privilege Levels section calls “traps that increase privilege level” vertical and “traps that remain at the same privilege level” horizontal. Which level takes a trap is a rule stated in the machine-level chapter: “By default, all traps at any privilege level are handled in machine mode”, unless M-mode has delegated it (a later section), and “Traps never transition from a more-privileged mode to a less-privileged mode.” So a trap climbs or stays level. The only way down is a return instruction, mret or sret, executed by a handler that is finished with the trap, or by software that wants to enter a lower mode with no trap behind it. There is no instruction that calls S-mode. To start S-mode at all, M-mode must fabricate the state a trap would have left (the mode to return to, the address to return to) and then return into it. That is what drop_to_s does, and it is why a drop looks like the tail of a trap handler with no trap before it.

What a trap does to the hart is a short list. It saves the interrupted instruction’s address, the reason, and a trap-specific value in CSRs. It saves the previous mode and the previous interrupt-enable bit in two fields of mstatus. It loads the program counter from a register holding the handler’s address. (With the H extension it also records and resets the virtualization state and writes two more CSRs, mtval2 and mtinst.) The specification’s account of what a trap writes has no general-purpose register and no stack pointer on it, so the first instruction of the handler runs with every register as the interrupted code left it, including a stack pointer that may be unusable. The mscratch section shows what software does about it.

The hypervisor extension adds modes under S and U

The hypervisor extension (the H extension) is the RISC-V extension that adds hardware support for running a guest operating system under a hypervisor: it “virtualizes the supervisor-level architecture to support the efficient hosting of guest operating systems atop a type-1 or type-2 hypervisor.” It turns S-mode into HS-mode and adds two guest modes, VS-mode (the guest’s kernel) and VU-mode (the guest’s processes), which the figure draws dashed. The S-mode this chapter drops into is HS-mode: reset-state.txt prints mstatus as 0xa00000000 before the drop, with MPV (bit 39) clear, which is what an mret with MPP=S needs to land in HS and not in a guest. Chapter 18 defines the virtualization mode that separates HS from VS and the new CSRs, and walks a guest kernel’s instructions through them; nothing in Part I uses the guest modes. The extension is also visible in misa, below, whose H bit this board sets.

x86’s rings, the other dialect

The same problem is solved on x86 with a different shape. The Intel software developer’s manual (Volume 3A, Chapter 6, “Protection”) describes the mechanism: “The processor’s segment-protection mechanism recognizes 4 privilege levels, numbered from 0 to 3. The greater numbers mean lesser privileges.” Drawn as rings, level 0 is the centre. The level of the running code is the current privilege level, CPL, which “is stored in bits 0 and 1 of the CS and SS segment registers” and “Normally ... is equal to the privilege level of the code segment from which instructions are being fetched.” So on x86 the mode is two bits of a segment selector, and it changes when control transfers to a code segment with a different privilege level. Segments and gates carry their own descriptor privilege level (DPL), and a lower-privileged program cannot name a more-privileged segment.

Two contrasts with RISC-V matter for what follows. The first is how control reaches more privilege. A RISC-V trap goes to one vector register per mode (mtvec, stvec, below), and nothing else can enter a higher mode. On x86 a call to more privileged code goes through a gate, a descriptor that names the target and says who may use it. Interrupts and exceptions go through gates in the interrupt descriptor table, and 64-bit mode adds the SYSCALL instruction, which the manual says is “intended for use by user code running at privilege level 3 to access operating system or executive procedures running at privilege level 0”, with SYSRET as its return (Volume 3A, section 6.8.8). The second contrast is the stack. Whenever a call gate transfers control to a more privileged nonconforming code segment, “the processor automatically switches to the stack for the destination code segment’s privilege level”, whose pointer comes from the task-state segment (section 6.8.5). SYSCALL does not: the manual says it “does not save the stack pointer”. A RISC-V trap never switches stacks. It leaves sp where it was.

The middle rings have a history. Multics, the system whose ring protection the Schroeder and Saltzer paper (1972) describes, used eight rings: the lowest-level supervisor procedures in ring 0, the remaining supervisor in ring 1, ordinary user procedures in ring 4, rings 2 and 3 for user-constructed subsystems and rings 5 to 7 for a user’s self-protection. The paper calls its mechanism “a methodical generalization of the traditional supervisor/user protection scheme”. The x86 manual’s four rings have the same shape with fewer rungs, and its own guidance for software that wants fewer is: “Systems that use only 2 of the 4 possible privilege levels should use levels 0 and 3.” Three things the sources say bear on the middle rungs. Paging distinguishes only two kinds of access: “accesses made while CPL < 3 are supervisor-mode accesses, while accesses made while CPL = 3 are user-mode accesses” (Volume 3A, section 5.6.1), so to the page tables ring 1 and ring 2 are ring 0. The 64-bit fast system-call path connects levels 3 and 0 alone. And Xen’s paravirtualized x86 put a guest kernel in ring 1 (Barham et al., SOSP 2003, section 2.1.2), which the authors could do because “To our knowledge, rings 1 and 2 have not been used by any well-known x86 OS since OS/2.” That sentence is the authors’ 2003 statement, not a measurement.

The hardware answer for guests is on a different axis. The VMX extensions (Intel’s, in Volume 3C chapter 26) add two kinds of processor operation: “VMX root operation and VMX non-root operation. In general, a VMM will run in VMX root operation and guest software will run in VMX non-root operation.” The manual says that processor behavior in root operation “is very much as it is outside VMX operation”, and states the purpose for guests in terms of the ring: “Because VMX operation places restrictions even on software running with current privilege level (CPL) 0, guest software can run at the privilege level for which it was originally designed.” A guest kernel on VMX can therefore run at CPL 0, the same ring it would have on bare metal, with the hypervisor’s restrictions applying under it. The H extension makes the same kind of move with the V bit: a guest kernel runs in VS-mode, “virtual S-mode” in the specification’s words, so it keeps its S name while a second piece of state (V) puts the hypervisor under it. Chapter 18 meets the x86 counterpart again, in its history of the hardware fix for trap-and-emulate.

RISC-V x86
Levels M, S, U (and HS, VS, VU with H) rings 0 to 3 (plus VMX root and non-root)
Where the current level lives hart state, recorded on a trap in mstatus.MPP and SPP (below) CPL, bits 1:0 of the CS and SS selectors
How control reaches more privilege a trap, to one vector register per mode gates (call, interrupt, trap, task), SYSCALL
Stack on privilege change none: software swaps sp hardware loads the destination ring’s stack from the TSS (call gates); SYSCALL does not
What paging distinguishes the U bit: user versus supervisor (chapter 4) CPL < 3 versus CPL = 3

CSRs: an address space of its own

A control and status register (CSR) is a register that configures or reports the hart itself: the trap vector, the mode stack, the delegation masks, the cycle counter. CSRs are not memory. They have no address on the bus, a load or a store cannot reach one, and each CSR instruction names exactly one of them. The Zicsr extension defines six instructions. The three that matter are csrrw (atomic read and write), csrrs (atomic read and set bits) and csrrc (atomic read and clear bits), each also in an immediate form (csrrwi, csrrsi, csrrci) that takes a 5-bit constant in place of a source register. “All CSR instructions atomically read-modify-write a single CSR, whose CSR specifier is encoded in the 12-bit csr field of the instruction held in bits 31-20.” The names csrr (read), csrw (write), csrs (set bits) and csrc (clear bits) that the assembly in this book uses are assembler pseudoinstructions: csrr rd, csr is csrrs rd, csr, x0 and csrw csr, rs1 is csrrw x0, csr, rs1.

The 12-bit field is an immediate: it is in the instruction word, not in a register. Two consequences follow. A CSR cannot be named by a computed number; the register is fixed when the program is assembled. And the space has 4,096 slots, in which the specification lays out an access rule by position.

A CSR number is also an access rule The twelve-bit CSR number split into bits 11 to 10, bits 9 to 8 and bits 7 to 0, for four registers. mhartid, 0xf14, is 11 11 0001 0100: read-only, machine mode and up. mstatus, 0x300, is 00 11: read/write, machine. sstatus, 0x100, is 00 01: read/write, supervisor and up. cycle, 0xc00, is 11 00: read-only, user and up. [11:10] [9:8] [7:0] mhartid 0xf14 11 11 0001 0100 read-only, M and up mstatus 0x300 00 11 0000 0000 read/write, M and up sstatus 0x100 00 01 0000 0000 read/write, S and up cycle 0xc00 11 00 0000 0000 read-only, U and up csr[11:10] = 11 means read-only. csr[9:8] is the lowest mode that may access it: 00 U, 01 S, 10 hypervisor, 11 M.

The text from the specification’s CSR chapter: “By convention, the upper 4 bits of the CSR address (csr[11:8]) are used to encode the read and write accessibility of the CSRs according to privilege level” (it points at a table of address ranges). “The top two bits (csr[11:10]) indicate whether the register is read/write (00, 01, or 10) or read-only (11). The next two bits (csr[9:8]) encode the lowest privilege level that can access the CSR, with the pattern 10 representing hypervisor CSRs.” The figure applies the rule to four registers. mhartid is 0xf14, which is 1111 0001 0100: bits 11:10 are 11, so it is read-only, and bits 9:8 are 11, so the lowest mode that may access it is M. mstatus at 0x300 is read/write and M-level. sstatus at 0x100 (the S-mode view of mstatus; chapter 4 uses its SUM and MXR bits and chapter 5 its interrupt-enable and previous-privilege bits) is read/write and S-level, so S and M may name it and U may not. cycle at 0xc00 is read-only and U-level.

Two rules turn the encoding into behaviour. “Attempts to access a CSR without appropriate privilege level raise illegal-instruction exceptions” (or, from a guest, virtual-instruction exceptions, which chapter 18 explains), and “Attempts to write a read-only register raise illegal-instruction exceptions.” Both are decided by the instruction’s bits, without reading the register. Reading a read-only register is not a write: the Zicsr rule is that for csrrs and csrrc “if rs1=x0, then the instruction will not write to the CSR at all, and so shall not cause any of the side effects that might otherwise occur on a CSR write, nor raise illegal-instruction exceptions on accesses to read-only CSRs.” That is why csrr t0, mhartid is a legal read in M-mode and an illegal one in S-mode and U-mode: the number’s bits 9:8 are 11, and M is the only mode that satisfies them. The reverse direction is always open: “although CSRs and instructions are associated with one privilege level, they are also accessible at all higher privilege levels.”

The instruction the lab uses to prove the drop decodes by hand. csrr t0, mhartid is csrrs x5, 0xf14, x0: opcode 0x73 (SYSTEM), rd = 5 (t0 is x5), funct3 = 2 (csrrs), rs1 = 0, and the 12-bit field 0xf14. Assembled, bits 31:20 are 0xf14, bits 19:15 are zero, bits 14:12 are 2, bits 11:7 are 5, bits 6:0 are 0x73: 0xf14 << 20 is 0xf1400000, 2 << 12 is 0x2000, 5 << 7 is 0x280, and the sum with 0x73 is 0xf14022f3. The lab’s capture prints exactly that word as mtval. Exercise (g) shows the other rule, a write to a read-only register, taking the same cause 2 from M.

Three field kinds recur in the register descriptions. A WPRI field (writes preserve, reads ignore) is reserved for the future: software leaves it alone. A WLRL field has legal values and illegal ones, and software must not rely on what it reads back after an illegal write. A WARL field accepts any write and reads back a legal value, so software discovers what the hart supports by writing and reading: “the range of supported values can be determined by attempting to write a desired setting then reading to see if the value was retained.” The side runs use the WARL rule as a probe wherever the specification leaves the supported set to the implementation.

misa: what the hart says it is

misa (number 0x301) is the machine ISA register, “a WARL read-write register reporting the ISA supported by the hart”, with the allowance that “a value of zero can be returned to indicate the misa register has not been implemented.” Its two fields on this 64-bit hart: bits 63:62 are MXL, the base width (1 is 32 bits, 2 is 64, and the specification gives the width as 2MXL+42^{\mathrm{MXL}+4}), and bits 25:0 are the Extensions field, “a single bit per letter of the alphabet (bit 0 encodes presence of extension “A”, bit 1 encodes presence of extension “B”, through to bit 25 which encodes “Z”)”. The extension letters this chapter needs: A atomics, C compressed, D and F double and single float, H hypervisor, I the base integer ISA, M integer multiply and divide, S supervisor mode, U user mode.

The side run labs/ch03/ex/misa.txt reads misa on this board, and exercise (e) decodes it. S, U and H are set. S and U are implemented (“When the “S” bit is 1, the implementation supports supervisor mode”), and H is the bit the hypervisor chapter assigns: “The hypervisor extension is enabled by setting bit 7 in the misa CSR, which corresponds to the letter H.”

misa is also WARL, and exercise (e) tries a write. The specification allows implementations to make the extension bits writable (“Extensions field is a WARL field that can contain writable bits where the implementation allows the supported ISA to be modified”) and a bit that is clear does not prove a feature absent (“one of these bits being clear does not necessarily imply that the corresponding feature is not implemented”).

A kernel cannot read misa; it is an M-level CSR (0x301, bits 9:8 11) and S-mode taking an illegal-instruction exception is the specified result. The specification says why, in a note: “We require that lower privilege levels execute environment calls instead of reading CPU registers to determine features available at each privilege level. This enables virtualization layers to alter the ISA observed at any level”. An S-mode kernel learns what the hart has from firmware or from the device tree that the board passes in a1 (chapter 2). The device tree describes the hart with an ISA string, whose grammar is in the specification’s ISA extension naming chapter: it begins with the base (rv64i), then single-letter standard extensions (“Standard ISA extensions are given a name consisting of a single letter”), then multi-letter extensions each separated by an underscore. A Z prefix names an unprivileged extension (zba, zicsr), Sv a supervisor virtual-memory one (svadu), Ss another supervisor-level one (sstc), Sh a hypervisor-level one (shgatpa), Sm a machine-level one; other prefixes occur too (sdtrig). The board’s string, from labs/ch03/ex/isa-string.txt, begins rv64imafdch_zic64b_zicbom_ and carries 42 multi-letter names after its seven letters. Its single letters are i m a f d c h, which are the misa letters minus S and U; the string names no letter for the privilege modes. Most multi-letter extensions, svadu and sstc among them, have no misa bit (exercise (e) meets a group that does), so a kernel on this board learns of the Svadu extension (chapter 4) from the device tree, not from misa.

mstatus: the privilege stack and the switchboard

mstatus (0x300) is the register that “keeps track of and controls the hart’s current operating state”. Its RV64 layout, from the specification’s figure, places each field at a fixed bit. The fields this book uses:

Field Bits Meaning
SIE 1 S-mode global interrupt enable
MIE 3 M-mode global interrupt enable
SPIE 5 SIE stacked on a trap into S
MPIE 7 MIE stacked on a trap into M
SPP 8 previous privilege for sret: one bit, 0 for U, 1 for S
MPP 12:11 previous privilege for mret: two bits, 00 U, 01 S, 11 M
MPRV 17 M’s loads and stores use MPP’s translation and protection
SUM, MXR 18, 19 S-mode’s access to U pages, and loads from execute-only pages (chapter 4)
TVM, TW, TSR 20, 21, 22 let M make S’s satp/sfence.vma, wfi, and sret trap (chapter 18)
UXL, SXL 33:32, 35:34 the base width of U and S; 2 is 64-bit
MPV 39 the virtualization mode before a trap into M (the H extension, chapter 18)

The positions are from the specification’s RV64 mstatus figure. Every mstatus value the captures print has 0xa00000000 in its high half: bits 33 and 35, UXL and SXL both 2, 64-bit.

Why a stack of two. A trap changes the mode and must remember the old one; the handler’s own return needs it. If the handler may itself be interrupted, the new trap needs to remember the handler’s state too. The specification’s design is a two-level stack in the status register: “each privilege mode x that can respond to interrupts has a two-level stack of interrupt-enable bits and privilege modes. xPIE holds the value of the interrupt-enable bit active prior to the trap, and xPP holds the previous privilege mode.” The rule on entry: “When a trap is taken from privilege mode y into privilege mode x, xPIE is set to the value of xIE; xIE is set to 0; and xPP is set to y.” So on a trap into M from S, MPIE takes MIE’s old value, MIE clears (the handler runs with M’s interrupts off), and MPP takes S. The width of the fields is the width of what can be recorded: “The xPP fields can only hold privilege modes up to x, so MPP is two bits wide and SPP is one bit wide.” SPP has room for U and S and nothing else because no trap into S can come from M (a trap never goes down), which is why sret has no way to climb.

What the enable bits gate. MIE and SIE are not the whole story of interrupts, and it matters here that they gate less than their names suggest. The rule: “When a hart is executing in privilege mode x, interrupts are globally enabled when xIE=1 and globally disabled when xIE=0. Interrupts for lower-privilege modes, w<x, are always globally disabled regardless of the setting of any global wIE bit for the lower-privilege mode. Interrupts for higher-privilege modes, y>x, are always globally enabled regardless of the setting of the global yIE bit for the higher-privilege mode.” MIE therefore matters only while the hart is in M; once the hart is in S or U, MIE stops nothing. An interrupt also needs its own bit. The specification: “An interrupt i will trap to M-mode (causing the privilege mode to change to M-mode) if all of the following are true: (a) either the current privilege mode is M and the MIE bit in the mstatus register is set, or the current privilege mode has less privilege than M-mode; (b) bit i is set in both mip and mie; and (c) if register mideleg exists, bit i is not set in mideleg.” mip (0x344) holds the pending interrupts and mie (0x304) the per-source enables, both indexed by interrupt cause code. Exercise (c) shows what the board’s reset values of the two hold off. Chapter 6 depends on this: the timer interrupt that M handles reaches a hart running in S because M is higher than S and its bit is set in mie.

Reset. The Reset section names MIE and MPRV (and MBE where little-endian accesses are supported): “The mstatus fields MIE and MPRV are reset to 0”. It says nothing of the previous-mode and previous-enable fields, and ends with “All other hart state is UNSPECIFIED.” The lab reads MPP at the top of ch3_drop and prints M: mstatus MPP=U. That is a fact about this QEMU, as is MPIE clear and MPV clear before the drop (mpie-base.txt, reset-state.txt). A hart whose reset left MPP at M would still drop correctly because drop_to_s writes MPP before it returns, which is the point of writing it.

Discovering which modes exist. The fields are WARL: “xPP fields are WARL fields that can hold only privilege mode x and any implemented privilege mode lower than x.” The specification adds a probe: “M-mode software can determine whether a privilege mode is implemented by writing that mode to MPP then reading it back.” ember does not need the probe, because misa is readable in M.

mret, in full

The specification’s account of mret is in three places. The privilege-stack text says: “When executing an xRET instruction, supposing xPP holds the value y, xIE is set to xPIE; the privilege mode is changed to y; xPIE is set to 1; and xPP is set to the least-privileged supported mode (U if U-mode is implemented, else M). If y≠M, xRET also sets MPRV=0.” The trap-return section adds the program counter: “In addition to manipulating the privilege stack ..., xRET sets the pc to the value stored in the xepc register.” And the hypervisor chapter, because this hart has the H extension, adds the virtualization state: “MRET then in mstatus/mstatush sets MPV=0, MPP=0, MIE=MPIE, and MPIE=1. Lastly, MRET sets the privilege mode as previously determined, and sets pc=mepc”, where the new mode is determined by MPP and MPV together, and MPV is ignored when MPP is 3. Taken together, mret does these things as one indivisible step:

  1. The new mode is the one MPP names (and, with H, V is set from MPV, unless MPP is M).
  2. pc becomes mepc.
  3. MIE takes MPIE’s value.
  4. MPIE becomes 1.
  5. MPP becomes the least-privileged supported mode, U on this hart. Its reason, in the specification: “Setting xPP to the least-privileged supported mode on an xRET helps identify software bugs in the management of the two-level privilege-mode stack.” A handler that forgets to set MPP before the next mret drops into U rather than back into M.
  6. MPRV becomes 0 if the new mode is not M.
  7. With H, MPV becomes 0.

Item 6 has a use: MPRV is the bit that makes M’s loads and stores borrow the privilege MPP names (chapter 4 mentions it; ember never sets it), and without item 6 the bit would stay set while S ran and would reappear on the next trap into M. Exercises (b) and (c) observe the list. The manual names a few further effects that need extensions this board mostly lacks (Smdbltrp’s MDT, Zicfilp’s landing-pad state); for A, which it has, “the xRET instruction is allowed to clear any outstanding LR address reservation but is not required to.”

An xRET is itself privileged: “An xRET instruction can be executed in privilege mode x or higher ... Attempting to execute an xRET instruction in a mode less privileged than x will raise an illegal-instruction exception.” S-mode cannot mret; exercise (g) runs it. M-mode may execute sret, and the rule is the same one: “executing a lower-privilege xRET instruction will pop the relevant lower-privilege interrupt enable and privilege mode stack.”

Where a trap lands: mtvec, mepc, mcause, mtval

A trap into M sets the program counter from mtvec and records the rest in three CSRs.

mtvec (0x305) “holds trap vector configuration, consisting of a vector base address (BASE) and a vector mode (MODE)”. BASE is bits 63:2 of the handler’s address, so the handler’s address has its two low bits zero: “The value in the BASE field must always be aligned on a 4-byte boundary”. MODE is bits 1:0: 0 is Direct (“All traps set pc to BASE”), 1 is Vectored (“Asynchronous interrupts set pc to BASE+4×cause”), and 2 and above are reserved. In Vectored mode synchronous exceptions still go to BASE, and the spec’s example is the machine timer interrupt, cause 7, landing at BASE+0x1c. The specification lets the implementation demand more alignment in Vectored mode. ember uses Direct: the single entry point is the shim, and .align 2 in mshim.S supplies the 4-byte alignment. The field is WARL, and labs/ch03/ex/mtvec-warl.txt probes this board by writing a different BASE with each of the four MODE values:

M: mtvec wrote 0x1000 read 0x1000
M: mtvec wrote 0x2001 read 0x2001
M: mtvec wrote 0x3002 read 0x2001
M: mtvec wrote 0x4003 read 0x2001

Modes 0 and 1 are accepted whole. A write with a reserved MODE (2 or 3) leaves the register unchanged, base included: this board drops the entire write. The specification permits any legal value; this is the board’s choice. The Reset section does not give mtvec a value (“All other hart state is UNSPECIFIED”), and chapter 2’s exercise (b) found this board resets it to 0.

mepc (0x341) “is written with the virtual address of the instruction that was interrupted or that encountered the exception.” For ecall it is the ecall itself (“not the address of the following instruction”), which is why a handler that means to step past the instruction adds 4 before returning (chapter 5’s does). mret reads it back. Its bit 0 is always zero.

mcause (0x342) has an Interrupt bit at the top (bit 63 here) and an Exception Code in the rest (“a WLRL field, so is only guaranteed to hold supported exception codes”). “Interrupts can be separated from other traps with a single branch on the sign of the mcause register value.” The codes that matter, from the specification’s table:

Exception code Cause
0 Instruction address misaligned
1 Instruction access fault
2 Illegal instruction
3 Breakpoint
4 Load address misaligned
5 Load access fault
6 Store/AMO address misaligned
7 Store/AMO access fault
8 Environment call from U-mode
9 Environment call from S-mode
11 Environment call from M-mode
12 Instruction page fault
13 Load page fault
15 Store/AMO page fault

and for the Interrupt bit set: 1 supervisor software, 3 machine software, 5 supervisor timer, 7 machine timer, 9 supervisor external, 11 machine external. The “access fault” causes (1, 5, 7) are the ones PMP and the platform’s physical memory attributes raise; the “page fault” causes (12, 13, 15) are chapter 4’s translation failing. The listing’s MCAUSE_INT is bit 63, and the shim masks it off before it compares.

mtval (0x343) is a second word of information, and the specification leaves most of its contents to the platform: “When a trap is taken into M-mode, mtval is either set to zero or written with exception-specific information to assist software in handling the trap. ... The hardware platform will specify which exceptions must set mtval informatively, which may unconditionally set it to zero, and which may exhibit either behavior”. Two rules are specified when it is written. For a breakpoint, misaligned access, access fault, page fault or hardware error on a fetch, a load or a store, “mtval will contain the faulting virtual address”, and with translation on, that address is written “even for physical-memory access-fault exceptions” (chapter 4). For illegal-instruction: “The mtval register can optionally also be used to return the faulting instruction bits”, the shortest of the instruction, its first ILEN bits (the maximum instruction length), and its first MXLEN bits (the register width, 64 here), “right-justified and all unused upper bits are cleared to zero”. “Optionally” decides what this book may claim. On this board’s QEMU the illegal-instruction case writes the instruction bits (every cause-2 transcript in labs/ch03/ex/); that is a board fact and a hart that always wrote zero would also conform. Chapter 5’s S-mode handler reads the same word from stval.

mscratch: a register for the handler to use first

A trap handler’s first problem is that it needs a register and a stack and has neither: the trap saved nothing, and sp still holds whatever the interrupted code had. For an exception from S-mode code that was running on its own stack, the stack is plausible, and the shim of this chapter could use it. For a trap that interrupts U-mode code (chapter 8 derives the fault), sp is a user address that M-mode does not translate and that may have no memory behind it. The designers’ answer is a register the hart reserves for the handler. The specification: “The mscratch register is an MXLEN-bit read/write register dedicated for use by machine mode. Typically, it is used to hold a pointer to a machine-mode hart-local context space and swapped with a user register upon entry to an M-mode trap handler.” The swap is a single instruction, csrrw sp, mscratch, sp: for csrrw with rd not x0, the old CSR value goes to rd and the register’s value goes to the CSR, so sp becomes the shim’s stack and mscratch holds the interrupted sp. The same instruction at the exit swaps them back. This chapter’s drop installs the shim stack in mscratch unconditionally and the entry code swaps through it on every M trap, although every trap in this chapter comes from S, whose sp would have served. Chapter 8 is where it earns its place.

Delegation: medeleg and mideleg

By default every trap goes to M. A kernel in S would then be reached only through an M-mode handler that forwarded each trap by hand, which the specification allows (“a machine-mode handler can redirect traps back to the appropriate level with the MRET instruction”), and it offers a faster path: “To increase performance, implementations can provide individual read/write bits within medeleg and mideleg to indicate that certain exceptions and interrupts should be processed directly by a lower privilege level.” medeleg (0x302) is the exception delegation register and mideleg (0x303) the interrupt one. A set bit delegates the corresponding cause, with the rule’s condition spelled out: “setting a bit in medeleg or mideleg will delegate the corresponding trap, when occurring in S-mode or U-mode, to the S-mode trap handler.” The bit index is the cause code: medeleg has “a bit position allocated for every synchronous exception ..., with the index of the bit position equal to the value returned in the mcause register (i.e., setting bit 8 allows user-mode environment calls to be delegated to a lower-privilege trap handler)”, and mideleg “holds trap delegation bits for individual interrupts, with the layout of bits matching those in the mip register” (the pending-interrupt register, 0x344), where STIP delegation is bit 5.

A delegated trap is taken by S, and S’s registers are the ones written: “the scause register is written with the trap cause; the sepc register is written with the virtual address of the instruction that took the trap; the stval register is written with an exception-specific datum; the SPP field of mstatus is written with the active privilege mode at the time of the trap; the SPIE field of mstatus is written with the value of the SIE field at the time of the trap; and the SIE field of mstatus is cleared. The mcause, mepc, and mtval registers and the MPP and MPIE fields of mstatus are not written.” The handler address is stvec, S-mode’s twin of mtvec (0x105), which chapter 5 sets. Delegation cannot lower a trap that arises in M: it is never delegated. (“If M-mode has delegated illegal-instruction exceptions to S-mode, and M-mode software later executes an illegal instruction, the trap is taken in M-mode.”) Delegation also masks: delegated interrupts “result in the interrupt being masked at the delegator privilege level.”

The hardware may not honour every bit, and the specification gives the discovery method: “the supported delegatable bits found by writing one to every bit location, then reading back the value in medeleg or mideleg.” Two rules are fixed regardless: “An implementation shall not have any bits of medeleg be read-only one”, and for exceptions that cannot occur in less privileged modes the bits “should be read-only zero. In particular, medeleg[11] is read-only zero” (an environment call from M-mode is raised in M and could not be delegated), and “medeleg[16] is read-only zero as double trap is not delegatable.” The H extension adds a rule for mideleg: “bits 10, 6, and 2 of mideleg (corresponding to the standard VS-level interrupts) are each read-only one” and “if any guest external interrupts are implemented (GEILEN is nonzero)”, bit 12 “is also read-only one” (section 14.1.4.2). The base rule adds that an implementation “shall not fix as read-only one any bits of mideleg corresponding to machine-level interrupts (but may do so for lower-level interrupts).”

The side run labs/ch03/ex/delegation-probe.txt applies the probe on this board, from M, before the drop, and exercise (d) decodes its all-ones readbacks. medeleg resets to 0. mideleg resets to 0x1444, and only bits 2, 6 and 10 of that are the H extension’s. Bit 12 reads one too, but the specification forces it only when GEILEN is nonzero, and hgeie, whose writable bits are GEILEN:1 (“bits GEILEN:1 shall be writable in hgeie, and all other bit positions shall be read-only zeros”), reads 0 after a write of all ones in reset-state.txt. So GEILEN is 0 under the lab’s flags, and bit 12 reading one is this QEMU’s choice, which the base rule allows. Writing bits 1 and 9, the two that chapter 5 delegates, reads back 0x1646: that is the value later chapters see, the reset 0x1444 plus those two.

This chapter writes neither register, so every trap that can occur here goes to M (the bits mideleg has set at reset are interrupt bits, and no interrupt is enabled) and the proof arrives where the shim can print it. The hinge turns in chapter 5. Exercise (d) delegates the proof’s cause and shows where it goes.

PMP, derived

A mode is only a mode if the memory system honours it. S and U see physical memory through page tables (chapter 4) once S turns paging on, but the page tables are S’s own, and a kernel that is in S can write any of them. The check below the page tables, one that S cannot rewrite, is the physical memory protection unit: “an optional physical memory protection (PMP) unit provides per-hart machine-mode control registers to allow physical memory access privileges (read, write, execute) to be specified for each physical memory region.” PMP’s defaults are the asymmetry this chapter needs. “In effect, PMP can grant permissions to S and U modes, which by default have none, and can revoke permissions from M-mode, which by default has full permissions.” So a hart with PMP that drops to S without programming it takes an instruction access fault at S’s first fetch, by the rule below. The check applies “to all accesses whose effective privilege mode is S or U, including instruction fetches and data accesses”, to “page-table accesses for virtual-address translation, for which the effective privilege mode is S”, and to M’s loads and stores while MPRV is set and MPP names S or U. It is checked “in parallel with” the physical memory attributes of the platform, and a violation is “always trapped precisely”: an access fault, never a page fault.

Top-of-range PMP regions over the board's address space The board's physical address space as four regions: ROM, MMIO, DRAM from 0x80000000 to 0x88000000, and the rest up to 4 GiB. Below, ember's single TOR entry from zero to 0x100000000 covers all four. In a second configuration entry 0 is off and only supplies the lower bound for entry 1, a TOR entry that covers DRAM alone; S and U accesses outside it fail. physical address space, regions not to scale ROM 0x1000 MMIO devices DRAM 0x80000000 to 0x88000000 above DRAM to 4 GiB entry 0: TOR, [0, pmpaddr0 << 2) = [0, 0x100000000), R W X this chapter's drop: one entry covers every region no entry covers these entry 1: TOR, R W X none the side run pmp-tor-pair: entry 0 is off and only gives entry 1 its bottom, pmpaddr0 = 0x80000000 >> 2; entry 1's top is pmpaddr1 = 0x88000000 >> 2. S and U fail outside entry 1. M still succeeds.

The registers. Each PMP entry is a configuration byte and an address register: “PMP entries are described by an 8-bit configuration register and one MXLEN-bit address register.” Up to 64 are architected, and “Implementations may implement zero, 16, or 64 PMP entries; the lowest-numbered PMP entries must be implemented first.” The CSRs are M-only. On RV64 the configuration bytes are packed eight to a register, in even-numbered registers only: pmpcfg0 holds the bytes for entries 0 to 7 (0x3a0), pmpcfg2 entries 8 to 15, and “For RV64, the odd-numbered configuration registers ... are illegal.” The address registers are pmpaddr0 through pmpaddr63 (0x3b0 and up). Each address register holds an address divided by four: “For RV64, each PMP address register encodes bits 55-2 of a 56-bit physical address.” The grain of PMP is four bytes at the finest (“regions as small as four bytes”), so the two low address bits carry nothing at that grain and the register leaves them out; a platform may specify a coarser grain, and every boundary this chapter uses is aligned to 128 MiB or more, so the grain does not matter here. So the value for the address 0x100000000 is 0x100000000 >> 2, which is 0x40000000.

The configuration byte. Its layout (specification Figure, PMP configuration register format): bit 0 R, bit 1 W, bit 2 X, bits 4:3 A, bits 6:5 reserved zero, bit 7 L. R, W and X permit the matching access when set; “When one of these bits is clear, the corresponding access type is denied.” The combination R=0, W=1 is reserved. A is the address-matching mode: 0 OFF (“Null region (disabled)”), 1 TOR (“Top of range”), 2 NA4 (a naturally aligned four-byte region), 3 NAPOT (a naturally aligned power-of-two region, 8 bytes or more, whose size is encoded in the address register’s low bits). The value 0x0f is 0000 1111: R, W and X set, A = 01 (bits 4:3), L clear. The register pmpcfg0 holds this byte as entry 0’s, in bits 7:0.

Top of range. A TOR entry has only a top address; its bottom is the previous entry’s address register. The specification: “If PMP entry i’s A field is set to TOR, the entry matches any address y such that pmpaddri−1 ≤ y < pmpaddri (irrespective of the value of pmpcfgi−1). If PMP entry 0’s A field is set to TOR, zero is used for the lower bound, and so it matches any address y<pmpaddr0.” The registers hold bytes divided by four, so in bytes the matched range is

4pmpaddri−1≤a<4pmpaddri,4\,\mathrm{pmpaddr}_{i-1} \le a < 4\,\mathrm{pmpaddr}_i,

and “If pmpaddri−1 ≥ pmpaddri and pmpcfgi.A=TOR, then PMP entry i matches no addresses.” Entry 0’s lower bound is address 0, which makes it the one-entry way to say “everything below this address.” ember’s entry is pmpaddr0 = 0x40000000 with TOR and R|W|X: every byte from 0 to just below 0x100000000. That covers the reset ROM at 0x1000, every device below DRAM (the exit device at 0x00100000, the CLINT (the timer block, chapter 6) at 0x02000000, the PLIC (the interrupt controller, chapter 5) at 0x0c000000, the UART at 0x10000000), and DRAM from 0x80000000, which with -m 128M ends at 0x88000000. NAPOT could describe this range too, by folding the size into the address register’s low bits; TOR needs only the top address, and an arbitrary range, as the pair in the figure shows, is a TOR entry above any other entry.

The matching rules. The specification: “PMP entries are statically prioritized. The lowest-numbered PMP entry that matches any byte of a memory operation determines whether that operation succeeds or fails. The matching PMP entry must match all bytes of a memory operation, or the operation fails, irrespective of the L, R, W, and X bits.” And the decision: “If a PMP entry matches all bytes of a memory operation, then the L, R, W, and X bits determine whether the operation succeeds or fails. If the L bit is clear and the privilege mode of the access is M, the operation succeeds. Otherwise, if the L bit is set or the privilege mode of the access is S or U, then the operation succeeds only if the R, W, or X bit corresponding to the access type is set.” The case that matters for a drop is no match: “If no PMP entry matches an M-mode memory operation, the operation succeeds. If no PMP entry matches an S-mode or U-mode memory operation, but at least one PMP entry is implemented, the operation fails.” And at the extreme: “If at least one PMP entry is implemented, but all PMP entries’ A fields are set to OFF, then all S-mode and U-mode memory accesses will fail.” The Reset section puts every writable entry in that state: “Writable PMP registers’ A and L fields are set to 0, unless the platform mandates a different reset value”. A fetch that fails raises “an instruction access-fault exception”; a load, a load access fault; a store or AMO (an atomic memory operation), a store access fault: causes 1, 5 and 7.

The L bit. “The L bit indicates that the PMP entry is locked, i.e., writes to the configuration register and associated address registers are ignored. Locked PMP entries remain locked until the hart is reset.” It also changes who the entry binds: “When the L bit is set, these permissions are enforced for all privilege modes. When the L bit is clear, any M-mode access matching the PMP entry will succeed; the R/W/X permissions apply only to S and U modes.” ember leaves L clear, so its entry grants S and U and constrains no one else.

Four side runs in labs/ch03/ex/ observe the rules on this board, and exercise (f) has their transcripts. Each differs from the lab by one pmp_open change.

One more rule the lab does not exercise and the code does not follow. After PMP changes, “when the PMP settings are modified, M-mode software must synchronize the PMP settings with the virtual memory system and any PMP or address-translation caches. This is accomplished by executing an SFENCE.VMA instruction with rs1=x0 and rs2=x0, after the PMP CSRs are written”, and the rule is scoped to harts with virtual memory (“If page-based virtual memory is not implemented, memory accesses check the PMP settings synchronously, so no SFENCE.VMA is needed.”). The hypervisor chapter adds, for a hart with the H extension (section 14.1.5.3): “Executing an HFENCE.GVMA instruction with rs1=x0 and rs2=x0 suffices to flush all G-stage or VS-stage address-translation cache entries that have cached PMP settings”. This hart has both, and pmp_open executes neither; the drop works here. The specification does not say the omission is safe on every hart, so a reader moving this drop to other hardware should add the fences (chapter 19’s guests are the case that needs the second); the lab cannot show a hart that fails without them.

What this board does that the specification leaves open

Every row is a board fact, from a capture, for QEMU 11.1.1 virt; none is architecture.

Fact Evidence Specification says
mstatus.MPP is U at reset lab capture M: mstatus MPP=U unspecified (only MIE and MPRV are reset)
stvec is 0 at reset; mtvec is 0 (chapter 2) delegate-illegal.txt unspecified
mideleg reads 0x1444 at reset (bit 12 included, with GEILEN 0); medeleg reads 0 delegation-probe.txt, reset-state.txt H forces bits 2, 6 and 10; bit 12 only if GEILEN is nonzero
mie is 0 and mip is 0x80 (machine timer pending), satp is 0, mcounteren is 0, MPV is 0 reset-state.txt unspecified (only hgatp.MODE and vsatp.MODE reset)
a mtvec write with a reserved MODE is dropped whole mtvec-warl.txt WARL

The PMP behaviour on this board, including the one place it departs from the specification’s sequence, is in exercise (f).

Walkthrough

The reference code is ember/priv.h, drop.c, mshim.S, mshim.c and main.c. Every listing below is shown as compiled at chapter 3; the files carry other chapters’ branches (the timer enable in drop_to_s, the delegation call in ch3_drop, S’s other entries in s_entry) that this chapter’s image does not contain.

The accessors

#define csr_read(csr)                                                          \
    ({                                                                         \
        unsigned long __v;                                                     \
        __asm__ volatile("csrr %0, " #csr : "=r"(__v));                        \
        __v;                                                                   \
    })

#define csr_write(csr, val)                                                    \
    __asm__ volatile("csrw " #csr ", %0" : : "rK"(val))

#define csr_set(csr, val)                                                      \
    __asm__ volatile("csrs " #csr ", %0" : : "rK"(val))

#define csr_clear(csr, val)                                                    \
    __asm__ volatile("csrc " #csr ", %0" : : "rK"(val))

/* mstatus RV64, privileged spec. Bit numbers are the spec's. */
#define MSTATUS_SIE   (1UL << 1)
#define MSTATUS_MIE   (1UL << 3)
#define MSTATUS_SPIE  (1UL << 5)
#define MSTATUS_MPIE  (1UL << 7)
#define MSTATUS_SPP   (1UL << 8)
#define MSTATUS_MPP_SHIFT 11
#define MSTATUS_MPP   (3UL << MSTATUS_MPP_SHIFT)
#define MSTATUS_MPP_U (0UL << MSTATUS_MPP_SHIFT)
#define MSTATUS_MPP_S (1UL << MSTATUS_MPP_SHIFT)
#define MSTATUS_MPP_M (3UL << MSTATUS_MPP_SHIFT)

The header comment in priv.h says why these are macros: “Inline asm, not functions: a call would need a stack we do not yet trust at every call site.” There is a deeper reason, which is the immediate. #csr pastes the register’s name into the assembly template, so csr_read(mstatus) becomes csrr %0, mstatus, and the assembler resolves mstatus to 0x300 in the instruction word. A function unsigned long csr_read(int csr) could not exist, since the number has no run-time form. volatile keeps the compiler from deleting or merging the instruction, and keeps it in order with other volatile asm. The output constraint "=r" returns the value in a register of the compiler’s choosing. csr_write takes "rK": a register, or a constant in the range of the K constraint (a 5-bit unsigned immediate), which the assembler encodes in the immediate form. csr_write(pmpcfg0, 0x0f) below is such a constant and becomes a csrwi; the large pmpaddr0 value goes through a register. csr_set and csr_clear are csrs and csrc, the atomic bit forms, which the file keeps for later chapters.

The constants beneath are mstatus’s fields at the positions of the table above. MSTATUS_MPP is 3UL << 11 (a mask, two bits), MSTATUS_MPP_U is 0UL << 11, MSTATUS_MPP_S is 1UL << 11 and MSTATUS_MPP_M is 3UL << 11. The UL suffix keeps the shifts 64 bits wide; it matters most for the bit-63 case that priv.h defines just outside this listing, MCAUSE_INT, since 1 << 63 overflows int. priv.h also defines the cause codes the shim compares, MCAUSE_ILLEGAL (2), MCAUSE_LOAD_PAGE (13) and MCAUSE_STORE_PAGE (15).

Turning PMP on

static void pmp_open(void)
{
    /*
     * This QEMU enforces PMP: with no matching entry, S/U fetches fail
     * (scause/mcause 1, instruction access fault). One TOR region from
     * 0 covering ROM, MMIO, and DRAM lets S run the image. Observed
     * on virt 11.1.1; the lab is the arbiter.
     */
    csr_write(pmpaddr0, 0x100000000UL >> 2);
    csr_write(pmpcfg0, 0x0f); /* R|W|X|TOR */
}

Two writes, each derived in the PMP section: pmpaddr0 = 0x100000000UL >> 2 is 0x40000000 and pmpcfg0 = 0x0f is entry 0’s byte. Entries 1 to 7 are the zero bytes above it, OFF, the state the hart reset them to. The order is address then configuration. Both writes happen in M before any lower mode runs, so the order cannot be observed here; address first is the order that never has an enabled entry holding a register’s unspecified reset value. The comment’s “This QEMU enforces PMP” is what the side runs observe, and “the lab is the arbiter” is all it claims about this board.

The drop

The shim’s stack, defined above drop_to_s in the same file:

/* Ch 8: the M shim's own stack. From ch 8 the timer can fire while U
 * runs, and the shim cannot push on U's sp — mscratch parks this
 * stack top exactly as sscratch parks the proc's kernel stack. */
static unsigned long mshim_stack[512]; /* 4 KiB, .bss, 16-byte aligned */
static unsigned long *const mshim_sp = &mshim_stack[512];

4 KiB of .bss (512 eight-byte words), and mshim_sp points one word past its end, the first push address for a stack that grows down. It exists for mscratch, which the next listing loads.

void drop_to_s(void (*entry)(void))
{
    unsigned long s;

    pmp_open();
    csr_write(mtvec, (unsigned long)mshim_entry);
    /* Unconditional: mshim_entry swaps through mscratch on every M
     * trap. From ch 8 the timer can fire while U runs; for traps from
     * S (ch 3–7) the shim now runs on its own stack instead of the
     * kernel's, which nothing in those chapters observes. */
    csr_write(mscratch, (unsigned long)mshim_sp);
    s = csr_read(mstatus);
    s = (s & ~MSTATUS_MPP) | MSTATUS_MPP_S;
    csr_write(mstatus, s);
    csr_write(mepc, (unsigned long)entry);
    __asm__ volatile("mret");
}

drop_to_s is a trap handler’s tail with the trap omitted. In order:

  • pmp_open(). Anywhere before the mret would do: M-mode needs no entry, and S’s first fetch needs it in place.
  • csr_write(mtvec, (unsigned long)mshim_entry). The handler address for every future trap into M. mshim_entry is 4-byte aligned, so its low two bits are zero, which selects MODE 0, Direct. It must be written before the mret, because the first trap, S’s probe, goes to whatever mtvec holds, and on this board mtvec resets to 0.
  • csr_write(mscratch, (unsigned long)mshim_sp). The swap target, written unconditionally.
  • s = csr_read(mstatus); s = (s & ~MSTATUS_MPP) | MSTATUS_MPP_S; csr_write(mstatus, s);. A read-modify-write of one field. The mask-then-or matters. Writing only MSTATUS_MPP_S would overwrite every other field with zero. Or-ing without clearing would leave MPP at 01 | old: if MPP held 11 (M), 11 | 01 is still 11 and the mret would stay in M. Clearing first makes the result independent of the old value, which on this board is 00.
  • csr_write(mepc, (unsigned long)entry). The address the mret will load into the program counter.
  • __asm__ volatile("mret"). The instruction. Items 1 to 7 above apply, and nothing in this function’s C continues, since the next instruction fetched is entry’s. volatile stops the compiler from deleting an instruction whose effect it cannot see. There is no "memory" clobber because drop_to_s makes no store that S must see; the stores it does make are CSR writes, and volatile asms keep their order.

The function has no return, and ch3_drop does not expect one.

The landing

mtvec points here:

    .section .text
    .align 2
    .globl mshim_entry
mshim_entry:
    csrrw   sp, mscratch, sp
    addi    sp, sp, -128
    sd      ra, 0(sp)
    sd      t0, 8(sp)
    sd      t1, 16(sp)
    sd      t2, 24(sp)
    sd      t3, 32(sp)
    sd      t4, 40(sp)
    sd      t5, 48(sp)
    sd      t6, 56(sp)
    sd      a0, 64(sp)
    sd      a1, 72(sp)
    sd      a2, 80(sp)
    sd      a3, 88(sp)
    sd      a4, 96(sp)
    sd      a5, 104(sp)
    sd      a6, 112(sp)
    sd      a7, 120(sp)
    csrr    a0, mcause
    csrr    a1, mtval
    call    mshim
    ld      ra, 0(sp)
    ld      t0, 8(sp)
    ld      t1, 16(sp)
    ld      t2, 24(sp)
    ld      t3, 32(sp)
    ld      t4, 40(sp)
    ld      t5, 48(sp)
    ld      t6, 56(sp)
    ld      a0, 64(sp)
    ld      a1, 72(sp)
    ld      a2, 80(sp)
    ld      a3, 88(sp)
    ld      a4, 96(sp)
    ld      a5, 104(sp)
    ld      a6, 112(sp)
    ld      a7, 120(sp)
    addi    sp, sp, 128
    csrrw   sp, mscratch, sp   /* the interrupted world's sp back */
    mret

Hardware has saved nothing, so this code does everything. csrrw sp, mscratch, sp is the swap: sp becomes the shim stack top that drop_to_s stored, and mscratch now holds the interrupted sp. addi sp, sp, -128 reserves sixteen eight-byte slots. The sixteen sd instructions save ra, t0 to t6, and a0 to a7: every caller-saved integer register. The shim calls into C, and the C ABI lets the callee clobber exactly those registers, so saving them preserves everything of the interrupted code that the shim’s own C could destroy. The callee-saved registers (s0 to s11) are the C function’s responsibility to restore, and sp is the swapped one. ra is in the list because call mshim overwrites it, and the interrupted code expects its own back.

csrr a0, mcause and csrr a1, mtval put the two trap words into the first two argument registers of the C call, after the saves (the saves read a0 and a1 first). call mshim is the C handler; for an exception it does not return, but chapter 6’s timer interrupt does, and the epilogue is written for that case: restore the sixteen registers, release the 128 bytes, csrrw sp, mscratch, sp once more to put the interrupted sp back and the shim stack top back in mscratch for the next trap, and mret. That mret has the same rules as the drop’s. Its mepc is the one the trap wrote, so it resumes where the trap left off; its MPP is whatever the trap wrote, so the mode is the interrupted one.

void mshim(unsigned long cause, unsigned long tval)
{
    unsigned long code = cause & ~MCAUSE_INT;
    int expected = 0;

    uart_puts("M: trap cause ");
    uart_puthex(code);
    if (code == MCAUSE_ILLEGAL) {
        uart_puts(" (illegal instruction) mtval=");
        uart_puthex(tval);
        uart_puts(" — S-mode proven\r\n");
    } else if (code == MCAUSE_STORE_PAGE || code == MCAUSE_LOAD_PAGE) {
        uart_puts(" (page fault) mtval=");
        uart_puthex(tval);
        uart_puts("\r\n");
    } else {
        uart_puts(" mtval=");
        uart_puthex(tval);
        uart_puts("\r\n");
    }

    expected = (code == MCAUSE_ILLEGAL);
    if (expected) {
        uart_puts("PASS\r\n");
        halt(0);
    }
    halt(1);
}

The C half. code = cause & ~MCAUSE_INT removes bit 63, so code is the exception code whether the trap was an interrupt or not. The page-fault branch is for chapter 4’s lab, which shares this shim. expected is 1 only for the cause this chapter’s lab expects, which prints PASS and calls halt(0); anything else is halt(1), a fail.

The shim prints S-mode proven for every illegal-instruction trap, whatever mode it came from, so the capture shows only that the hart was not allowed to execute the probe. Exercise (a) shows what tells S from U.

The S entry and the proof

static void s_entry(void)
{
    uart_puts("S: running\r\n");
    /* S-mode cannot read mhartid. The illegal instruction traps to M. */
    __asm__ volatile("csrr t0, mhartid");
    uart_puts("S: survived csrr mhartid\r\n");
    halt(1);
}

This is the code the drop lands on. The mret of the previous listing loaded pc with s_entry’s address and set the mode to S. uart_puts("S: running\r\n") is chapter 2’s console, reached through MMIO: the UART at 0x10000000 is in PMP entry 0’s range, and S-mode physical addresses are bus addresses here only because satp, the register that switches translation on (chapter 4’s subject), is 0, Bare (no translation), which this board resets it to (reset-state.txt; the specification does not reset satp, so a portable drop writes it before the mret). The probe is csrr t0, mhartid, 0xf14022f3, whose number’s bits 9:8 are 11, which no mode below M satisfies. It traps before it finishes, and the statements after it are the failure path.

static void ch3_drop(unsigned long hartid)
{
    unsigned long s = csr_read(mstatus);
    unsigned long mpp = (s & MSTATUS_MPP) >> MSTATUS_MPP_SHIFT;

    uart_puts("M: hart ");
    uart_puthex(hartid);
    uart_puts("\r\n");
    uart_puts("M: mstatus MPP=");
    uart_putc(mpp == 3 ? 'M' : mpp == 1 ? 'S' : 'U');
    uart_puts("\r\n");
    drop_to_s(s_entry);
}

ch3_drop runs in M. It reads mstatus before it changes anything and prints MPP as a letter, so the U in the capture is the hart’s own reset state and not something the drop wrote. drop_to_s(s_entry) does not return.

The capture

labs/ch03/capture.txt is the reference transcript:

ember: hart a0=0x0 mhartid=0x0
ember: .data survived: data_word = 0x600d
ember: .bss zero: bss_probe[0] = 0x0, bss_probe[31] = 0x0
M: hart 0x0
M: mstatus MPP=U
S: running
M: trap cause 0x2 (illegal instruction) mtval=0xf14022f3 — S-mode proven
PASS

The first three lines are chapter 2’s report, minus its symbol lines (they print link addresses, which belong to chapter 2 alone). M: hart 0x0 and M: mstatus MPP=U come from M before the drop. S: running is printed by the code the mret entered. The cause-2 line is the shim in M: the trap happened (the climb), mcause is 2 (illegal instruction), and mtval is 0xf14022f3 (this board’s choice to return the instruction bits). PASS is the shim’s verdict and halt(0).

Exercises

(a) Drop to U (MPP_U) instead of S, with the same probe. What do the last two lines of the transcript show, and what experiment tells S from U?

Answer

From labs/ch03/ex/drop-u.txt, the lines after M: mstatus MPP=U:

S: running
M: mstatus at trap 0xa00000000
M: mepc is the entry point 0x0
M: trap cause 0x2 (illegal instruction) mtval=0xf14022f3 — S-mode proven
PASS

The cause line is the lab’s, word for word, and S: running prints too, because the UART is reached by physical address and PMP entry 0 allows U as well as S. The capture cannot tell the two modes apart, and the shim’s S-mode proven is a label on any illegal instruction. The mode is in the trap-time mstatus the run adds: MPP is bits 12:11, and 0xa00000000 has them 00, a trap from U, against 0xa00000800 (01, S) in mpie-base.txt. An instruction that S may execute and U may not tells them directly. csrr t0, sstatus (number 0x100, bits 9:8 01) is that instruction. drop-s-sstatus.txt reads it from S and prints S: sstatus=0x200000000 (UXL, bits 33:32, is 2) before the lab’s probe traps; drop-u-sstatus.txt reads it from U and the trap is cause 0x2 ... mtval=0x100022f3 with no value printed.

(b) Set MPP to M (MPP_M), clear MPIE and set MPRV before the mret, and read mstatus in the code the mret enters. What does it hold, and why does csrr mhartid now succeed?

Answer

labs/ch03/ex/mret-to-m.txt:

M: mstatus before mret 0xa00021800
S: running
M: mstatus after mret 0xa00020080
S: survived csrr mhartid

The hart stayed in M, so the probe is a legal read in M and the lab’s failure line prints (no trap, no PASS). The values apply the xRET rule to this run. Before: MPP (12:11) is 11, MPIE (7) is 0, MPRV (17) is 1. After: MPP is 00, since xPP is set to “the least-privileged supported mode (U if U-mode is implemented, else M)”; MPIE (7) is 1, since “xPIE is set to 1”; MIE (3) is 0, the old MPIE, since “xIE is set to xPIE”; MPRV is still 1, since “If y≠M, xRET also sets MPRV=0” and y is M. Bit 39, MPV, is 0 throughout.

(c) A trap from S records MPIE and MPP in mstatus. What do they hold when the shim runs, with MPIE untouched, with it cleared, and with it set before the drop, and what does the mret do to MPRV? Then: mip reads 0x80 at reset. Why does no timer interrupt reach the hart in S, and what changes with mie.MTIE set?

Answer

The shim prints mstatus at the trap. Without any change before the drop (mpie-base.txt) and with MPIE cleared (mpie-clear.txt) it is 0xa00000800; with MPIE set before the mret (mpie-set.txt) it is 0xa00000880. MPP (12:11) is 01 in all three, the mode the trap came from. MPIE (bit 7) is the only difference: the mret copied MPIE into MIE, S ran with that MIE, and the trap copied MIE back into MPIE and cleared MIE (“xPIE is set to the value of xIE; xIE is set to 0”). That base and clear agree shows MPIE was 0 at reset on this board.

mret-mprv.txt is the MPRV half. It sets bit 17 with MPP=S: M: mstatus before mret 0xa00020800, and at the trap M: mstatus at trap 0xa00000800. A trap into M does not clear MPRV (the hypervisor chapter’s Trap Entry section lists the fields it writes (MPV, MPP, GVA, MPIE, MIE) and MPRV is not one of them), so the mret cleared it.

reset-state.txt prints M: mie 0x0 and M: mip 0x80: the machine timer interrupt (bit 7) is pending from reset, because mtimecmp is 0 (chapter 6). MIE is not what holds it off. While the hart is in S, “the current privilege mode has less privilege than M-mode”, so condition (a) of the rule in the mstatus section holds whatever MIE says. Condition (b) fails: bit 7 is not set in mie, which the Reset section leaves unspecified and this board resets to 0. mtie-set.txt sets that one bit before the mret, with MIE and MPIE still 0:

M: raw mcause 0x8000000000000007
M: mstatus at trap 0xa00000800
M: trap cause 0x7 mtval=0x0

The Interrupt bit (63) is set and the code is 7, the machine timer interrupt, taken from S (MPP 01) before S: running prints. The specification says the conditions are evaluated again immediately after an xRET, which is where it fires.

(d) Delegate cause 2 (csr_write(medeleg, 1UL << 2) before the mret) and run the lab. stvec has not been written. Where does the trap go, and what does each side see? Then probe which delegation bits this board has: write all ones to medeleg and mideleg and read them back.

Answer

labs/ch03/ex/delegate-illegal.txt, from the line the run adds before the drop:

M: stvec 0x0
S: running
M: mstatus at trap 0xa00000900
M: mepc 0x0
M: scause 0x2
M: stval 0xf14022f3
M: sstatus 0x200000100
M: trap cause 0x1 mtval=0x0

The probe’s illegal instruction occurred in S, and bit 2 of medeleg sends it to S: scause is 2, stval is the instruction word, sstatus has SPP (bit 8) set, a trap from S, and the program counter goes to stvec, which this board resets to 0 (the Reset section leaves it unspecified). That is the delegated hop, read afterwards from M. There is no S handler at address 0, so the next event is an instruction access fault at pc = 0, cause 1, raised in S (MPP is 01 in the trap-time mstatus, and SPP, bit 8, is still set from the first trap) with mepc = 0. Bit 1 of medeleg is clear, so cause 1 is not delegated and goes to M, where the shim prints it: a fail, not PASS. The fault at 0 is not PMP, since entry 0 grants S R, W and X for every address below 4 GiB; chapter 2’s exercise (b) shows M faulting at 0 the same way with a zero mtvec. The transcript also shows the register split of the delegation section: the first trap wrote scause and stval; the second wrote mepc and mtval.

The probe, delegation-probe.txt (its 0x1444 reset value is in the Mechanism section):

M: medeleg at reset 0x0
M: mideleg at reset 0x1444
M: medeleg after all ones 0xf4b7ff
M: mideleg after all ones 0x3666
M: mideleg after writing bits 1 and 9 0x1646

0xf4b7ff has bits 0 to 10, 12, 13, 15, 18 and 20 to 23 set. Bits 11 and 16 are clear, which the specification requires (“medeleg[11] is read-only zero”, “medeleg[16] is read-only zero”). The causes: 0 to 9, 12, 13 and 15 are the ones in the Mechanism table; 10 is the environment call from VS-mode; 18 is the software-check exception; 20, 21, 22 and 23 are the instruction guest-page, load guest-page, virtual-instruction and store/AMO guest-page exceptions (the hypervisor chapter’s cause table, 14.1.6.1). mideleg reads 0x3666, bits 1, 2, 5, 6, 9, 10, 12 and 13 (13 is the counter-overflow interrupt, outside this book), with the machine-level bits 3, 7 and 11 not writable. Writing only bits 1 and 9 reads back 0x1646.

(e) Decode, bit by bit, the misa value misa.txt prints, and say what its write test shows. Which misa letter is clear although the device tree’s ISA string lists extensions it covers?

Answer

misa.txt:

M: misa 0x80000000001411ad MXL 0x2 extensions ACDFHIMSU
M: after clearing H and M 0x80000000001411ad

Bits 63:62 are 10, so MXL is 2 (64-bit). The low bits 0x1411ad are 0001 0100 0001 0001 1010 1101, which sets bits 0, 2, 3, 5, 7, 8, 12, 18 and 20: A, C, D, F, H, I, M, S, U. The second line is after csrc misa with bits 7 and 12: the register is unchanged, so clearing H and M is ignored on this board, which the specification allows (“a WARL field”). Bit 1, B, is clear in misa although the string lists zba, zbb and zbs. The specification covers it: “When the “B” bit is 0, it indicates that the implementation might not support” one or more of those three, so a clear bit is not proof of absence. mmu-type in isa-string.txt is riscv,sv57, which chapter 4 sets beside the Sv39 the lab uses.

(f) Change pmp_open four ways, one at a time: drop the X bit; use the pair “entry 0 OFF at 0x80000000 >> 2, entry 1 TOR at 0x88000000 >> 2”; delete both writes; and replace them with one entry that matches nothing S touches (an NA4 entry at address 0 with no R, W or X). For each, what does S see first, which cause and which mtval, and from which mode is the trap taken?

Answer

From the four transcripts in labs/ch03/ex/:

pmp-no-exec.txt   M: mstatus at trap 0xa00000800
                  M: mepc is the entry point 0x1
                  M: trap cause 0x1 mtval>>28=0x8
pmp-na4.txt       M: mstatus at trap 0xa00000800
                  M: mepc is the entry point 0x1
                  M: trap cause 0x1 mtval>>28=0x8
pmp-tor-pair.txt  M: mstatus at trap 0xa00000800
                  M: mepc is the entry point 0x0
                  M: trap cause 0x5 mtval=0x10000005
pmp-none.txt      M: mstatus at trap 0xa00001800
                  M: mepc is the mret instruction 0x1
                  M: mepc is the entry point 0x0
                  M: trap cause 0x1 mtval=0x0

No X, and the NA4 entry that matches nothing: S’s first instruction fetch is an instruction access fault (cause 1), at an address in DRAM (mtval>>28 is 8; the run prints the shift so the checkout path does not matter), taken from S (MPP 01), at the entry point (mepc equals it). S: running never prints. The first is a permission failure, the second the no-match rule with an entry implemented and active. The pair: entry 1 covers DRAM, so S’s fetches succeed; its first access outside is the line-status poll in uart_puts, a load, so the fault is cause 5 and mtval is the UART’s register address 0x10000005. M’s earlier prints, which used the UART with no entry covering it, succeeded. None: the specification says all entries OFF fails all S and U accesses, which puts the fault at S’s first fetch. This board takes it in M (MPP 11), on the mret itself: the run places a label on the mret and prints 1 for mepc equal to it, 0 for mepc equal to the entry point, and mtval is 0. S fetches nothing. All are access faults from PMP, not page faults, and none prints PASS.

(g) Which of csrr t0, satp, csrw sscratch, t0, csrr t0, mcycle, csrw time, t0, csrr t0, cycle and mret can S-mode execute without a trap? Decide from the CSR numbers and the rules, then check against reset-state.txt, s-cycle.txt, s-mret.txt and write-ro.txt.

Answer

The numbers: satp 0x180 (bits 11:10 00, 9:8 01: read/write, S and up); sscratch 0x140 (00, 01: the same); mcycle 0xb00 (10, 11: read/write, M only); time 0xc01 (11, 00: read-only, U and up); cycle 0xc00 (the same). So by encoding S may use satp and sscratch and may not touch mcycle; csrw time, t0 is csrrw x0, 0xc01, t0, a write to a read-only register, which “raise[s] illegal-instruction exceptions” from any mode. satp has a second control, mstatus.TVM, which makes S’s satp access trap when set; bit 20 is clear in every mstatus the runs print. cycle has one too: “When the CY, TM, IR, or HPMn bit in the mcounteren register is clear, attempts to read the cycle, time, instret, or hpmcountern register while executing in S-mode or U-mode will cause an illegal-instruction exception.” reset-state.txt prints M: mcounteren 0x0 and M: satp 0x0, and s-cycle.txt shows the read trapping from S: mtval=0xc00022f3, cause 2. mret is illegal from S: s-mret.txt, mtval=0x30200073, from the rule “Attempting to execute an xRET instruction in a mode less privileged than x will raise an illegal-instruction exception.” The write rule applies in M too: write-ro.txt has M-mode executing csrw mhartid, zero (csrrw x0, 0xf14, x0) and taking cause 2 with mtval=0xf1401073.

Lab

make lab CH=03
make lab CH=03 IMPL=mine
make ex CH=03

The reference transcript is the one above. IMPL=mine stubs drop_to_s to return at once, so S never runs, main halts with failure, and the capture diff fails on the missing lines until the reader writes the drop. make ex CH=03 reruns every side run in a scratch copy of ember/ and diffs each transcript against the committed one in labs/ch03/ex/; it is not part of make check. The transcripts are from QEMU 11.1.1 and print no link addresses; where an address would appear (pmp-no-exec) the run prints a shifted value. labs/ch03/ex/isa-string.sh writes isa-string.txt, the ISA string the device tree hands a kernel, which exercise (e) sets beside misa; it overwrites that file and make ex does not diff it.

If the reference traps with cause 1 instead of cause 2, PMP is the first suspect: no TOR entry, pmpcfg0 without X, or the entry written after the mret. Exercise (f) says how to read the mstatus printed with a cause-1 trap.

Further reading

results matching ""

    No results matching ""