RV32/64 Privileged Architecture

RISC-V defines a hierarchy of privilege modes to govern hardware access, isolate software tasks, and manage system events. Execution environments separate fundamental hardware configuration from general-purpose operating systems and untrusted application code.

  • Machine Mode (M-mode): The highest and only mandatory privilege level, executing the most trusted code with full, unfettered access to memory, I/O, and low-level system configuration.
  • Supervisor Mode (S-mode): An optional, moderately privileged level designed for operating systems, providing virtual memory and multitasking support.
  • User Mode (U-mode): The least privileged level, restricting access to system control registers and restricting memory capabilities to execute untrusted applications safely.

These tiered privilege levels require a foundational environment with absolute hardware access to bootstrap and control the system, a role fulfilled by Machine mode.

Machine Mode (M-mode) Exceptions and Interrupts

Machine mode intercepts and processes all unusual runtime events, broadly categorized into exceptions and interrupts. All RISC-V exceptions are precise: instructions prior to the exception complete execution, while the faulting instruction and subsequent instructions do not.

  • Synchronous Exceptions: Triggered by instruction execution.
    • Access Faults: Attempting illegal physical memory operations (e.g., writing to ROM).
    • Breakpoints: Executing an ebreak instruction or matching a debug trigger.
    • Environment Calls: Executing an ecall instruction to request services from the execution environment.
    • Illegal Instructions: Decoding an invalid opcode or accessing a privileged register from an unprivileged mode.
    • Misaligned Addresses: Accessing memory boundaries not divisible by the access size.
  • Asynchronous Interrupts: Triggered by external events.
    • Software Interrupts: Interprocessor interrupts triggered by storing to memory-mapped registers.
    • Timer Interrupts: Raised when the time comparator (mtimecmp) exceeds the real-time counter (mtime).
    • External Interrupts: Raised by a platform-level interrupt controller connected to external devices.

Handling these precise exceptions and asynchronous interrupts relies on a dedicated set of Control and Status Registers (CSRs).

  • Exception-Handling CSRs:

    • mtvec (Trap Vector): Stores the exception handler base address and vector mode. If the MODE bit is 1, asynchronous interrupts compute the handler address as .
    • mepc (Exception PC): Stores the address of the faulting instruction or the resumption point.
    • mcause (Exception Cause): Encodes the exception type. The most-significant bit is 1 for interrupts and 0 for synchronous exceptions.
    • mtval (Trap Value): Holds supplemental data, such as a faulting memory address or an illegal instruction opcode.
    • mstatus (Machine Status): Tracks global system state, including the global interrupt enable (MIE) and previous privilege mode (MPP).
    • mie and mip: Track enabled and pending interrupts mapped identically to the mcause exception codes.
    • mscratch: Provides temporary storage, typically pointing to an in-memory save area for context switching.
  • Hardware State Transitions on Exception:

    1. The mepc captures the current PC; the PC updates to mtvec.
    2. mcause and mtval populate with the event code and faulting details.
    3. mstatus.MIE is cleared to disable interrupts; the previous MIE state moves to mstatus.MPIE.
    4. The pre-exception privilege mode shifts into mstatus.MPP, and execution elevates to M-mode.
  • Hardware State Transitions on Return (mret):

    1. The PC restores from mepc.
    2. The global interrupt enable mstatus.MIE restores from mstatus.MPIE.
    3. The privilege level degrades to the mode encoded in mstatus.MPP.
  • Wait For Interrupt (wfi):

    • Idles the processor until an enabled interrupt becomes pending.
    • If executed when mstatus.MIE=0, a pending enabled interrupt resumes execution at the instruction following wfi rather than jumping to mtvec.

While Machine mode governs global hardware execution and precise traps, executing untrusted application code necessitates a restricted environment isolated from system-critical hardware.

User Mode (U-mode) and Process Isolation

User mode executes application software subject to access restrictions enforced by Machine mode. Attempting to execute an M-mode instruction (like mret) or access an M-mode CSR generates an illegal instruction exception, immediately returning control to M-mode.

  • Physical Memory Protection (PMP):
    • M-mode utilizes PMP CSRs to specify bounded physical memory regions that U-mode may access.
    • Memory accesses strictly evaluate against PMP address registers (pmpaddr0 to pmpaddrN).
    • If a physical address falls within a PMP region, the corresponding pmpcfg register dictates permissions.
  • PMP Configuration Registers (pmpcfg):
    • R, W, X bits: Grant read, write, and execute permissions independently.
    • A field (Mode): Disables or enables the PMP region matching logic.
    • L field (Lock): Locks the configuration until the next system reset.

Physical Memory Protection effectively isolates contiguous physical regions for specific tasks, but dynamic, fragmented, and paged multitasking environments require the advanced memory abstractions provided by Supervisor mode.

Supervisor Mode (S-mode) and Exception Delegation

Supervisor mode provides the necessary abstractions for modern operating systems while remaining subject to PMP boundaries and M-mode authority.

To eliminate the overhead of M-mode intercepting OS-bound exceptions, RISC-V implements hardware exception delegation. Delegation bypasses M-mode, transferring control directly to S-mode.

  • Exception Delegation CSRs:

    • mideleg (Machine Interrupt Delegation): Routes specific asynchronous interrupts directly to S-mode handlers.
    • medeleg (Machine Exception Delegation): Routes specific synchronous exceptions directly to S-mode handlers.
    • Exceptions never downgrade privilege levels. An M-mode exception resolves in M-mode, regardless of delegation bits.
  • S-mode Trap Handling:

    • S-mode mirrors the M-mode trap architecture using a subset of independent CSRs: sepc, stvec, scause, sscratch, stval, and sstatus.
    • sie and sip represent strictly the subset of interrupts explicitly delegated by mideleg.
    • Exceptions delegated to S-mode automatically update the S-mode CSRs, disable S-mode interrupts (sstatus.SIE=0), log the previous mode (sstatus.SPP), and set the PC to stvec.
    • The sret instruction reverses the state, returning control to the interrupted application.

Delegated execution management in Supervisor mode relies on isolating and virtualizing process memory, accomplished through an integrated page-based virtual memory system.

Page-Based Virtual Memory

Supervisor mode manages multitasking isolation by mapping Virtual Addresses (VA) to Physical Addresses (PA) using hierarchical, fixed-size page tables.

  • The satp CSR:

    • MODE: Enables paging and selects the tree depth (Sv32, Sv39, Sv48) or disables translation (Bare).
    • ASID (Address Space Identifier): Tags translations to specific processes, reducing context switch overhead.
    • PPN (Physical Page Number): Stores the physical base address of the root page table.
  • Page Table Entry (PTE) Structure:

    • V (Valid): Unset bits trigger a page-fault exception upon traversal.
    • R, W, X (Permissions): Define read, write, and execute rights. If all are 0, the PTE points to a subsequent page table level. Otherwise, it is a terminal leaf node.
    • U (User): Grants (1) or restricts (0) access to U-mode processes.
    • G (Global): Signals that the mapping spans all virtual address spaces.
    • A (Accessed) & D (Dirty): Track read/execute operations and write operations to facilitate OS swap algorithms.
    • PPN: The translated physical base address of the target page.

Virtual Addressing Schemes

RISC-V parameterizes its page-table structures based on the register width (XLEN) to ensure a single page table exactly matches the base page size (4 KiB), optimizing OS memory allocation.

  • Sv32 (RV32 Paging):
    • Supports a 32-bit VA space mapped to a 34-bit PA space.
    • Uses 4-byte PTEs, resulting in a radix 2-level tree structure.
    • Virtual structure: 4 MiB megapages subdivided into 4 KiB base pages.
  • Sv39 (RV64 Paging):
    • Supports a 39-bit VA space mapped to a 56-bit PA space.
    • Uses 8-byte PTEs, resulting in a radix 3-level tree structure.
    • Virtual structure: 1 GiB gigapages subdivided into 2 MiB megapages, subdivided into 4 KiB base pages.
    • Bits 63–39 of the 64-bit VA must strictly duplicate bit 38. Violations trigger an access exception, preserving high-order bits for future ISA expansion.

Translation Caching and Coherence

To overcome the latency of multi-level page table traversals, hardware implementations utilize an address-translation cache (Translation Lookaside Buffer, or TLB).

  • sfence.vma Instruction:
    • Because the TLB does not automatically snoop memory for OS-driven page table alterations, S-mode software must explicitly invalidate stale entries.
    • sfence.vma orders previous page table stores with subsequent virtual address translations.
    • Accepts optional virtual address and ASID registers to surgically flush specific cached translations, or flushes the entire TLB if operands are omitted.
    • Multiprocessor coherence requires a “TLB shootdown” via software interprocessor interrupts to synchronize sfence.vma executions across parallel harts.

The interplay between virtual address translation, address-translation caches, and TLB coherence completes the hardware mechanisms necessary for executing high-performance, isolated software stacks.