Contributors to all versions of the spec in alphabetical order (please contact editors to suggest corrections): Krste Asanović, Peter Ashenden, Rimas Avižienis, Jacob Bachmeyer, Allen J. Baum, Jonathan Behrens, Paolo Bonzini, Ruslan Bukin, Christopher Celio, Chuanhua Chang, David Chisnall, Anthony Coulter, Palmer Dabbelt, Monte Dalrymple, Paul Donahue, Greg Favor, Dennis Ferguson, Marc Gauthier, Andy Glew, Gary Guo, Mike Frysinger, John Hauser, David Horner, Olof Johansson, David Kruckemyer, Yunsup Lee, Daniel Lustig, Andrew Lutomirski, Prashanth Mundkur, Jonathan Neuschäfer, Rishiyur Nikhil, Stefan O’Rear, Albert Ou, John Ousterhout, David Patterson, Dmitri Pavlov, Kade Phillips, Josh Scheid, Colin Schmidt, Michael Taylor, Wesley Terpstra, Matt Thomas, Tommy Thorn, Ray VanDeWalker, Megan Wachs, Steve Wallach, Andrew Waterman, Claire Wolf, and Reinoud Zandijk..

This document is released under a Creative Commons Attribution 4.0 International License.

This document is a derivative of the RISC-V privileged specification version 1.9.1 released under following license: ©2010-2017 Andrew Waterman, Yunsup Lee, Rimas Avižienis, David Patterson, Krste Asanović. Creative Commons Attribution 4.0 International License.

Preface

Preface to Version 20240528

This document describes the RISC-V privileged architecture. This release, version 20240528, contains the following versions of the RISC-V ISA modules:

Module Version Status

Machine ISA
Smstateen Extension
Smcsrind/Sscsrind Extension
Smepmp
Smcntrpmf
Smrnmi Extension
Smcdeleg
Smdbltrp
Supervisor ISA
Svade Extension
Svnapot Extension
Svpbmt Extension
Svinval Extension
Svadu Extension
Sstc
Sscofpmf
Ssdbltrp
Hypervisor ISA
Shlcofideleg

1.13
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.13
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
0.1

Draft
Ratified
Ratified
Ratified
Ratified
Ratified
Ratified
Draft
Draft
Ratified
Ratified
Ratified
Ratified
Ratified
Ratified
Ratified
Draft
Ratified
Draft

The following changes have been made since version 1.12 of the Machine and Supervisor ISAs, which, while not strictly backwards compatible, are not anticipated to cause software portability problems in practice:

  • Redefined misa.MXL to be read-only, making MXLEN a constant.

  • Added the constraint that SXLEN≥UXLEN.

Additionally, the following compatible changes have been made to the Machine and Supervisor ISAs since version 1.12:

  • Defined the misa.B field to reflect that the B extension has been implemented.

  • Defined the misa.V field to reflect that the V extension has been implemented.

  • Defined the RV32-only medelegh and hedelegh CSRs.

  • Defined the misaligned atomicity granule PMA, superseding the proposed Zam extension.

  • Allocated interrupt 13 for Sscofpmf LCOFI interrupt.

  • Defined hardware error and software check exception codes.

  • Specified synchronization requirements when changing the PBMTE fields in menvcfg and henvcfg.

  • Exposed count-overflow interrups to VS-mode via the Shlcofideleg extension.

Finally, the following clarifications and document improvments have been made since the last document release:

  • Transliterated the document from LaTeX into AsciiDoc.

  • Included all ratified extensions through March 2024.

  • Clarified that "platform- or custom-use" interrupts are actually "platform-use interrupts", where the platform can choose to make some custom.

  • Clarified semantics of explicit accesses to CSRs wider than XLEN bits.

  • Clarified that MXLEN≥SXLEN.

  • Clarified that WFI is not a HINT instruction.

  • Clarified that VS-stage page-table accesses set G-stage A/D bits.

  • Clarified ordering rules when PBMT=IO is used on main-memory regions.

  • Clarified ordering rules for hardware A/D bit updates.

  • Clarified that, for a given exception cause, xtval might sometimes be set to a nonzero value but sometimes not.

  • Clarified exception behavior of unimplemented or inaccessible CSRs.

  • Clarified that Svpbmt allows implementations to override additional PMAs.

  • Replaced the concept of vacant memory regions with inaccessible memory or I/O regions.

  • Clarified that timer and count-overflow interrupts' arrival in interrupt-pending registers is not immediate.

Preface to Version 20211203

This document describes the RISC-V privileged architecture. This release, version 20211203, contains the following versions of the RISC-V ISA modules:

Module Version Status

Machine ISA
Supervisor ISA
Svnapot Extension
Svpbmt Extension
Svinval Extension
Hypervisor ISA

1.12
1.12
1.0
1.0
1.0
1.0

Ratified
Ratified
Ratified
Ratified
Ratified
Ratified

The following changes have been made since version 1.11, which, while not strictly backwards compatible, are not anticipated to cause software portability problems in practice:

  • Changed MRET and SRET to clear mstatus.MPRV when leaving M-mode.

  • Reserved additional satp patterns for future use.

  • Stated that the scause Exception Code field must implement bits 4–0 at minimum.

  • Relaxed I/O regions have been specified to follow RVWMO. The previous specification implied that PPO rules other than fences and acquire/release annotations did not apply.

  • Constrained the LR/SC reservation set size and shape when using page-based virtual memory.

  • PMP changes require an SFENCE.VMA on any hart that implements page-based virtual memory, even if VM is not currently enabled.

  • Allowed for speculative updates of page table entry A bits.

  • Clarify that if the address-translation algorithm non-speculatively reaches a PTE in which a bit reserved for future standard use is set, a page-fault exception must be raised.

Additionally, the following compatible changes have been made since version 1.11:

  • Removed the N extension.

  • Defined the mandatory RV32-only CSR mstatush, which contains most of the same fields as the upper 32 bits of RV64’s mstatus.

  • Defined the mandatory CSR mconfigptr, which if nonzero contains the address of a configuration data structure.

  • Defined optional mseccfg and mseccfgh CSRs, which control the machine’s security configuration.

  • Defined menvcfg, henvcfg, and senvcfg CSRs (and RV32-only menvcfgh and henvcfgh CSRs), which control various characteristics of the execution environment.

  • Designated part of SYSTEM major opcode for custom use.

  • Permitted the unconditional delegation of less-privileged interrupts.

  • Added optional big-endian and bi-endian support.

  • Made priority of load/store/AMO address-misaligned exceptions implementation-defined relative to load/store/AMO page-fault and access-fault exceptions.

  • PMP reset values are now platform-defined.

  • An additional 48 optional PMP registers have been defined.

  • Slightly relaxed the atomicity requirement for A and D bit updates performed by the implementation.

  • Clarify the architectural behavior of address-translation caches

  • Added Sv57 and Sv57x4 address translation modes.

  • Software breakpoint exceptions are permitted to write either 0 or the pc to xtval.

  • Clarified that bare S-mode need not support the SFENCE.VMA instruction.

  • Specified relaxed constraints for implicit reads of non-idempotent regions.

  • Added the Svnapot Standard Extension, along with the N bit in Sv39, Sv48, and Sv57 PTEs.

  • Added the Svpbmt Standard Extension, along with the PBMT bits in Sv39, Sv48, and Sv57 PTEs.

  • Added the Svinval Standard Extension and associated instructions.

Finally, the hypervisor architecture proposal has been extensively revised.

Preface to Version 1.11

This is version 1.11 of the RISC-V privileged architecture. The document contains the following versions of the RISC-V ISA modules:

Module Version Status

Machine ISA
Supervisor ISA
Hypervisor ISA

1.11
1.11
0.3

Ratified
Ratified
Draft

Changes from version 1.10 include:

  • Moved Machine and Supervisor spec to Ratified status.

  • Improvements to the description and commentary.

  • Added a draft proposal for a hypervisor extension.

  • Specified which interrupt sources are reserved for standard use.

  • Allocated some synchronous exception causes for custom use.

  • Specified the priority ordering of synchronous exceptions.

  • Added specification that xRET instructions may, but are not required to, clear LR reservations if A extension present.

  • The virtual-memory system no longer permits supervisor mode to execute instructions from user pages, regardless of the SUM setting.

  • Clarified that ASIDs are private to a hart, and added commentary about the possibility of a future global-ASID extension.

  • SFENCE.VMA semantics have been clarified.

  • Made the mstatus.MPP field WARL, rather than WLRL.

  • Made the unused xip fields WPRI, rather than WIRI.

  • Made the unused misa fields WARL, rather than WIRI.

  • Made the unused pmpaddr and pmpcfg fields WARL, rather than WIRI.

  • Required all harts in a system to employ the same PTE-update scheme as each other.

  • Rectified an editing error that misdescribed the mechanism by which mstatus.xIE is written upon an exception.

  • Described scheme for emulating misaligned AMOs.

  • Specified the behavior of the misa and xepc registers in systems with variable IALIGN.

  • Specified the behavior of writing self-contradictory values to the misa register.

  • Defined the mcountinhibit CSR, which stops performance counters from incrementing to reduce energy consumption.

  • Specified semantics for PMP regions coarser than four bytes.

  • Specified contents of CSRs across XLEN modification.

  • Moved PLIC chapter into its own document.

Preface to Version 1.10

This is version 1.10 of the RISC-V privileged architecture proposal. Changes from version 1.9.1 include:

  • The previous version of this document was released under a Creative Commons Attribution 4.0 International License by the original authors, and this and future versions of this document will be released under the same license.

  • The explicit convention on shadow CSR addresses has been removed to reclaim CSR space. Shadow CSRs can still be added as needed.

  • The mvendorid register now contains the JEDEC code of the core provider as opposed to a code supplied by the Foundation. This avoids redundancy and offloads work from the Foundation.

  • The interrupt-enable stack discipline has been simplified.

  • An optional mechanism to change the base ISA used by supervisor and user modes has been added to the mstatus CSR, and the field previously called Base in misa has been renamed to MXL for consistency.

  • Clarified expected use of XS to summarize additional extension state status fields in mstatus.

  • Optional vectored interrupt support has been added to the mtvec and stvec CSRs.

  • The SEIP and UEIP bits in the mip CSR have been redefined to support software injection of external interrupts.

  • The mbadaddr register has been subsumed by a more general mtval register that can now capture bad instruction bits on an illegal instruction fault to speed instruction emulation.

  • The machine-mode base-and-bounds translation and protection schemes have been removed from the specification as part of moving the virtual memory configuration to sptbr (now satp). Some of the motivation for the base and bound schemes are now covered by the PMP registers, but space remains available in mstatus to add these back at a later date if deemed useful.

  • In systems with only M-mode, or with both M-mode and U-mode but without U-mode trap support, the medeleg and mideleg registers now do not exist, whereas previously they returned zero.

  • Virtual-memory page faults now have mcause values distinct from physical-memory access faults. Page-fault exceptions can now be delegated to S-mode without delegating exceptions generated by PMA and PMP checks.

  • An optional physical-memory protection (PMP) scheme has been proposed.

  • The supervisor virtual memory configuration has been moved from the mstatus register to the sptbr register. Accordingly, the sptbr register has been renamed to satp (Supervisor Address Translation and Protection) to reflect its broadened role.

  • The SFENCE.VM instruction has been removed in favor of the improved SFENCE.VMA instruction.

  • The mstatus bit MXR has been exposed to S-mode via sstatus.

  • The polarity of the PUM bit in sstatus has been inverted to shorten code sequences involving MXR. The bit has been renamed to SUM.

  • Hardware management of page-table entry Accessed and Dirty bits has been made optional; simpler implementations may trap to software to set them.

  • The counter-enable scheme has changed, so that S-mode can control availability of counters to U-mode.

  • H-mode has been removed, as we are focusing on recursive virtualization support in S-mode. The encoding space has been reserved and may be repurposed at a later date.

  • A mechanism to improve virtualization performance by trapping S-mode virtual-memory management operations has been added.

  • The Supervisor Binary Interface (SBI) chapter has been removed, so that it can be maintained as a separate specification.

Preface to Version 1.9.1

This is version 1.9.1 of the RISC-V privileged architecture proposal. Changes from version 1.9 include:

  • Numerous additions and improvements to the commentary sections.

  • Change configuration string proposal to be use a search process that supports various formats including Device Tree String and flattened Device Tree.

  • Made misa optionally writable to support modifying base and supported ISA extensions. CSR address of misa changed.

  • Added description of debug mode and debug CSRs.

  • Added a hardware performance monitoring scheme. Simplified the handling of existing hardware counters, removing privileged versions of the counters and the corresponding delta registers.

  • Fixed description of SPIE in presence of user-level interrupts.

1. Introduction

This document describes the RISC-V privileged architecture, which covers all aspects of RISC-V systems beyond the unprivileged ISA, including privileged instructions as well as additional functionality required for running operating systems and attaching external devices.

Commentary on our design decisions is formatted as in this paragraph, and can be skipped if the reader is only interested in the specification itself.


We briefly note that the entire privileged-level design described in this document could be replaced with an entirely different privileged-level design without changing the unprivileged ISA, and possibly without even changing the ABI. In particular, this privileged specification was designed to run existing popular operating systems, and so embodies the conventional level-based protection model. Alternate privileged specifications could embody other more flexible protection-domain models. For simplicity of expression, the text is written as if this was the only possible privileged architecture.

1.1. RISC-V Privileged Software Stack Terminology

This section describes the terminology we use to describe components of the wide range of possible privileged software stacks for RISC-V.

Figure 1 shows some of the possible software stacks that can be supported by the RISC-V architecture. The left-hand side shows a simple system that supports only a single application running on an application execution environment (AEE). The application is coded to run with a particular application binary interface (ABI). The ABI includes the supported user-level ISA plus a set of ABI calls to interact with the AEE. The ABI hides details of the AEE from the application to allow greater flexibility in implementing the AEE. The same ABI could be implemented natively on multiple different host OSs, or could be supported by a user-mode emulation environment running on a machine with a different native ISA.

Our graphical convention represents abstract interfaces using black boxes with white text, to separate them from concrete instances of components implementing the interfaces.

privimps
Figure 1. Different implementation stacks supporting various forms of privileged execution.

The middle configuration shows a conventional operating system (OS) that can support multiprogrammed execution of multiple applications. Each application communicates over an ABI with the OS, which provides the AEE. Just as applications interface with an AEE via an ABI, RISC-V operating systems interface with a supervisor execution environment (SEE) via a supervisor binary interface (SBI). An SBI comprises the user-level and supervisor-level ISA together with a set of SBI function calls. Using a single SBI across all SEE implementations allows a single OS binary image to run on any SEE. The SEE can be a simple boot loader and BIOS-style IO system in a low-end hardware platform, or a hypervisor-provided virtual machine in a high-end server, or a thin translation layer over a host operating system in an architecture simulation environment.

Most supervisor-level ISA definitions do not separate the SBI from the execution environment and/or the hardware platform, complicating virtualization and bring-up of new hardware platforms.

The rightmost configuration shows a virtual machine monitor configuration where multiple multiprogrammed OSs are supported by a single hypervisor. Each OS communicates via an SBI with the hypervisor, which provides the SEE. The hypervisor communicates with the hypervisor execution environment (HEE) using a hypervisor binary interface (HBI), to isolate the hypervisor from details of the hardware platform.

The ABI, SBI, and HBI are still a work-in-progress, but we are now prioritizing support for Type-2 hypervisors where the SBI is provided recursively by an S-mode OS.

Hardware implementations of the RISC-V ISA will generally require additional features beyond the privileged ISA to support the various execution environments (AEE, SEE, or HEE).

1.2. Privilege Levels

At any time, a RISC-V hardware thread (hart) is running at some privilege level encoded as a mode in one or more CSRs (control and status registers). Three RISC-V privilege levels are currently defined as shown in Table 1.

Table 1. RISC-V privilege levels.
Level Encoding Name Abbreviation

0
1
2
3

00
01
10
11

User/Application
Supervisor
Reserved
Machine

U
S
 
M

Privilege levels are used to provide protection between different components of the software stack, and attempts to perform operations not permitted by the current privilege mode will cause an exception to be raised. These exceptions will normally cause traps into an underlying execution environment.

In the description, we try to separate the privilege level for which code is written, from the privilege mode in which it runs, although the two are often tied. For example, a supervisor-level operating system can run in supervisor-mode on a system with three privilege modes, but can also run in user-mode under a classic virtual machine monitor on systems with two or more privilege modes. In both cases, the same supervisor-level operating system binary code can be used, coded to a supervisor-level SBI and hence expecting to be able to use supervisor-level privileged instructions and CSRs. When running a guest OS in user mode, all supervisor-level actions will be trapped and emulated by the SEE running in the higher-privilege level.

The machine level has the highest privileges and is the only mandatory privilege level for a RISC-V hardware platform. Code run in machine-mode (M-mode) is usually inherently trusted, as it has low-level access to the machine implementation. M-mode can be used to manage secure execution environments on RISC-V. User-mode (U-mode) and supervisor-mode (S-mode) are intended for conventional application and operating system usage respectively.

Each privilege level has a core set of privileged ISA extensions with optional extensions and variants. For example, machine-mode supports an optional standard extension for memory protection. Also, supervisor mode can be extended to support Type-2 hypervisor execution as described in Chapter 19.

Implementations might provide anywhere from 1 to 3 privilege modes trading off reduced isolation for lower implementation cost, as shown in Table 2.

Table 2. Supported combination of privilege modes.
Number of levels Supported Modes Intended Usage

1
2
3

M
M, U
M, S, U

Simple embedded systems
Secure embedded systems
Systems running Unix-like operating systems

All hardware implementations must provide M-mode, as this is the only mode that has unfettered access to the whole machine. The simplest RISC-V implementations may provide only M-mode, though this will provide no protection against incorrect or malicious application code.

The lock feature of the optional PMP facility can provide some limited protection even with only M-mode implemented.

Many RISC-V implementations will also support at least user mode (U-mode) to protect the rest of the system from application code. Supervisor mode (S-mode) can be added to provide isolation between a supervisor-level operating system and the SEE.

A hart normally runs application code in U-mode until some trap (e.g., a supervisor call or a timer interrupt) forces a switch to a trap handler, which usually runs in a more privileged mode. The hart will then execute the trap handler, which will eventually resume execution at or after the original trapped instruction in U-mode. Traps that increase privilege level are termed vertical traps, while traps that remain at the same privilege level are termed horizontal traps. The RISC-V privileged architecture provides flexible routing of traps to different privilege layers.

Horizontal traps can be implemented as vertical traps that return control to a horizontal trap handler in the less-privileged mode.

1.3. Debug Mode

Implementations may also include a debug mode to support off-chip debugging and/or manufacturing test. Debug mode (D-mode) can be considered an additional privilege mode, with even more access than M-mode. The separate debug specification proposal describes operation of a RISC-V hart in debug mode. Debug mode reserves a few CSR addresses that are only accessible in D-mode, and may also reserve some portions of the physical address space on a platform.

2. Control and Status Registers (CSRs)

The SYSTEM major opcode is used to encode all privileged instructions in the RISC-V ISA. These can be divided into two main classes: those that atomically read-modify-write control and status registers (CSRs), which are defined in the Zicsr extension, and all other privileged instructions. The privileged architecture requires the Zicsr extension; which other privileged instructions are required depends on the privileged-architecture feature set.

In addition to the unprivileged state described in Volume I of this manual, an implementation may contain additional CSRs, accessible by some subset of the privilege levels using the CSR instructions described in Volume I. In this chapter, we map out the CSR address space. The following chapters describe the function of each of the CSRs according to privilege level, as well as the other privileged instructions which are generally closely associated with a particular privilege level. Note that although CSRs and instructions are associated with one privilege level, they are also accessible at all higher privilege levels.

Standard CSRs do not have side effects on reads but may have side effects on writes.

2.1. CSR Address Mapping Conventions

The standard RISC-V ISA sets aside a 12-bit encoding space (csr[11:0]) for up to 4,096 CSRs. 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 as shown in Table 3. 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.

The CSR address convention uses the upper bits of the CSR address to encode default access privileges. This simplifies error checking in the hardware and provides a larger CSR space, but does constrain the mapping of CSRs into the address space.

Implementations might allow a more-privileged level to trap otherwise permitted CSR accesses by a less-privileged level to allow these accesses to be intercepted. This change should be transparent to the less-privileged software.

Instructions that access a non-existent CSR are reserved. Attempts to access a CSR without appropriate privilege level raise illegal-instruction exceptions or, as described in Section 19.6.1, virtual-instruction exceptions. Attempts to write a read-only register raise illegal-instruction exceptions. A read/write register might also contain some bits that are read-only, in which case writes to the read-only bits are ignored.

Table 3 also indicates the convention to allocate CSR addresses between standard and custom uses. The CSR addresses designated for custom uses will not be redefined by future standard extensions.

Machine-mode standard read-write CSRs 0x7A0-0x7BF are reserved for use by the debug system. Of these CSRs, 0x7A0-0x7AF are accessible to machine mode, whereas 0x7B0-0x7BF are only visible to debug mode. Implementations should raise illegal-instruction exceptions on machine-mode access to the latter set of registers.

Effective virtualization requires that as many instructions run natively as possible inside a virtualized environment, while any privileged accesses trap to the virtual machine monitor. (Goldberg, 1974) CSRs that are read-only at some lower privilege level are shadowed into separate CSR addresses if they are made read-write at a higher privilege level. This avoids trapping permitted lower-privilege accesses while still causing traps on illegal accesses. Currently, the counters are the only shadowed CSRs.

2.2. CSR Listing

Table 4-Table 8 list the CSRs that have currently been allocated CSR addresses. The timers, counters, and floating-point CSRs are standard unprivileged CSRs. The other registers are used by privileged code, as described in the following chapters. Note that not all registers are required on all implementations.

Table 3. Allocation of RISC-V CSR address ranges.

CSR Address

Hex

Use and Accessibility

[11:10]

[9:8]

[7:4]

Unprivileged and User-Level CSRs

00

00

XXXX

0x000-0x0FF

Standard read/write

01

00

XXXX

0x400-0x4FF

Standard read/write

10

00

XXXX

0x800-0x8FF

Custom read/write

11

00

0XXX

0xC00-0xC7F

Standard read-only

11

00

10XX

0xC80-0xCBF

Standard read-only

11

00

11XX

0xCC0-0xCFF

Custom read-only

Supervisor-Level CSRs

00

01

XXXX

0x100-0x1FF

Standard read/write

01

01

0XXX

0x500-0x57F

Standard read/write

01

01

10XX

0x580-0x5BF

Standard read/write

01

01

11XX

0x5C0-0x5FF

Custom read/write

10

01

0XXX

0x900-0x97F

Standard read/write

10

01

10XX

0x980-0x9BF

Standard read/write

10

01

11XX

0x9C0-0x9FF

Custom read/write

11

01

0XXX

0xD00-0xD7F

Standard read-only

11

01

10XX

0xD80-0xDBF

Standard read-only

11

01

11XX

0xDC0-0xDFF

Custom read-only

Hypervisor and VS CSRs

00

10

XXXX

0x200-0x2FF

Standard read/write

01

10

0XXX

0x600-0x67F

Standard read/write

01

10

10XX

0x680-0x6BF

Standard read/write

01

10

11XX

0x6C0-0x6FF

Custom read/write

10

10

0XXX

0xA00-0xA7F

Standard read/write

10

10

10XX

0xA80-0xABF

Standard read/write

10

10

11XX

0xAC0-0xAFF

Custom read/write

11

10

0XXX

0xE00-0xE7F

Standard read-only

11

10

10XX

0xE80-0xEBF

Standard read-only

11

10

11XX

0xEC0-0xEFF

Custom read-only

Machine-Level CSRs

00

11

XXXX

0x300-0x3FF

Standard read/write

01

11

0XXX

0x700-0x77F

Standard read/write

01

11

100X

0x780-0x79F

Standard read/write

01

11

1010

0x7A0-0x7AF

Standard read/write debug CSRs

01

11

1011

0x7B0-0x7BF

Debug-mode-only CSRs

01

11

11XX

0x7C0-0x7FF

Custom read/write

10

11

0XXX

0xB00-0xB7F

Standard read/write

10

11

10XX

0xB80-0xBBF

Standard read/write

10

11

11XX

0xBC0-0xBFF

Custom read/write

11

11

0XXX

0xF00-0xF7F

Standard read-only

11

11

10XX

0xF80-0xFBF

Standard read-only

11

11

11XX

0xFC0-0xFFF

Custom read-only

Table 4. Currently allocated RISC-V unprivileged CSR addresses.
Number Privilege Name Description

Unprivileged Floating-Point CSRs

0x001
0x002
0x003

URW
URW
URW

fflags
frm
fcsr

Floating-Point Accrued Exceptions.
Floating-Point Dynamic Rounding Mode.
Floating-Point Control and Status Register (frm +fflags).

Unprivileged Zicfiss extension CSR

0x011

URW

ssp

Shadow Stack Pointer.

Unprivileged Counter/Timers

0xC00
0xC01
0xC02
0xC03
0xC04
 
0xC1F
0xC80
0xC81
0xC82
0xC83
0xC84
 
0xC9F

URO
URO
URO
URO
URO
 
URO
URO
URO
URO
URO
URO
 
URO

cycle
time
instret
hpmcounter3
hpmcounter4

hpmcounter31
cycleh
timeh
instreth
hpmcounter3h
hpmcounter4h

hpmcounter31h

Cycle counter for RDCYCLE instruction.
Timer for RDTIME instruction.
Instructions-retired counter for RDINSTRET instruction.
Performance-monitoring counter.
Performance-monitoring counter.
 
Performance-monitoring counter.
Upper 32 bits of cycle, RV32 only.
Upper 32 bits of time, RV32 only.
Upper 32 bits of instret, RV32 only.
Upper 32 bits of hpmcounter3, RV32 only.
Upper 32 bits of hpmcounter4, RV32 only.
 
Upper 32 bits of hpmcounter31, RV32 only.

Table 5. Currently allocated RISC-V supervisor-level CSR addresses.
Number Privilege Name Description

Supervisor Trap Setup

0x100
0x104
0x105
0x106

SRW
SRW
SRW
SRW

sstatus
sie
stvec
scounteren

Supervisor status register.
Supervisor interrupt-enable register.
Supervisor trap handler base address.
Supervisor counter enable.

Supervisor Configuration

0x10A

SRW

senvcfg

Supervisor environment configuration register.

Supervisor Counter Setup

0x120

SRW

scountinhibit

Supervisor counter-inhibit register.

Supervisor Trap Handling

0x140
0x141
0x142
0x143
0x144
0xDA0

SRW
SRW
SRW
SRW
SRW
SRO

sscratch
sepc
scause
stval
sip
scountovf

Scratch register for supervisor trap handlers.
Supervisor exception program counter.
Supervisor trap cause.
Supervisor bad address or instruction.
Supervisor interrupt pending.
Supervisor count overflow.

Supervisor Protection and Translation

0x180

SRW

satp

Supervisor address translation and protection.

Debug/Trace Registers

0x5A8

SRW

scontext

Supervisor-mode context register.

Supervisor State Enable Registers

0x10C
0x10D
0x10E
0x10F

SRW
SRW
SRW
SRW

sstateen0
sstateen1
sstateen2
sstateen3

Supervisor State Enable 0 Register.
Supervisor State Enable 1 Register.
Supervisor State Enable 2 Register.
Supervisor State Enable 3 Register.

Table 6. Currently allocated RISC-V hypervisor and VS CSR addresses.
Number Privilege Name Description

Hypervisor Trap Setup

0x600
0x602
0x603
0x604
0x606
0x607
0x612

HRW
HRW
HRW
HRW
HRW
HRW
HRW

hstatus
hedeleg
hideleg
hie
hcounteren
hgeie
hedelegh

Hypervisor status register.
Hypervisor exception delegation register.
Hypervisor interrupt delegation register.
Hypervisor interrupt-enable register.
Hypervisor counter enable.
Hypervisor guest external interrupt-enable register.
Upper 32 bits of hedeleg, RV32 only.

Hypervisor Trap Handling

0x643
0x644
0x645
0x64A
0xE12

HRW
HRW
HRW
HRW
HRO

htval
hip
hvip
htinst
hgeip

Hypervisor bad guest physical address.
Hypervisor interrupt pending.
Hypervisor virtual interrupt pending.
Hypervisor trap instruction (transformed).
Hypervisor guest external interrupt pending.

Hypervisor Configuration

0x60A
0x61A

HRW
HRM

henvcfg
henvcfgh

Hypervisor environment configuration register.
Upper 32 bits of henvcfg, RV32 only.

Hypervisor Protection and Translation

0x680

HRW

hgatp

Hypervisor guest address translation and protection.

Debug/Trace Registers

0x6A8

HRW

hcontext

Hypervisor-mode context register.

Hypervisor Counter/Timer Virtualization Registers

0x605
0x615

HRW
HRW

htimedelta
htimedeltah

Delta for VS/VU-mode timer.
Upper 32 bits of htimedelta, RV32 only.

Hypervisor State Enable Registers

0x60C
0x60D
0x60E
0x60F
0x61C
0x61D
0x61E
0x61F

HRW
HRW
HRW
HRW
HRW
HRW
HRW
HRW

hstateen0
hstateen1
hstateen2
hstateen3
hstateen0h
hstateen1h
hstateen2h
hstateen3h

Hypervisor State Enable 0 Register.
Hypervisor State Enable 1 Register.
Hypervisor State Enable 2 Register.
Hypervisor State Enable 3 Register.
Upper 32 bits of Hypervisor State Enable 0 Register, RV32 only.
Upper 32 bits of Hypervisor State Enable 1 Register, RV32 only.
Upper 32 bits of Hypervisor State Enable 2 Register, RV32 only.
Upper 32 bits of Hypervisor State Enable 3 Register, RV32 only.

Virtual Supervisor Registers

0x200
0x204
0x205
0x240
0x241
0x242
0x243
0x244
0x280

HRW
HRW
HRW
HRW
HRW
HRW
HRW
HRW
HRW

vsstatus
vsie
vstvec
vsscratch
vsepc
vscause
vstval
vsip
vsatp

Virtual supervisor status register.
Virtual supervisor interrupt-enable register.
Virtual supervisor trap handler base address.
Virtual supervisor scratch register.
Virtual supervisor exception program counter.
Virtual supervisor trap cause.
Virtual supervisor bad address or instruction.
Virtual supervisor interrupt pending.
Virtual supervisor address translation and protection.

Table 7. Currently allocated RISC-V machine-level CSR addresses.
Number Privilege Name Description

Machine Information Registers

0xF11
0xF12
0xF13
0xF14
0xF15

MRO
MRO
MRO
MRO
MRO

mvendorid
marchid
mimpid
mhartid
mconfigptr

Vendor ID.
Architecture ID.
Implementation ID.
Hardware thread ID.
Pointer to configuration data structure.

Machine Trap Setup

0x300
0x301
0x302
0x303
0x304
0x305
0x306
0x310
0x312

MRW
MRW
MRW
MRW
MRW
MRW
MRW
MRW
MRW

mstatus
misa
medeleg
mideleg
mie
mtvec
mcounteren
mstatush
medelegh

Machine status register.
ISA and extensions
Machine exception delegation register.
Machine interrupt delegation register.
Machine interrupt-enable register.
Machine trap-handler base address.
Machine counter enable.
Additional machine status register, RV32 only.
Upper 32 bits of medeleg, RV32 only.

Machine Trap Handling

0x340
0x341
0x342
0x343
0x344
0x34A
0x34B

MRW
MRW
MRW
MRW
MRW
MRW
MRW

mscratch
mepc
mcause
mtval
mip
mtinst
mtval2

Scratch register for machine trap handlers.
Machine exception program counter.
Machine trap cause.
Machine bad address or instruction.
Machine interrupt pending.
Machine trap instruction (transformed).
Machine bad guest physical address.

Machine Configuration

0x30A
0x31A
0x747
0x757

MRW
MRW
MRW
MRW

menvcfg
menvcfgh
mseccfg
mseccfgh

Machine environment configuration register.
Upper 32 bits of menvcfg, RV32 only.
Machine security configuration register.
Upper 32 bits of mseccfg, RV32 only.

Machine Memory Protection

0x3A0
0x3A1
0x3A2
0x3A3
 
0x3AE
0x3AF
0x3B0
0x3B1
 
0x3EF

MRW
MRW
MRW
MRW
 
MRW
MRW
MRW
MRW
 
MRW

pmpcfg0
pmpcfg1
pmpcfg2
pmpcfg3

pmpcfg14
pmpcfg15
pmpaddr0
pmpaddr1

pmpaddr63

Physical memory protection configuration.
Physical memory protection configuration, RV32 only.
Physical memory protection configuration.
Physical memory protection configuration, RV32 only.
 
Physical memory protection configuration.
Physical memory protection configuration, RV32 only.
Physical memory protection address register.
Physical memory protection address register.
 
Physical memory protection address register.

Machine State Enable Registers

0x30C
0x30D
0x30E
0x30F
0x31C
0x31D
0x31E
0x31F

MRW
MRW
MRW
MRW
MRW
MRW
MRW
MRW

mstateen0
mstateen1
mstateen2
mstateen3
mstateen0h
mstateen1h
mstateen2h
mstateen3h

Machine State Enable 0 Register.
Machine State Enable 1 Register.
Machine State Enable 2 Register.
Machine State Enable 3 Register.
Upper 32 bits of Machine State Enable 0 Register, RV32 only.
Upper 32 bits of Machine State Enable 1 Register, RV32 only.
Upper 32 bits of Machine State Enable 2 Register, RV32 only.
Upper 32 bits of Machine State Enable 3 Register, RV32 only.

Table 8. Currently allocated RISC-V machine-level CSR addresses.
Number Privilege Name Description

Machine Non-Maskable Interrupt Handling

0x740
0x741
0x742
0x744

MRW
MRW
MRW
MRW

mnscratch
mnepc
mncause
mnstatus

Resumable NMI scratch register.
Resumable NMI program counter.
Resumable NMI cause.
Resumable NMI status.

Machine Counter/Timers

0xB00
0xB02
0xB03
0xB04
 
0xB1F
0xB80
0xB82
0xB83
0xB84
 
0xB9F

MRW
MRW
MRW
MRW
 
MRW
MRW
MRW
MRW
MRW
 
MRW

mcycle
minstret
mhpmcounter3
mhpmcounter4

mhpmcounter31
mcycleh
minstreth
mhpmcounter3h
mhpmcounter4h
mhpmcounter31h

Machine cycle counter.
Machine instructions-retired counter.
Machine performance-monitoring counter.
Machine performance-monitoring counter.
 
Machine performance-monitoring counter.
Upper 32 bits of mcycle, RV32 only.
Upper 32 bits of minstret, RV32 only.
Upper 32 bits of mhpmcounter3, RV32 only.
Upper 32 bits of mhpmcounter4, RV32 only.
 
Upper 32 bits of mhpmcounter31, RV32 only.

Machine Counter Setup

0x320
0x323
0x324
 
0x33F
0x723
0x724
 
0x73F

MRW
MRW
MRW
 
MRW
MRW
MRW
 
MRW

mcountinhibit
mhpmevent3
mhpmevent4

mhpmevent31
mhpmevent3h
mhpmevent4h

mhpmevent31h

Machine counter-inhibit register.
Machine performance-monitoring event selector.
Machine performance-monitoring event selector.
 
Machine performance-monitoring event selector.
Upper 32 bits of mhpmevent3, RV32 only.
Upper 32 bits of mhpmevent4, RV32 only.
 
Upper 32 bits of mhpmevent31, RV32 only.

Debug/Trace Registers (shared with Debug Mode)

0x7A0
0x7A1
0x7A2
0x7A3
0x7A8

MRW
MRW
MRW
MRW
MRW

tselect
tdata1
tdata2
tdata3
mcontext

Debug/Trace trigger register select.
First Debug/Trace trigger data register.
Second Debug/Trace trigger data register.
Third Debug/Trace trigger data register.
Machine-mode context register.

Debug Mode Registers

0x7B0
0x7B1
0x7B2
0x7B3

DRW
DRW
DRW
DRW

dcsr
dpc
dscratch0
dscratch1

Debug control and status register.
Debug program counter.
Debug scratch register 0.
Debug scratch register 1.

2.3. CSR Field Specifications

The following definitions and abbreviations are used in specifying the behavior of fields within the CSRs.

2.3.1. Reserved Writes Preserve Values, Reads Ignore Values (WPRI)

Some whole read/write fields are reserved for future use. Software should ignore the values read from these fields, and should preserve the values held in these fields when writing values to other fields of the same register. For forward compatibility, implementations that do not furnish these fields must make them read-only zero. These fields are labeled WPRI in the register descriptions.

To simplify the software model, any backward-compatible future definition of previously reserved fields within a CSR must cope with the possibility that a non-atomic read/modify/write sequence is used to update other fields in the CSR. Alternatively, the original CSR definition must specify that subfields can only be updated atomically, which may require a two-instruction clear bit/set bit sequence in general that can be problematic if intermediate values are not legal.

Some read/write CSR fields specify behavior for only a subset of possible bit encodings, with other bit encodings reserved. Software should not write anything other than legal values to such a field, and should not assume a read will return a legal value unless the last write was of a legal value, or the register has not been written since another operation (e.g., reset) set the register to a legal value. These fields are labeled WLRL in the register descriptions.

Hardware implementations need only implement enough state bits to differentiate between the supported values, but must always return the complete specified bit-encoding of any supported value when read.

Implementations are permitted but not required to raise an illegal-instruction exception if an instruction attempts to write a non-supported value to a WLRL field. Implementations can return arbitrary bit patterns on the read of a WLRL field when the last write was of an illegal value, but the value returned should deterministically depend on the illegal written value and the value of the field prior to the write.

Some read/write CSR fields are only defined for a subset of bit encodings, but allow any value to be written while guaranteeing to return a legal value whenever read. Assuming that writing the CSR has no other side effects, the range of supported values can be determined by attempting to write a desired setting then reading to see if the value was retained. These fields are labeled WARL in the register descriptions.

Implementations will not raise an exception on writes of unsupported values to a WARL field. Implementations can return any legal value on the read of a WARL field when the last write was of an illegal value, but the legal value returned should deterministically depend on the illegal written value and the architectural state of the hart.

2.4. CSR Field Modulation

If a write to one CSR changes the set of legal values allowed for a field of a second CSR, then unless specified otherwise, the second CSR’s field immediately gets an UNSPECIFIED value from among its new legal values. This is true even if the field’s value before the write remains legal after the write; the value of the field may be changed in consequence of the write to the controlling CSR.

As a special case of this rule, the value written to one CSR may control whether a field of a second CSR is writable (with multiple legal values) or is read-only. When a write to the controlling CSR causes the second CSR’s field to change from previously read-only to now writable, that field immediately gets an UNSPECIFIED but legal value, unless specified otherwise.


Some CSR fields are, when writable, defined as aliases of other CSR fields. Let x be such a CSR field, and let y be the CSR field it aliases when writable. If a write to a controlling CSR causes field x to change from previously read-only to now writable, the new value of x is not UNSPECIFIED but instead immediately reflects the existing value of its alias y, as required.

A change to the value of a CSR for this reason is not a write to the affected CSR and thus does not trigger any side effects specified for that CSR.

2.5. Implicit Reads of CSRs

Implementations sometimes perform implicit reads of CSRs. (For example, all S-mode instruction fetches implicitly read the satp CSR.) Unless otherwise specified, the value returned by an implicit read of a CSR is the same value that would have been returned by an explicit read of the CSR, using a CSR-access instruction in a sufficient privilege mode.

2.6. CSR Width Modulation

If the width of a CSR is changed (for example, by changing SXLEN or UXLEN, as described in Section 3.1.6.3), the values of the writable fields and bits of the new-width CSR are, unless specified otherwise, determined from the previous-width CSR as though by this algorithm:

  1. The value of the previous-width CSR is copied to a temporary register of the same width.

  2. For the read-only bits of the previous-width CSR, the bits at the same positions in the temporary register are set to zeros.

  3. The width of the temporary register is changed to the new width. If the new width W is narrower than the previous width, the least-significant W bits of the temporary register are retained and the more-significant bits are discarded. If the new width is wider than the previous width, the temporary register is zero-extended to the wider width.

  4. Each writable field of the new-width CSR takes the value of the bits at the same positions in the temporary register.

Changing the width of a CSR is not a read or write of the CSR and thus does not trigger any side effects.

2.7. Explicit Accesses to CSRs Wider than XLEN

If a standard CSR is wider than XLEN bits, then an explicit read of the CSR returns the register’s least-significant XLEN bits, and an explicit write to the CSR modifies only the register’s least-significant XLEN bits, leaving the upper bits unchanged.

Some standard CSRs, such as the counter CSRs of extension Zicntr, are always 64 bits, even when XLEN=32 (RV32). For each such 64-bit CSR (for example, counter time), a corresponding 32-bit high-half CSR is usually defined with the same name but with the letter ‘h’ appended at the end (timeh). The high-half CSR aliases bits 63:32 of its namesake 64-bit CSR, thus providing a way for RV32 software to read and modify the otherwise-unreachable 32 bits.

Standard high-half CSRs are accessible only when the base RISC-V instruction set is RV32 (XLEN=32). For RV64 (when XLEN=64), the addresses of all standard high-half CSRs are reserved, so an attempt to access a high-half CSR typically raises an illegal-instruction exception.

3. Machine-Level ISA, Version 1.13

This chapter describes the machine-level operations available in machine-mode (M-mode), which is the highest privilege mode in a RISC-V hart. M-mode is used for low-level access to a hardware platform and is the first mode entered at reset. M-mode can also be used to implement features that are too difficult or expensive to implement in hardware directly. The RISC-V machine-level ISA contains a common core that is extended depending on which other privilege levels are supported and other details of the hardware implementation.

3.1. Machine-Level CSRs

In addition to the machine-level CSRs described in this section, M-mode code can access all CSRs at lower privilege levels.

3.1.1. Machine ISA (misa) Register

The misa CSR is a WARL read-write register reporting the ISA supported by the hart. This register must be readable in any implementation, but a value of zero can be returned to indicate the misa register has not been implemented, requiring that CPU capabilities be determined through a separate non-standard mechanism.

Diagram
Figure 2. Machine ISA register (misa)

The MXL (Machine XLEN) field encodes the native base integer ISA width as shown in Table 9. The MXL field is read-only. If misa is nonzero, the MXL field indicates the effective XLEN in M-mode, a constant termed MXLEN. XLEN is never greater than MXLEN, but XLEN might be smaller than MXLEN in less-privileged modes.

Table 9. Encoding of MXL field in misa
MXL XLEN

1
2
3

32
64
128

The misa CSR is MXLEN bits wide.

The base width can be quickly ascertained using branches on the sign of the returned misa value, and possibly a shift left by one and a second branch on the sign. These checks can be written in assembly code without knowing the register width (MXLEN) of the hart. The base width is given by MXLEN=2MXL+4.

The base width can also be found if misa is zero, by placing the immediate 4 in a register, then shifting the register left by 31 bits at a time. If zero after one shift, then the hart is RV32. If zero after two shifts, then the hart is RV64, else RV128.

The Extensions field encodes the presence of the standard extensions, with 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 "I" bit will be set for RV32I, RV64I, and RV128I base ISAs, and the "E" bit will be set for RV32E and RV64E. The Extensions field is a WARL field that can contain writable bits where the implementation allows the supported ISA to be modified. At reset, the Extensions field shall contain the maximal set of supported extensions, and "I" shall be selected over "E" if both are available.

When a standard extension is disabled by clearing its bit in misa, the instructions and CSRs defined or modified by the extension revert to their defined or reserved behaviors as if the extension is not implemented.

For a given RISC-V execution environment, an instruction, extension, or other feature of the RISC-V ISA is ordinarily judged to be implemented or not by the observable execution behavior in that environment. For example, the F extension is said to be implemented for an execution environment if and only if the instructions that the RISC-V Unprivileged ISA defines for F execute as specified.

With this definition of implemented, disabling an extension by clearing its bit in misa results in the extension being considered not implemented in M-mode. For example, setting misa.F=0 results in the F extension being not implemented for M-mode, because the F extension’s instructions will not act as the Unprivileged ISA requires but may instead raise an illegal-instruction exception.

Defining the term implemented based strictly on the observable behavior might conflict with other common understandings of the same word. In particular, although common usage may allow for the combination "implemented but disabled," in this document it is considered a contradiction of terms, because disabled implies execution will not behave as required for the feature to be considered implemented. In the same vein, "implemented and enabled" is redundant here; "implemented" suffices.

Table 10. Encoding of Extensions field in misa. All bits that are reserved for future use must return zero when read.
Bit Character Description

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z

Atomic extension
B extension
Compressed extension
Double-precision floating-point extension
RV32E/64E base ISA
Single-precision floating-point extension
Reserved
Hypervisor extension
RV32I/64I/128I base ISA
Reserved
Reserved
Reserved
Integer Multiply/Divide extension
Tentatively reserved for User-Level Interrupts extension
Reserved
Tentatively reserved for Packed-SIMD extension
Quad-precision floating-point extension
Reserved
Supervisor mode implemented
Reserved
User mode implemented
Vector extension
Reserved
Non-standard extensions present
Reserved
Reserved

The design of the RV128I base ISA is not yet complete, and while much of the remainder of this specification is expected to apply to RV128, this version of the document focuses only on RV32 and RV64.

The "U" and "S" bits will be set if there is support for user and supervisor modes respectively.

The "X" bit will be set if there are any non-standard extensions.

When "B" bit is 1, the implementation supports the instructions provided by the Zba, Zbb, and Zbs extensions. When "B" bit is 0, it indicates that the implementation may not support one or more of the Zba, Zbb, or Zbs extensions.

The misa CSR exposes a rudimentary catalog of CPU features to machine-mode code. More extensive information can be obtained in machine mode by probing other machine registers, and examining other ROM storage in the system as part of the boot process.

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, and supports a much richer command interface without burdening hardware designs.

The "E" bit is read-only. Unless misa is all read-only zero, the "E" bit always reads as the complement of the "I" bit. If an execution environment supports both RV32E and RV32I, software can select RV32E by clearing the "I" bit.

If an ISA feature x depends on an ISA feature y, then attempting to enable feature x but disable feature y results in both features being disabled. For example, setting "F"=0 and "D"=1 results in both "F" and "D" being cleared.

An implementation may impose additional constraints on the collective setting of two or more misa fields, in which case they function collectively as a single WARL field. An attempt to write an unsupported combination causes those bits to be set to some supported combination.

Writing misa may increase IALIGN, e.g., by disabling the "C" extension. If an instruction that would write misa increases IALIGN, and the subsequent instruction’s address is not IALIGN-bit aligned, the write to misa is suppressed, leaving misa unchanged.

When software enables an extension that was previously disabled, then all state uniquely associated with that extension is UNSPECIFIED, unless otherwise specified by that extension.

Although one of the bits 25—​0 in misa being set to 1 implies that the corresponding feature is implemented, the inverse is not necessarily true: one of these bits being clear does not necessarily imply that the corresponding feature is not implemented. This follows from the fact that, when a feature is not implemented, the corresponding opcodes and CSRs become reserved, not necessarily illegal.

3.1.2. Machine Vendor ID (mvendorid) Register

The mvendorid CSR is a 32-bit read-only register providing the JEDEC manufacturer ID of the provider of the core. This register must be readable in any implementation, but a value of 0 can be returned to indicate the field is not implemented or that this is a non-commercial implementation.

Diagram
Figure 3. Vendor ID register (mvendorid)

JEDEC manufacturer IDs are ordinarily encoded as a sequence of one-byte continuation codes 0x7f, terminated by a one-byte ID not equal to 0x7f, with an odd parity bit in the most-significant bit of each byte. mvendorid encodes the number of one-byte continuation codes in the Bank field, and encodes the final byte in the Offset field, discarding the parity bit. For example, the JEDEC manufacturer ID 0x7f 0x7f 0x7f 0x7f 0x7f 0x7f 0x7f 0x7f 0x7f 0x7f 0x7f 0x7f 0x8a (twelve continuation codes followed by 0x8a) would be encoded in the mvendorid CSR as 0x60a.

In JEDEC’s parlance, the bank number is one greater than the number of continuation codes; hence, the mvendorid Bank field encodes a value that is one less than the JEDEC bank number.


Previously the vendor ID was to be a number allocated by RISC-V International, but this duplicates the work of JEDEC in maintaining a manufacturer ID standard. At time of writing, registering a manufacturer ID with JEDEC has a one-time cost of $500.

3.1.3. Machine Architecture ID (marchid) Register

The marchid CSR is an MXLEN-bit read-only register encoding the base microarchitecture of the hart. This register must be readable in any implementation, but a value of 0 can be returned to indicate the field is not implemented. The combination of mvendorid and marchid should uniquely identify the type of hart microarchitecture that is implemented.

Diagram
Figure 4. Machine Architecture ID (marchid) register

Open-source project architecture IDs are allocated globally by RISC-V International, and have non-zero architecture IDs with a zero most-significant-bit (MSB). Commercial architecture IDs are allocated by each commercial vendor independently, but must have the MSB set and cannot contain zero in the remaining MXLEN-1 bits.

The intent is for the architecture ID to represent the microarchitecture associated with the repo around which development occurs rather than a particular organization. Commercial fabrications of open-source designs should (and might be required by the license to) retain the original architecture ID. This will aid in reducing fragmentation and tool support costs, as well as provide attribution. Open-source architecture IDs are administered by RISC-V International and should only be allocated to released, functioning open-source projects. Commercial architecture IDs can be managed independently by any registered vendor but are required to have IDs disjoint from the open-source architecture IDs (MSB set) to prevent collisions if a vendor wishes to use both closed-source and open-source microarchitectures.

The convention adopted within the following Implementation field can be used to segregate branches of the same architecture design, including by organization. The misa register also helps distinguish different variants of a design.

3.1.4. Machine Implementation ID (mimpid) Register

The mimpid CSR provides a unique encoding of the version of the processor implementation. This register must be readable in any implementation, but a value of 0 can be returned to indicate that the field is not implemented. The Implementation value should reflect the design of the RISC-V processor itself and not any surrounding system.

Diagram
Figure 5. Machine Implementation ID (mimpid) register

The format of this field is left to the provider of the architecture source code, but will often be printed by standard tools as a hexadecimal string without any leading or trailing zeros, so the Implementation value can be left-justified (i.e., filled in from most-significant nibble down) with subfields aligned on nibble boundaries to ease human readability.

3.1.5. Hart ID (mhartid) Register

The mhartid CSR is an MXLEN-bit read-only register containing the integer ID of the hardware thread running the code. This register must be readable in any implementation. Hart IDs might not necessarily be numbered contiguously in a multiprocessor system, but at least one hart must have a hart ID of zero. Hart IDs must be unique within the execution environment.

Diagram
Figure 6. Hart ID (mhartid) register

In certain cases, we must ensure exactly one hart runs some code (e.g., at reset), and so require one hart to have a known hart ID of zero.

For efficiency, system implementers should aim to reduce the magnitude of the largest hart ID used in a system.

3.1.6. Machine Status (mstatus and mstatush) Registers

The mstatus register is an MXLEN-bit read/write register formatted as shown in Figure 7 for RV32 and Figure 8 for RV64. The mstatus register keeps track of and controls the hart’s current operating state. A restricted view of mstatus appears as the sstatus register in the S-level ISA.

Diagram
Figure 7. Machine-mode status (mstatus) register for RV32
Diagram
Figure 8. Machine-mode status (mstatus) register for RV64

For RV32 only, mstatush is a 32-bit read/write register formatted as shown in Figure 9. Bits 30:4 of mstatush generally contain the same fields found in bits 62:36 of mstatus for RV64. Fields SD, SXL, and UXL do not exist in mstatush.

Diagram
Figure 9. Additional machine-mode status (mstatush) register for RV32.
3.1.6.1. Privilege and Global Interrupt-Enable Stack in mstatus register

Global interrupt-enable bits, MIE and SIE, are provided for M-mode and S-mode respectively. These bits are primarily used to guarantee atomicity with respect to interrupt handlers in the current privilege mode.

The global xIE bits are located in the low-order bits of mstatus, allowing them to be atomically set or cleared with a single CSR instruction.

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. Higher-privilege-level code can use separate per-interrupt enable bits to disable selected higher-privilege-mode interrupts before ceding control to a lower-privilege mode.

A higher-privilege mode y could disable all of its interrupts before ceding control to a lower-privilege mode but this would be unusual as it would leave only a synchronous trap, non-maskable interrupt, or reset as means to regain control of the hart.

To support nested traps, 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 xPP fields can only hold privilege modes up to x, so MPP is two bits wide and SPP is one bit wide. 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.

For lower privilege modes, any trap (synchronous or asynchronous) is usually taken at a higher privilege mode with interrupts disabled upon entry. The higher-level trap handler will either service the trap and return using the stacked information, or, if not returning immediately to the interrupted context, will save the privilege stack before re-enabling interrupts, so only one entry per stack is required.

An MRET or SRET instruction is used to return from a trap in M-mode or S-mode respectively. 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.

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.

Trap handlers must be designed to neither enable interrupts nor cause exceptions during the phase of handling where the trap handler preserves the critical state information required to handle and resume from the trap. An exception or interrupt in this critical phase of trap handling may lead to a trap that can overwrite such critical state. This could result in the loss of data needed to recover from the initial trap. Further, if an exception occurs in the code path needed to handle traps, then such a situation may lead to an infinite loop of traps. To prevent this, trap handlers must be meticulously designed to identify and safely manage exceptions within their operational flow.

xPP fields are WARL fields that can hold only privilege mode x and any implemented privilege mode lower than x. If privilege mode x is not implemented, then xPP must be read-only 0.

M-mode software can determine whether a privilege mode is implemented by writing that mode to MPP then reading it back.

If the machine provides only U and M modes, then only a single hardware storage bit is required to represent either 00 or 11 in MPP.

3.1.6.2. Double Trap Control in mstatus Register

A double trap typically arises during a sensitive phase in trap handling operations — when an exception or interrupt occurs while the trap handler (the component responsible for managing these events) is in a non-reentrant state. This non-reentrancy usually occurs in the early phase of trap handling, wherein the trap handler has not yet preserved the necessary state to handle and resume from the trap. The occurrence of a trap during this phase can lead to an overwrite of critical state information, resulting in the loss of data needed to recover from the initial trap. The trap that caused this critical error condition is henceforth called the unexpected trap. Trap handlers are designed to neither enable interrupts nor cause exceptions during this phase of handling. However, managing Hardware-Error exceptions, which may occur unpredictably, presents significant challenges in trap handler implementation due to the potential risk of a double trap.

The M-mode-disable-trap (MDT) bit is a WARL field introduced by the Smdbltrp extension. Upon reset, the MDT field is set to 1. When the MDT bit is set to 1 by an explicit CSR write, the MIE (Machine Interrupt Enable) bit is cleared to 0. For RV64, this clearing occurs regardless of the value written, if any, to the MIE bit by the same write. The MIE bit can only be set to 1 by an explicit CSR write if the MDT bit is already 0 or, for RV64, is being set to 0 by the same write (For RV32, the MDT bit is in mstatush and the MIE bit in mstatus register).

When a trap is to be taken into M-mode, if the MDT bit is currently 0, it is then set to 1, and the trap is delivered as expected. However, if MDT is already set to 1, then this is an unexpected trap. Additionally, when the Smrnmi extension is implemented, a trap that occurs when executing in M-mode with the mnstatus.NMIE set to 0 is an unexpected trap.

In the event of a unexpected trap, the handling is as follows:

  • When the Smrnmi extension is implemented and mnstatus.NMIE is 1, the hart traps to the RNMI handler. To deliver this trap, the mnepc and mncause registers are written with the values that the unexpected trap would have written to the mepc and mcause registers respectively. The privilege mode information fields in the mnstatus register are written to indicate M-mode and its NMIE field is set to 0.

The consequence of this specification is that on occurrence of double trap the RNMI handler is not provided with information that a trap reports in the mtval and the mtval2 registers. This information, if needed, can be obtained by the RNMI handler by decoding the instruction at the address in mnepc and examining its source register contents.

  • When the Smrnmi extension is not implemented, or if the Smrnmi extension is implemented and mnstatus.NMIE is 0, the hart enters a critical-error state without updating any architectural state, including the pc. This state involves ceasing execution, disabling all interrupts (including NMIs), and asserting a critical-error signal to the platform.

The actions performed by the platform when a hart asserts a critical-error signal are platform-specific. The range of possible actions include restarting the affected hart or restarting the entire platform, among others.

The MRET and SRET instructions, when executed in M-mode, set the MDT bit to 0. If the new privilege mode is U, VS, or VU, then sstatus.SDT is also set to 0. Additionally, if it is VU, then vsstatus.SDT is also set to 0.

3.1.6.3. Base ISA Control in mstatus Register

For RV64 harts, the SXL and UXL fields are WARL fields that control the value of XLEN for S-mode and U-mode, respectively. The encoding of these fields is the same as the MXL field of misa, shown in Table 9. The effective XLEN in S-mode and U-mode are termed SXLEN and UXLEN, respectively.

When MXLEN=32, the SXL and UXL fields do not exist, and SXLEN=32 and UXLEN=32.

When MXLEN=64, if S-mode is not supported, then SXL is read-only zero. Otherwise, it is a WARL field that encodes the current value of SXLEN. In particular, an implementation may make SXL be a read-only field whose value always ensures that SXLEN=MXLEN.

When MXLEN=64, if U-mode is not supported, then UXL is read-only zero. Otherwise, it is a WARL field that encodes the current value of UXLEN. In particular, an implementation may make UXL be a read-only field whose value always ensures that UXLEN=MXLEN or UXLEN=SXLEN.

If S-mode is implemented, the set of legal values that the UXL field may assume excludes those that would cause UXLEN to be greater than SXLEN.

Whenever XLEN in any mode is set to a value less than the widest supported XLEN, all operations must ignore source operand register bits above the configured XLEN, and must sign-extend results to fill the entire widest supported XLEN in the destination register. Similarly, pc bits above XLEN are ignored, and when the pc is written, it is sign-extended to fill the widest supported XLEN.

We require that operations always fill the entire underlying hardware registers with defined values to avoid implementation-defined behavior.

To reduce hardware complexity, the architecture imposes no checks that lower-privilege modes have XLEN settings less than or equal to the next-higher privilege mode. In practice, such settings would almost always be a software bug, but machine operation is well-defined even in this case.

3.1.6.4. Memory Privilege in mstatus Register

The MPRV (Modify PRiVilege) bit modifies the effective privilege mode, i.e., the privilege level at which loads and stores execute. When MPRV=0, loads and stores behave as normal, using the translation and protection mechanisms of the current privilege mode. When MPRV=1, load and store memory addresses are translated and protected, and endianness is applied, as though the current privilege mode were set to MPP. Instruction address-translation and protection are unaffected by the setting of MPRV. MPRV is read-only 0 if U-mode is not supported.

An MRET or SRET instruction that changes the privilege mode to a mode less privileged than M also sets MPRV=0.

The MXR (Make eXecutable Readable) bit modifies the privilege with which loads access virtual memory. When MXR=0, only loads from pages marked readable (R=1 in Figure 60) will succeed. When MXR=1, loads from pages marked either readable or executable (R=1 or X=1) will succeed. MXR has no effect when page-based virtual memory is not in effect. MXR is read-only 0 if S-mode is not supported.

The MPRV and MXR mechanisms were conceived to improve the efficiency of M-mode routines that emulate missing hardware features, e.g., misaligned loads and stores. MPRV obviates the need to perform address translation in software. MXR allows instruction words to be loaded from pages marked execute-only.

The current privilege mode and the privilege mode specified by MPP might have different XLEN settings. When MPRV=1, load and store memory addresses are treated as though the current XLEN were set to MPP’s XLEN, following the rules in Section 3.1.6.3.

The SUM (permit Supervisor User Memory access) bit modifies the privilege with which S-mode loads and stores access virtual memory. When SUM=0, S-mode memory accesses to pages that are accessible by U-mode (U=1 in Figure 60) will fault. When SUM=1, these accesses are permitted. SUM has no effect when page-based virtual memory is not in effect. Note that, while SUM is ordinarily ignored when not executing in S-mode, it is in effect when MPRV=1 and MPP=S. SUM is read-only 0 if S-mode is not supported or if satp.MODE is read-only 0.

The MXR and SUM mechanisms only affect the interpretation of permissions encoded in page-table entries. In particular, they have no impact on whether access-fault exceptions are raised due to PMAs or PMP.

3.1.6.5. Endianness Control in mstatus and mstatush Registers

The MBE, SBE, and UBE bits in mstatus and mstatush are WARL fields that control the endianness of memory accesses other than instruction fetches. Instruction fetches are always little-endian.

MBE controls whether non-instruction-fetch memory accesses made from M-mode (assuming mstatus.MPRV=0) are little-endian (MBE=0) or big-endian (MBE=1).

If S-mode is not supported, SBE is read-only 0. Otherwise, SBE controls whether explicit load and store memory accesses made from S-mode are little-endian (SBE=0) or big-endian (SBE=1).

If U-mode is not supported, UBE is read-only 0. Otherwise, UBE controls whether explicit load and store memory accesses made from U-mode are little-endian (UBE=0) or big-endian (UBE=1).

For implicit accesses to supervisor-level memory management data structures, such as page tables, endianness is always controlled by SBE. Since changing SBE alters the implementation’s interpretation of these data structures, if any such data structures remain in use across a change to SBE, M-mode software must follow such a change to SBE by executing an SFENCE.VMA instruction with rs1=x0 and rs2=x0.

Only in contrived scenarios will a given memory-management data structure be interpreted as both little-endian and big-endian. In practice, SBE will only be changed at runtime on world switches, in which case neither the old nor new memory-management data structure will be reinterpreted in a different endianness. In this case, no additional SFENCE.VMA is necessary, beyond what would ordinarily be required for a world switch.

If S-mode is supported, an implementation may make SBE be a read-only copy of MBE. If U-mode is supported, an implementation may make UBE be a read-only copy of either MBE or SBE.

An implementation supports only little-endian memory accesses if fields MBE, SBE, and UBE are all read-only 0. An implementation supports only big-endian memory accesses (aside from instruction fetches) if MBE is read-only 1 and SBE and UBE are each read-only 1 when S-mode and U-mode are supported.


Volume I defines a hart’s address space as a circular sequence of 2XLEN bytes at consecutive addresses. The correspondence between addresses and byte locations is fixed and not affected by any endianness mode. Rather, the applicable endianness mode determines the order of mapping between memory bytes and a multibyte quantity (halfword, word, etc.).


Standard RISC-V ABIs are expected to be purely little-endian-only or big-endian-only, with no accommodation for mixing endianness. Nevertheless, endianness control has been defined so as to permit, for instance, an OS of one endianness to execute user-mode programs of the opposite endianness. Consideration has been given also to the possibility of non-standard usages whereby software flips the endianness of memory accesses as needed.


RISC-V instructions are uniformly little-endian to decouple instruction encoding from the current endianness settings, for the benefit of both hardware and software. Otherwise, for instance, a RISC-V assembler or disassembler would always need to know the intended active endianness, despite that the endianness mode might change dynamically during execution. In contrast, by giving instructions a fixed endianness, it is sometimes possible for carefully written software to be endianness-agnostic even in binary form, much like position-independent code.

The choice to have instructions be only little-endian does have consequences, however, for RISC-V software that encodes or decodes machine instructions. In big-endian mode, such software must account for the fact that explicit loads and stores have endianness opposite that of instructions, for example by swapping byte order after loads and before stores.

3.1.6.6. Virtualization Support in mstatus Register

The TVM (Trap Virtual Memory) bit is a WARL field that supports intercepting supervisor virtual-memory management operations. When TVM=1, attempts to read or write the satp CSR or execute an SFENCE.VMA or SINVAL.VMA instruction while executing in S-mode will raise an illegal-instruction exception. When TVM=0, these operations are permitted in S-mode. TVM is read-only 0 when S-mode is not supported.

The TVM mechanism improves virtualization efficiency by permitting guest operating systems to execute in S-mode, rather than classically virtualizing them in U-mode. This approach obviates the need to trap accesses to most S-mode CSRs.

Trapping satp accesses and the SFENCE.VMA and SINVAL.VMA instructions provides the hooks necessary to lazily populate shadow page tables.

The TW (Timeout Wait) bit is a WARL field that supports intercepting the WFI instruction (see Section 3.3.3). When TW=0, the WFI instruction may execute in lower privilege modes when not prevented for some other reason. When TW=1, then if WFI is executed in any less-privileged mode, and it does not complete within an implementation-specific, bounded time limit, the WFI instruction causes an illegal-instruction exception. An implementation may have WFI always raise an illegal-instruction exception in less-privileged modes when TW=1, even if there are pending globally-disabled interrupts when the instruction is executed. TW is read-only 0 when there are no modes less privileged than M.

Trapping the WFI instruction can trigger a world switch to another guest OS, rather than wastefully idling in the current guest.

When S-mode is implemented, then executing WFI in U-mode causes an illegal-instruction exception, unless it completes within an implementation-specific, bounded time limit. A future revision of this specification might add a feature that allows S-mode to selectively permit WFI in U-mode. Such a feature would only be active when TW=0.

The TSR (Trap SRET) bit is a WARL field that supports intercepting the supervisor exception return instruction, SRET. When TSR=1, attempts to execute SRET while executing in S-mode will raise an illegal-instruction exception. When TSR=0, this operation is permitted in S-mode. TSR is read-only 0 when S-mode is not supported.

Trapping SRET is necessary to emulate the hypervisor extension (see Chapter 19) on implementations that do not provide it.

3.1.6.7. Extension Context Status in mstatus Register

Supporting substantial extensions is one of the primary goals of RISC-V, and hence we define a standard interface to allow unchanged privileged-mode code, particularly a supervisor-level OS, to support arbitrary user-mode state extensions.

To date, the V extension is the only standard extension that defines additional state beyond the floating-point CSR and data registers.

The FS[1:0] and VS[1:0] WARL fields and the XS[1:0] read-only field are used to reduce the cost of context save and restore by setting and tracking the current state of the floating-point unit and any other user-mode extensions respectively. The FS field encodes the status of the floating-point unit state, including the floating-point registers f0f31 and the CSRs fcsr, frm, and fflags. The VS field encodes the status of the vector extension state, including the vector registers v0v31 and the CSRs vcsr, vxrm, vxsat, vstart, vl, vtype, and vlenb. The XS field encodes the status of additional user-mode extensions and associated state. These fields can be checked by a context switch routine to quickly determine whether a state save or restore is required. If a save or restore is required, additional instructions and CSRs are typically required to effect and optimize the process.

The design anticipates that most context switches will not need to save/restore state in either or both of the floating-point unit or other extensions, so provides a fast check via the SD bit.

The FS, VS, and XS fields use the same status encoding as shown in Table 11, with the four possible status values being Off, Initial, Clean, and Dirty.

Table 11. Encoding of FS[1:0], VS[1:0], and XS[1:0] status fields
Status FS and VS Meaning XS Meaning

0
1
2
3

Off
Initial
Clean
Dirty

All off
None dirty or clean, some on
None dirty, some clean
Some dirty

If the F extension is implemented, the FS field shall not be read-only zero.

If neither the F extension nor S-mode is implemented, then FS is read-only zero. If S-mode is implemented but the F extension is not, FS may optionally be read-only zero.

Implementations with S-mode but without the F extension are permitted, but not required, to make the FS field be read-only zero. Some such implementations will choose not to have the FS field be read-only zero, so as to enable emulation of the F extension for both S-mode and U-mode via invisible traps into M-mode.

If the v registers are implemented, the VS field shall not be read-only zero.

If neither the v registers nor S-mode is implemented, then VS is read-only zero. If S-mode is implemented but the v registers are not, VS may optionally be read-only zero.

In harts without additional user extensions requiring new state, the XS field is read-only zero. Every additional extension with state provides a CSR field that encodes the equivalent of the XS states. The XS field represents a summary of all extensions' status as shown in Table 11.

The XS field effectively reports the maximum status value across all user-extension status fields, though individual extensions can use a different encoding than XS.

The SD bit is a read-only bit that summarizes whether either the FS, VS, or XS fields signal the presence of some dirty state that will require saving extended user context to memory. If FS, XS, and VS are all read-only zero, then SD is also always zero.

When an extension’s status is set to Off, any instruction that attempts to read or write the corresponding state will cause an illegal-instruction exception. When the status is Initial, the corresponding state should have an initial constant value. When the status is Clean, the corresponding state is potentially different from the initial value, but matches the last value stored on a context swap. When the status is Dirty, the corresponding state has potentially been modified since the last context save.

During a context save, the responsible privileged code need only write out the corresponding state if its status is Dirty, and can then reset the extension’s status to Clean. During a context restore, the context need only be loaded from memory if the status is Clean (it should never be Dirty at restore). If the status is Initial, the context must be set to an initial constant value on context restore to avoid a security hole, but this can be done without accessing memory. For example, the floating-point registers can all be initialized to the immediate value 0.

The FS and XS fields are read by the privileged code before saving the context. The FS field is set directly by privileged code when resuming a user context, while the XS field is set indirectly by writing to the status register of the individual extensions. The status fields will also be updated during execution of instructions, regardless of privilege mode.

Extensions to the user-mode ISA often include additional user-mode state, and this state can be considerably larger than the base integer registers. The extensions might only be used for some applications, or might only be needed for short phases within a single application. To improve performance, the user-mode extension can define additional instructions to allow user-mode software to return the unit to an initial state or even to turn off the unit.

For example, a coprocessor might require to be configured before use and can be "unconfigured" after use. The unconfigured state would be represented as the Initial state for context save. If the same application remains running between the unconfigure and the next configure (which would set status to Dirty), there is no need to actually reinitialize the state at the unconfigure instruction, as all state is local to the user process, i.e., the Initial state may only cause the coprocessor state to be initialized to a constant value at context restore, not at every unconfigure.

Executing a user-mode instruction to disable a unit and place it into the Off state will cause an illegal-instruction exception to be raised if any subsequent instruction tries to use the unit before it is turned back on. A user-mode instruction to turn a unit on must also ensure the unit’s state is properly initialized, as the unit might have been used by another context meantime.

Changing the setting of FS has no effect on the contents of the floating-point register state. In particular, setting FS=Off does not destroy the state, nor does setting FS=Initial clear the contents. Similarly, the setting of VS has no effect on the contents of the vector register state. Other extensions, however, might not preserve state when set to Off.

Implementations may choose to track the dirtiness of the floating-point register state imprecisely by reporting the state to be dirty even when it has not been modified. On some implementations, some instructions that do not mutate the floating-point state may cause the state to transition from Initial or Clean to Dirty. On other implementations, dirtiness might not be tracked at all, in which case the valid FS states are Off and Dirty, and an attempt to set FS to Initial or Clean causes it to be set to Dirty.

This definition of FS does not disallow setting FS to Dirty as a result of errant speculation. Some platforms may choose to disallow speculatively writing FS to close a potential side channel.

If an instruction explicitly or implicitly writes a floating-point register or the fcsr but does not alter its contents, and FS=Initial or FS=Clean, it is implementation-defined whether FS transitions to Dirty.

Implementations may choose to track the dirtiness of the vector register state in an analogous imprecise fashion, including possibly setting VS to Dirty when software attempts to set VS=Initial or VS=Clean. When VS=Initial or VS=Clean, it is implementation-defined whether an instruction that writes a vector register or vector CSR but does not alter its contents causes VS to transition to Dirty.

Table 12 shows all the possible state transitions for the FS, VS, or XS status bits. Note that the standard floating-point and vector extensions do not support user-mode unconfigure or disable/enable instructions.

Table 12. FS, VS, and XS state transitions.

Current State
Action

Off

Initial

Clean

Dirty

At context save in privileged code

Save state?
Next state

No
Off

No
Initial

No
Clean

Yes
Clean

At context restore in privileged code

Restore state?
Next state

No
Off

Yes, to initial
Initial

Yes, from memory
Clean

N/A
N/A

Execute instruction to read state

Action?
Next state

Exception
Off

Execute
Initial

Execute
Clean

Execute
Dirty

Execute instruction that possibly modifies state, including configuration

Action?
Next state

Exception
Off

Execute
Dirty

Execute
Dirty

Execute
Dirty

Execute instruction to unconfigure unit

Action?
Next state

Exception
Off

Execute
Initial

Execute
Initial

Execute
Initial

Execute instruction to disable unit

Action?
Next state

Execute
Off

Execute
Off

Execute
Off

Execute
Off

Execute instruction to enable unit

Action?
Next state

Execute
Initial

Execute
Initial

Execute
Initial

Execute
Initial

Standard privileged instructions to initialize, save, and restore extension state are provided to insulate privileged code from details of the added extension state by treating the state as an opaque object.

Many coprocessor extensions are only used in limited contexts that allows software to safely unconfigure or even disable units when done. This reduces the context-switch overhead of large stateful coprocessors.

We separate out floating-point state from other extension state, as when a floating-point unit is present the floating-point registers are part of the standard calling convention, and so user-mode software cannot know when it is safe to disable the floating-point unit.

The XS field provides a summary of all added extension state, but additional microarchitectural bits might be maintained in the extension to further reduce context save and restore overhead.

The SD bit is read-only and is set when either the FS, VS, or XS bits encode a Dirty state (i.e., SD=FS==11) OR (XS==11) OR (VS==11). This allows privileged code to quickly determine when no additional context save is required beyond the integer register set and pc.

The floating-point unit state is always initialized, saved, and restored using standard instructions (F, D, and/or Q), and privileged code must be aware of FLEN to determine the appropriate space to reserve for each f register.

Machine and Supervisor modes share a single copy of the FS, VS, and XS bits. Supervisor-level software normally uses the FS, VS, and XS bits directly to record the status with respect to the supervisor-level saved context. Machine-level software must be more conservative in saving and restoring the extension state in their corresponding version of the context.

In any reasonable use case, the number of context switches between user and supervisor level should far outweigh the number of context switches to other privilege levels. Note that coprocessors should not require their context to be saved and restored to service asynchronous interrupts, unless the interrupt results in a user-level context swap.

3.1.6.8. Previous Expected Landing Pad (ELP) State in mstatus Register

The Zicfilp extension adds the SPELP and MPELP fields that hold the previous ELP, and are updated as specified in Section 20.1.2. The xPELP fields are encoded as follows:

  • 0 - NO_LP_EXPECTED - no landing pad instruction expected.

  • 1 - LP_EXPECTED - a landing pad instruction is expected.

3.1.7. Machine Trap-Vector Base-Address (mtvec) Register

The mtvec register is an MXLEN-bit WARL read/write register that holds trap vector configuration, consisting of a vector base address (BASE) and a vector mode (MODE).

Diagram
Figure 10. Encoding of mtvec MODE field.

The mtvec register must always be implemented, but can contain a read-only value. If mtvec is writable, the set of values the register may hold can vary by implementation. The value in the BASE field must always be aligned on a 4-byte boundary, and the MODE setting may impose additional alignment constraints on the value in the BASE field.

We allow for considerable flexibility in implementation of the trap vector base address. On the one hand, we do not wish to burden low-end implementations with a large number of state bits, but on the other hand, we wish to allow flexibility for larger systems.

Table 13. Encoding of mtvec MODE field.
Value Name Description

0
1
≥2

Direct
Vectored
---

All traps set pc to BASE.
Asynchronous interrupts set pc to BASE+4×cause.
Reserved

The encoding of the MODE field is shown in Table 13. When MODE=Direct, all traps into machine mode cause the pc to be set to the address in the BASE field. When MODE=Vectored, all synchronous exceptions into machine mode cause the pc to be set to the address in the BASE field, whereas interrupts cause the pc to be set to the address in the BASE field plus four times the interrupt cause number. For example, a machine-mode timer interrupt (see Table 14) causes the pc to be set to BASE+0x1c.

An implementation may have different alignment constraints for different modes. In particular, MODE=Vectored may have stricter alignment constraints than MODE=Direct.

Allowing coarser alignments in Vectored mode enables vectoring to be implemented without a hardware adder circuit.


Reset and NMI vector locations are given in a platform specification.

3.1.8. Machine Trap Delegation (medeleg and mideleg) Registers

By default, all traps at any privilege level are handled in machine mode, though a machine-mode handler can redirect traps back to the appropriate level with the MRET instruction (Section 3.3.2). 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. The machine exception delegation register (medeleg) is a 64-bit read/write register. The machine interrupt delegation (mideleg) register is an MXLEN-bit read/write register.

In harts with S-mode, the medeleg and mideleg registers must exist, and 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. In harts without S-mode, the medeleg and mideleg registers should not exist.

In versions 1.9.1 and earlier , these registers existed but were hardwired to zero in M-mode only, or M/U without N harts. There is no reason to require they return zero in those cases, as the misa register indicates whether they exist.

When a trap is delegated to S-mode, 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.

An implementation can choose to subset the delegatable traps, with the supported delegatable bits found by writing one to every bit location, then reading back the value in medeleg or mideleg to see which bit positions hold a one.

An implementation shall not have any bits of medeleg be read-only one, i.e., any synchronous trap that can be delegated must support not being delegated. Similarly, 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).

Version 1.11 and earlier prohibited having any bits of mideleg be read-only one. Platform standards may always add such restrictions.

Traps never transition from a more-privileged mode to a less-privileged mode. For example, 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, rather than being delegated to S-mode. By contrast, traps may be taken horizontally. Using the same example, if M-mode has delegated illegal-instruction exceptions to S-mode, and S-mode software later executes an illegal instruction, the trap is taken in S-mode.

Delegated interrupts result in the interrupt being masked at the delegator privilege level. For example, if the supervisor timer interrupt (STI) is delegated to S-mode by setting mideleg[5], STIs will not be taken when executing in M-mode. By contrast, if mideleg[5] is clear, STIs can be taken in any mode and regardless of current mode will transfer control to M-mode.

Diagram
Figure 11. Machine Exception Delegation (medeleg) register.

medeleg has a bit position allocated for every synchronous exception shown in Table 14, 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).

When XLEN=32, medelegh is a 32-bit read/write register that aliases bits 63:32 of medeleg. The medelegh register does not exist when XLEN=64.

Diagram
Figure 12. Machine Interrupt Delegation (mideleg) Register.

mideleg holds trap delegation bits for individual interrupts, with the layout of bits matching those in the mip register (i.e., STIP interrupt delegation control is located in bit 5).

For exceptions that cannot occur in less privileged modes, the corresponding medeleg bits should be read-only zero. In particular, medeleg[11] is read-only zero.

The medeleg[16] is read-only zero as double trap is not delegatable.

3.1.9. Machine Interrupt (mip and mie) Registers

The mip register is an MXLEN-bit read/write register containing information on pending interrupts, while mie is the corresponding MXLEN-bit read/write register containing interrupt enable bits. Interrupt cause number i (as reported in CSR mcause, Section 3.1.15) corresponds with bit i in both mip and mie. Bits 15:0 are allocated to standard interrupt causes only, while bits 16 and above are designated for platform use.

Interrupts designated for platform use may be designated for custom use at the platform’s discretion.
Diagram
Figure 13. Machine Interrupt-Pending (mip) register.
Diagram
Figure 14. Machine Interrupt-Enable (mie) register

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.

These conditions for an interrupt trap to occur must be evaluated in a bounded amount of time from when an interrupt becomes, or ceases to be, pending in mip, and must also be evaluated immediately following the execution of an xRET instruction or an explicit write to a CSR on which these interrupt trap conditions expressly depend (including mip, mie, mstatus, and mideleg).

Interrupts to M-mode take priority over any interrupts to lower privilege modes.

Each individual bit in register mip may be writable or may be read-only. When bit i in mip is writable, a pending interrupt i can be cleared by writing 0 to this bit. If interrupt i can become pending but bit i in mip is read-only, the implementation must provide some other mechanism for clearing the pending interrupt.

A bit in mie must be writable if the corresponding interrupt can ever become pending. Bits of mie that are not writable must be read-only zero.

The standard portions (bits 15:0) of the mip and mie registers are formatted as shown in Figure 15 and Figure 16 respectively.

Diagram
Figure 15. Standard portion (bits 15:0) of mip.
Diagram
Figure 16. Standard portion (bits 15:0) of mie.

The machine-level interrupt registers handle a few root interrupt sources which are assigned a fixed service priority for simplicity, while separate external interrupt controllers can implement a more complex prioritization scheme over a much larger set of interrupts that are then muxed into the machine-level interrupt sources.


The non-maskable interrupt is not made visible via the mip register as its presence is implicitly known when executing the NMI trap handler.

Bits mip.MEIP and mie.MEIE are the interrupt-pending and interrupt-enable bits for machine-level external interrupts. MEIP is read-only in mip, and is set and cleared by a platform-specific interrupt controller.

Bits mip.MTIP and mie.MTIE are the interrupt-pending and interrupt-enable bits for machine timer interrupts. MTIP is read-only in the mip register, and is cleared by writing to the memory-mapped machine-mode timer compare register.

Bits mip.MSIP and mie.MSIE are the interrupt-pending and interrupt-enable bits for machine-level software interrupts. MSIP is read-only in mip, and is written by accesses to memory-mapped control registers, which are used by remote harts to provide machine-level interprocessor interrupts. A hart can write its own MSIP bit using the same memory-mapped control register. If a system has only one hart, or if a platform standard supports the delivery of machine-level interprocessor interrupts through external interrupts (MEI) instead, then mip.MSIP and mie.MSIE may both be read-only zeros.

If supervisor mode is not implemented, bits SEIP, STIP, and SSIP of mip and SEIE, STIE, and SSIE of mie are read-only zeros.

If supervisor mode is implemented, bits mip.SEIP and mie.SEIE are the interrupt-pending and interrupt-enable bits for supervisor-level external interrupts. SEIP is writable in mip, and may be written by M-mode software to indicate to S-mode that an external interrupt is pending. Additionally, the platform-level interrupt controller may generate supervisor-level external interrupts. Supervisor-level external interrupts are made pending based on the logical-OR of the software-writable SEIP bit and the signal from the external interrupt controller. When mip is read with a CSR instruction, the value of the SEIP bit returned in the rd destination register is the logical-OR of the software-writable bit and the interrupt signal from the interrupt controller, but the signal from the interrupt controller is not used to calculate the value written to SEIP. Only the software-writable SEIP bit participates in the read-modify-write sequence of a CSRRS or CSRRC instruction.

For example, if we name the software-writable SEIP bit B and the signal from the external interrupt controller E, then if csrrs t0, mip, t1 is executed, t0[9] is written with B || E, then B is written with B || t1[9]. If csrrw t0, mip, t1 is executed, then t0[9] is written with B || E, and B is simply written with t1[9]. In neither case does B depend upon E.

The SEIP field behavior is designed to allow a higher privilege layer to mimic external interrupts cleanly, without losing any real external interrupts. The behavior of the CSR instructions is slightly modified from regular CSR accesses as a result.

If supervisor mode is implemented, bits mip.STIP and mie.STIE are the interrupt-pending and interrupt-enable bits for supervisor-level timer interrupts. STIP is writable in mip, and may be written by M-mode software to deliver timer interrupts to S-mode.

If supervisor mode is implemented, bits mip.SSIP and mie.SSIE are the interrupt-pending and interrupt-enable bits for supervisor-level software interrupts. SSIP is writable in mip and may also be set to 1 by a platform-specific interrupt controller.

If the Sscofpmf extension is implemented, bits mip.LCOFIP and mie.LCOFIE are the interrupt-pending and interrupt-enable bits for local counter-overflow interrupts. LCOFIP is read-write in mip and reflects the occurrence of a local counter-overflow overflow interrupt request resulting from any of the mhpmeventn.OF bits being set. If the Sscofpmf extension is not implemented, mip.LCOFIP and mie.LCOFIE are read-only zeros.

Multiple simultaneous interrupts destined for M-mode are handled in the following decreasing priority order: MEI, MSI, MTI, SEI, SSI, STI, LCOFI.

The machine-level interrupt fixed-priority ordering rules were developed with the following rationale.

Interrupts for higher privilege modes must be serviced before interrupts for lower privilege modes to support preemption.

The platform-specific machine-level interrupt sources in bits 16 and above have platform-specific priority, but are typically chosen to have the highest service priority to support very fast local vectored interrupts.

External interrupts are handled before internal (timer/software) interrupts as external interrupts are usually generated by devices that might require low interrupt service times.

Software interrupts are handled before internal timer interrupts, because internal timer interrupts are usually intended for time slicing, where time precision is less important, whereas software interrupts are used for inter-processor messaging. Software interrupts can be avoided when high-precision timing is required, or high-precision timer interrupts can be routed via a different interrupt path. Software interrupts are located in the lowest four bits of mip as these are often written by software, and this position allows the use of a single CSR instruction with a five-bit immediate.

Restricted views of the mip and mie registers appear as the sip and sie registers for supervisor level. If an interrupt is delegated to S-mode by setting a bit in the mideleg register, it becomes visible in the sip register and is maskable using the sie register. Otherwise, the corresponding bits in sip and sie are read-only zero.

3.1.10. Hardware Performance Monitor

M-mode includes a basic hardware performance-monitoring facility. The mcycle CSR counts the number of clock cycles executed by the processor core on which the hart is running. The minstret CSR counts the number of instructions the hart has retired. The mcycle and minstret registers have 64-bit precision on all RV32 and RV64 harts.

The counter registers have an arbitrary value after the hart is reset, and can be written with a given value. Any CSR write takes effect after the writing instruction has otherwise completed. The mcycle CSR may be shared between harts on the same core, in which case writes to mcycle will be visible to those harts. The platform should provide a mechanism to indicate which harts share an mcycle CSR.

The hardware performance monitor includes 29 additional 64-bit event counters, mhpmcounter3-mhpmcounter31. The event selector CSRs, mhpmevent3-mhpmevent31, are 64-bit WARL registers that control which event causes the corresponding counter to increment. The meaning of these events is defined by the platform, but event 0 is defined to mean "no event." All counters should be implemented, but a legal implementation is to make both the counter and its corresponding event selector be read-only 0.

Diagram
Figure 17. Hardware performance monitor counters.

The mhpmcounters are WARL registers that support up to 64 bits of precision on RV32 and RV64.

When XLEN=32, reads of the mcycle, minstret, mhpmcountern, and mhpmeventn CSRs return bits 31-0 of the corresponding register, and writes change only bits 31-0; reads of the mcycleh, minstreth, mhpmcounternh, and mhpmeventnh CSRs return bits 63-32 of the corresponding register, and writes change only bits 63-32. The mhpmeventnh CSRs are provided only if the Sscofpmf extension is implemented.

3.1.11. Machine Counter-Enable (mcounteren) Register

The counter-enable mcounteren register is a 32-bit register that controls the availability of the hardware performance-monitoring counters to the next-lower privileged mode.

Diagram
Figure 18. Counter-enable (mcounteren) register.

The settings in this register only control accessibility. The act of reading or writing this register does not affect the underlying counters, which continue to increment even when not accessible.

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. When one of these bits is set, access to the corresponding register is permitted in the next implemented privilege mode (S-mode if implemented, otherwise U-mode).

The counter-enable bits support two common use cases with minimal hardware. For harts that do not need high-performance timers and counters, machine-mode software can trap accesses and implement all features in software. For harts that need high-performance timers and counters but are not concerned with obfuscating the underlying hardware counters, the counters can be directly exposed to lower privilege modes.

The cycle, instret, and hpmcountern CSRs are read-only shadows of mcycle, minstret, and mhpmcounter n, respectively. The time CSR is a read-only shadow of the memory-mapped mtime register. Analogously, on RV32I the cycleh, instreth and hpmcounternh CSRs are read-only shadows of mcycleh, minstreth and mhpmcounternh, respectively. On RV32I the timeh CSR is a read-only shadow of the upper 32 bits of the memory-mapped mtime register, while time shadows only the lower 32 bits of mtime.

Implementations can convert reads of the time and timeh CSRs into loads to the memory-mapped mtime register, or emulate this functionality on behalf of less-privileged modes in M-mode software.

In harts with U-mode, the mcounteren must be implemented, but all fields are WARL and may be read-only zero, indicating reads to the corresponding counter will cause an illegal-instruction exception when executing in a less-privileged mode. In harts without U-mode, the mcounteren register should not exist.

3.1.12. Machine Counter-Inhibit (mcountinhibit) Register

Diagram
Figure 19. Counter-inhibit mcountinhibit register

The counter-inhibit register mcountinhibit is a 32-bit WARL register that controls which of the hardware performance-monitoring counters increment. The settings in this register only control whether the counters increment; their accessibility is not affected by the setting of this register.

When the CY, IR, or HPMn bit in the mcountinhibit register is clear, the mcycle, minstret, or mhpmcountern register increments as usual. When the CY, IR, or HPM_n_ bit is set, the corresponding counter does not increment.

The mcycle CSR may be shared between harts on the same core, in which case the mcountinhibit.CY field is also shared between those harts, and so writes to mcountinhibit.CY will be visible to those harts.

If the mcountinhibit register is not implemented, the implementation behaves as though the register were set to zero.

When the mcycle and minstret counters are not needed, it is desirable to conditionally inhibit them to reduce energy consumption. Providing a single CSR to inhibit all counters also allows the counters to be atomically sampled.

Because the mtime counter can be shared between multiple cores, it cannot be inhibited with the mcountinhibit mechanism.

3.1.13. Machine Scratch (mscratch) Register

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.

Diagram
Figure 20. Machine-mode scratch register.

The MIPS ISA allocated two user registers (k0/k1) for use by the operating system. Although the MIPS scheme provides a fast and simple implementation, it also reduces available user registers, and does not scale to further privilege levels, or nested traps. It can also require both registers are cleared before returning to user level to avoid a potential security hole and to provide deterministic debugging behavior.

The RISC-V user ISA was designed to support many possible privileged system environments and so we did not want to infect the user-level ISA with any OS-dependent features. The RISC-V CSR swap instructions can quickly save/restore values to the mscratch register. Unlike the MIPS design, the OS can rely on holding a value in the mscratch register while the user context is running.

3.1.14. Machine Exception Program Counter (mepc) Register

mepc is an MXLEN-bit read/write register formatted as shown in Figure 21. The low bit of mepc (mepc[0]) is always zero. On implementations that support only IALIGN=32, the two low bits (mepc[1:0]) are always zero.

If an implementation allows IALIGN to be either 16 or 32 (by changing CSR misa, for example), then, whenever IALIGN=32, bit mepc[1] is masked on reads so that it appears to be 0. This masking occurs also for the implicit read by the MRET instruction. Though masked, mepc[1] remains writable when IALIGN=32.

mepc is a WARL register that must be able to hold all valid virtual addresses. It need not be capable of holding all possible invalid addresses. Prior to writing mepc, implementations may convert an invalid address into some other invalid address that mepc is capable of holding.

When address translation is not in effect, virtual addresses and physical addresses are equal. Hence, the set of addresses mepc must be able to represent includes the set of physical addresses that can be used as a valid pc or effective address.

When a trap is taken into M-mode, mepc is written with the virtual address of the instruction that was interrupted or that encountered the exception. Otherwise, mepc is never written by the implementation, though it may be explicitly written by software.

Diagram
Figure 21. Machine exception program counter register.

3.1.15. Machine Cause (mcause) Register

The mcause register is an MXLEN-bit read-write register formatted as shown in Figure 22. When a trap is taken into M-mode, mcause is written with a code indicating the event that caused the trap. Otherwise, mcause is never written by the implementation, though it may be explicitly written by software.

The Interrupt bit in the mcause register is set if the trap was caused by an interrupt. The Exception Code field contains a code identifying the last exception or interrupt. Table 14 lists the possible machine-level exception codes. The Exception Code is a WLRL field, so is only guaranteed to hold supported exception codes.

Diagram
Figure 22. Machine Cause (mcause) register.

Note that load and load-reserved instructions generate load exceptions, whereas store, store-conditional, and AMO instructions generate store/AMO exceptions.

Interrupts can be separated from other traps with a single branch on the sign of the mcause register value. A shift left can remove the interrupt bit and scale the exception codes to index into a trap vector table.


We do not distinguish privileged instruction exceptions from illegal-instruction exceptions. This simplifies the architecture and also hides details of which higher-privilege instructions are supported by an implementation. The privilege level servicing the trap can implement a policy on whether these need to be distinguished, and if so, whether a given opcode should be treated as illegal or privileged.

If an instruction may raise multiple synchronous exceptions, the decreasing priority order of Table 15 indicates which exception is taken and reported in mcause. The priority of any custom synchronous exceptions is implementation-defined.

Table 14. Machine cause (mcause) register values after trap.
Interrupt Exception Code Description

1
1
1
1

0
1
2
3

Reserved
Supervisor software interrupt
Reserved
Machine software interrupt

1
1
1
1

4
5
6
7

Reserved
Supervisor timer interrupt
Reserved
Machine timer interrupt

1
1
1
1

8
9
10
11

Reserved
Supervisor external interrupt
Reserved
Machine external interrupt

1
1
1
1

12
13
14-15
≥16

Reserved
Counter-overflow interrupt
Reserved
Designated for platform use

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20-23
24-31
32-47
48-63
≥64

Instruction address misaligned
Instruction access fault
Illegal instruction
Breakpoint
Load address misaligned
Load access fault
Store/AMO address misaligned
Store/AMO access fault
Environment call from U-mode
Environment call from S-mode
Reserved
Environment call from M-mode
Instruction page fault
Load page fault
Reserved
Store/AMO page fault
Double trap
Reserved
Software check
Hardware error
Reserved
Designated for custom use
Reserved
Designated for custom use
Reserved

Table 15. Synchronous exception priority in decreasing priority order.
Priority Exc.Code Description

Highest

3

Instruction address breakpoint

12, 1

During instruction address translation:
First encountered page fault or access fault

1

With physical address for instruction:
Instruction access fault

2
0
8,9,11
3
3

Illegal instruction
Instruction address misaligned
Environment call
Environment break
Load/store/AMO address breakpoint

4,6

Optionally:
Load/store/AMO address misaligned

13, 15, 5, 7

During address translation for an explicit memory access:
First encountered page fault or access fault

5,7

With physical address for an explicit memory access:
Load/store/AMO access fault

Lowest

4,6

If not higher priority:
Load/store/AMO address misaligned

When a virtual address is translated into a physical address, the address translation algorithm determines what specific exception may be raised.

Load/store/AMO address-misaligned exceptions may have either higher or lower priority than load/store/AMO page-fault and access-fault exceptions.

The relative priority of load/store/AMO address-misaligned and page-fault exceptions is implementation-defined to flexibly cater to two design points. Implementations that never support misaligned accesses can unconditionally raise the misaligned-address exception without performing address translation or protection checks. Implementations that support misaligned accesses only to some physical addresses must translate and check the address before determining whether the misaligned access may proceed, in which case raising the page-fault exception or access is more appropriate.


Instruction address breakpoints have the same cause value as, but different priority than, data address breakpoints (a.k.a. watchpoints) and environment break exceptions (which are raised by the EBREAK instruction).


Instruction address misaligned exceptions are raised by control-flow instructions with misaligned targets, rather than by the act of fetching an instruction. Therefore, these exceptions have lower priority than other instruction address exceptions.

A Software Check exception is a synchronous exception that is triggered when there are violations of checks and assertions defined by ISA extensions that aim to safeguard the integrity of software assets, including e.g. control-flow and memory-access constraints. When this exception is raised, the xtval register is set either to 0 or to an informative value defined by the extension that stipulated the exception be raised. The priority of this exception, relative to other synchronous exceptions, depends on the cause of this exception and is defined by the extension that stipulated the exception be raised.

A Hardware Error exception is a synchronous exception triggered when corrupted or uncorrectable data is accessed explicitly or implicitly by an instruction. In this context, "data" encompasses all types of information used within a RISC-V hart. Upon a hardware error exception, the xepc register is set to the address of the instruction that attempted to access corrupted data, while the xtval register is set either to 0 or to the virtual address of an instruction fetch, load, or store that attempted to access corrupted data. The priority of Hardware Error exception is implementation-defined, but any given occurrence is generally expected to be recognized at the point in the overall priority order at which the hardware error is discovered.

3.1.16. Machine Trap Value (mtval) Register

The mtval register is an MXLEN-bit read-write register formatted as shown in Figure 23. 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. Otherwise, mtval is never written by the implementation, though it may be explicitly written by software. The hardware platform will specify which exceptions must set mtval informatively, which may unconditionally set it to zero, and which may exhibit either behavior, depending on the underlying event that caused the exception. If the hardware platform specifies that no exceptions set mtval to a nonzero value, then mtval is read-only zero.

If mtval is written with a nonzero value when a breakpoint, address-misaligned, access-fault, or page-fault exception occurs on an instruction fetch, load, or store, then mtval will contain the faulting virtual address.

When page-based virtual memory is enabled, mtval is written with the faulting virtual address, even for physical-memory access-fault exceptions. This design reduces datapath cost for most implementations, particularly those with hardware page-table walkers.

Diagram
Figure 23. Machine Trap Value (mtval) register.

If mtval is written with a nonzero value when a misaligned load or store causes an access-fault or page-fault exception, then mtval will contain the virtual address of the portion of the access that caused the fault.

If mtval is written with a nonzero value when an instruction access-fault or page-fault exception occurs on a hart with variable-length instructions, then mtval will contain the virtual address of the portion of the instruction that caused the fault, while mepc will point to the beginning of the instruction.

The mtval register can optionally also be used to return the faulting instruction bits on an illegal-instruction exception (mepc points to the faulting instruction in memory). If mtval is written with a nonzero value when an illegal-instruction exception occurs, then mtval will contain the shortest of:

  • the actual faulting instruction

  • the first ILEN bits of the faulting instruction

  • the first MXLEN bits of the faulting instruction

The value loaded into mtval on an illegal-instruction exception is right-justified and all unused upper bits are cleared to zero.

Capturing the faulting instruction in mtval reduces the overhead of instruction emulation, potentially avoiding several partial instruction loads if the instruction is misaligned, and likely data cache misses or slow uncached accesses when loads are used to fetch the instruction into a data register. There is also a problem of atomicity if another agent is manipulating the instruction memory, as might occur in a dynamic translation system.

A requirement is that the entire instruction (or at least the first MXLEN bits) are fetched into mtval before taking the trap. This should not constrain implementations, which would typically fetch the entire instruction before attempting to decode the instruction, and avoids complicating software handlers.

A value of zero in mtval signifies either that the feature is not supported, or an illegal zero instruction was fetched. A load from the instruction memory pointed to by mepc can be used to distinguish these two cases (or alternatively, the system configuration information can be interrogated to install the appropriate trap handling before runtime).

On a trap caused by a software check exception, the mtval register holds the cause for the exception. The following encodings are defined:

  • 0 - No information provided.

  • 2 - Landing Pad Fault. Defined by the Zicfilp extension (Section 20.1).

  • 3 - Shadow Stack Fault. Defined by the Zicfiss extension (Section 20.2).

For other traps, mtval is set to zero, but a future standard may redefine mtval’s setting for other traps.

If mtval is not read-only zero, it is a WARL register that must be able to hold all valid virtual addresses and the value zero. It need not be capable of holding all possible invalid addresses. Prior to writing mtval, implementations may convert an invalid address into some other invalid address that mtval is capable of holding. If the feature to return the faulting instruction bits is implemented, mtval must also be able to hold all values less than 2N, where N is the smaller of MXLEN and ILEN.

3.1.17. Machine Configuration Pointer (mconfigptr) Register

The mconfigptr register is an MXLEN-bit read-only CSR, formatted as shown in Figure 24, that holds the physical address of a configuration data structure. Software can traverse this data structure to discover information about the harts, the platform, and their configuration.

Diagram
Figure 24. Machine Configuration Pointer (mconfigptr) register.

The pointer alignment in bits must be no smaller than MXLEN: i.e., if MXLEN is stem 527c932105a6826cbbe80abc7f968d0b, then mconfigptr[stem 1658b4cd346514bd8ef79419c9d3b35f-1:0] must be zero.

The mconfigptr register must be implemented, but it may be zero to indicate the configuration data structure does not exist or that an alternative mechanism must be used to locate it.

The format and schema of the configuration data structure have yet to be standardized.


While the mconfigptr register will simply be hardwired in some implementations, other implementations may provide a means to configure the value returned on CSR reads. For example, mconfigptr might present the value of a memory-mapped register that is programmed by the platform or by M-mode software towards the beginning of the boot process.

3.1.18. Machine Environment Configuration (menvcfg) Register

The menvcfg CSR is a 64-bit read/write register, formatted as shown in Figure 25, that controls certain characteristics of the execution environment for modes less privileged than M.

Diagram
Figure 25. Machine environment configuration (menvcfg) register.

If bit FIOM (Fence of I/O implies Memory) is set to one in menvcfg, FENCE instructions executed in modes less privileged than M are modified so the requirement to order accesses to device I/O implies also the requirement to order main memory accesses. Table 16 details the modified interpretation of FENCE instruction bits PI, PO, SI, and SO for modes less privileged than M when FIOM=1.

Similarly, for modes less privileged than M when FIOM=1, if an atomic instruction that accesses a region ordered as device I/O has its aq and/or rl bit set, then that instruction is ordered as though it accesses both device I/O and memory.

If S-mode is not supported, or if satp.MODE is read-only zero (always Bare), the implementation may make FIOM read-only zero.

Table 16. Modified interpretation of FENCE predecessor and successor sets for modes less privileged than M when FIOM=1.
Instruction bit Meaning when set

PI
PO

Predecessor device input and memory reads (PR implied)
Predecessor device output and memory writes (PW implied)

SI
SO

Successor device input and memory reads (SR implied)
Successor device output and memory writes (SW implied)

Bit FIOM is needed in menvcfg so M-mode can emulate the hypervisor extension of Chapter 19, which has an equivalent FIOM bit in the hypervisor CSR henvcfg.

The PBMTE bit controls whether the Svpbmt extension is available for use in S-mode and G-stage address translation (i.e., for page tables pointed to by satp or hgatp). When PBMTE=1, Svpbmt is available for S-mode and G-stage address translation. When PBMTE=0, the implementation behaves as though Svpbmt were not implemented. If Svpbmt is not implemented, PBMTE is read-only zero. Furthermore, for implementations with the hypervisor extension, henvcfg.PBMTE is read-only zero if menvcfg.PBMTE is zero.

After changing menvcfg.PBMTE, executing an SFENCE.VMA instruction with rs1=x0 and rs2=x0 suffices to synchronize address-translation caches with respect to the altered interpretation of page-table entries' PBMT fields. See Section 19.5.3 for additional synchronization requirements when the hypervisor extension is implemented.

If the Svadu extension is implemented, the ADUE bit controls whether hardware updating of PTE A/D bits is enabled for S-mode and G-stage address translations. When ADUE=1, hardware updating of PTE A/D bits is enabled during S-mode address translation, and the implementation behaves as though the Svade extension were not implemented for S-mode address translation. When the hypervisor extension is implemented, if ADUE=1, hardware updating of PTE A/D bits is enabled during G-stage address translation, and the implementation behaves as though the Svade extension were not implemented for G-stage address translation. When ADUE=0, the implementation behaves as though Svade were implemented for S-mode and G-stage address translation. If Svadu is not implemented, ADUE is read-only zero. Furthermore, for implementations with the hypervisor extension, henvcfg.ADUE is read-only zero if menvcfg.ADUE is zero.

The Svade extension requires page-fault exceptions be raised when PTE A/D bits need be set, hence Svade is implemented when ADUE=0.

If the Smcdeleg extension is implemented, the CDE (Counter Delegation Enable) bit controls whether Zicntr and Zihpm counters can be delegated to S-mode. When CDE=1, the Smcdeleg extension is enabled, see Chapter 9. When CDE=0, the Smcdeleg and Ssccfg extensions appear to be not implemented. If Smcdeleg is not implemented, CDE is read-only zero.

The definition of the STCE field is furnished by the Sstc extension.

The definition of the CBZE field is furnished by the Zicboz extension.

The definitions of the CBCFE and CBIE fields are furnished by the Zicbom extension.

The definition of the PMM field will be furnished by the forthcoming Smnpm extension. Its allocation within menvcfg may change prior to the ratification of that extension.

The Zicfilp extension adds the LPE field in menvcfg. When the LPE field is set to 1 and S-mode is implemented, the Zicfilp extension is enabled in S-mode. If LPE field is set to 1 and S-mode is not implemented, the Zicfilp extension is enabled in U-mode. When the LPE field is 0, the Zicfilp extension is not enabled in S-mode, and the following rules apply to S-mode. If the LPE field is 0 and S-mode is not implemented, then the same rules apply to U-mode.

  • The hart does not update the ELP state; it remains as NO_LP_EXPECTED.

  • The LPAD instruction operates as a no-op.

The Zicfiss extension adds the SSE field to menvcfg. When the SSE field is set to 1 the Zicfiss extension is activated in S-mode. When SSE field is 0, the following rules apply to privilege modes that are less than M:

  • 32-bit Zicfiss instructions will revert to their behavior as defined by Zimop.

  • 16-bit Zicfiss instructions will revert to their behavior as defined by Zcmop.

  • The pte.xwr=010b encoding in VS/S-stage page tables becomes reserved.

  • The henvcfg.SSE and senvcfg.SSE fields will read as zero and are read-only.

  • SSAMOSWAP.W/D raises an illegal-instruction exception.

The Ssdbltrp extension adds the double-trap-enable (DTE) field in menvcfg. When menvcfg.DTE is zero, the implementation behaves as though Ssdbltrp is not implemented. When Ssdbltrp is not implemented sstatus.SDT, vsstatus.SDT, and henvcfg.DTE bits are read-only zero.

When XLEN=32, menvcfgh is a 32-bit read/write register that aliases bits 63:32 of menvcfg. The menvcfgh register does not exist when XLEN=64.

If U-mode is not supported, then registers menvcfg and menvcfgh do not exist.

3.1.19. Machine Security Configuration (mseccfg) Register

mseccfg is an optional 64-bit read/write register, formatted as shown in Figure 26, that controls security features.

Diagram
Figure 26. Machine security configuration (mseccfg) register.

The definitions of the SSEED and USEED fields will be furnished by the forthcoming entropy-source extension, Zkr. Their allocations within mseccfg may change prior to the ratification of that extension.

The definitions of the RLB, MMWP, and MML fields will be furnished by the forthcoming PMP-enhancement extension, Smepmp. Their allocations within mseccfg may change prior to the ratification of that extension.

The definition of the PMM field will be furnished by the forthcoming Smmpm extension. Its allocation within mseccfg may change prior to the ratification of that extension.

The Zicfilp extension adds the MLPE field in mseccfg. When MLPE field is 1, Zicfilp extension is enabled in M-mode. When the MLPE field is 0, the Zicfilp extension is not enabled in M-mode and the following rules apply to M-mode.

  • The hart does not update the ELP state; it remains as NO_LP_EXPECTED.

  • The LPAD instruction operates as a no-op.

When XLEN=32 only, mseccfgh is a 32-bit read/write register that aliases bits 63:32 of mseccfg. Register mseccfgh does not exist when XLEN=64.

3.2. Machine-Level Memory-Mapped Registers

3.2.1. Machine Timer (mtime and mtimecmp) Registers

Platforms provide a real-time counter, exposed as a memory-mapped machine-mode read-write register, mtime. mtime must increment at constant frequency, and the platform must provide a mechanism for determining the period of an mtime tick. The mtime register will wrap around if the count overflows.

The mtime register has a 64-bit precision on all RV32 and RV64 systems. Platforms provide a 64-bit memory-mapped machine-mode timer compare register (mtimecmp). A machine timer interrupt becomes pending whenever mtime contains a value greater than or equal to mtimecmp, treating the values as unsigned integers. The interrupt remains posted until mtimecmp becomes greater than mtime (typically as a result of writing mtimecmp). The interrupt will only be taken if interrupts are enabled and the MTIE bit is set in the mie register.

Diagram
Figure 27. Machine time register (memory-mapped control register).
Diagram
Figure 28. Machine time compare register (memory-mapped control register).

The timer facility is defined to use wall-clock time rather than a cycle counter to support modern processors that run with a highly variable clock frequency to save energy through dynamic voltage and frequency scaling.

Accurate real-time clocks (RTCs) are relatively expensive to provide (requiring a crystal or MEMS oscillator) and have to run even when the rest of system is powered down, and so there is usually only one in a system located in a different frequency/voltage domain from the processors. Hence, the RTC must be shared by all the harts in a system and accesses to the RTC will potentially incur the penalty of a voltage-level-shifter and clock-domain crossing. It is thus more natural to expose mtime as a memory-mapped register than as a CSR.

Lower privilege levels do not have their own timecmp registers. Instead, machine-mode software can implement any number of virtual timers on a hart by multiplexing the next timer interrupt into the mtimecmp register.

Simple fixed-frequency systems can use a single clock for both cycle counting and wall-clock time.

If the result of the comparison between mtime and mtimecmp changes, it is guaranteed to be reflected in MTIP eventually, but not necessarily immediately.

A spurious timer interrupt might occur if an interrupt handler increments mtimecmp then immediately returns, because MTIP might not yet have fallen in the interim. All software should be written to assume this event is possible, but most software should assume this event is extremely unlikely. It is almost always more performant to incur an occasional spurious timer interrupt than to poll MTIP until it falls.

In RV32, memory-mapped writes to mtimecmp modify only one 32-bit part of the register. The following code sequence sets a 64-bit mtimecmp value without spuriously generating a timer interrupt due to the intermediate value of the comparand:

For RV64, naturally aligned 64-bit memory accesses to the mtime and mtimecmp registers are additionally supported and are atomic.

Sample code for setting the 64-bit time comparand in RV32 assuming a little-endian memory system and that the registers live in a strongly ordered I/O region. Storing -1 to the low-order bits of mtimecmp prevents mtimecmp from temporarily becoming smaller than the lesser of the old and new values.
            # New comparand is in a1:a0.
            li t0, -1
            la t1, mtimecmp
            sw t0, 0(t1)     # No smaller than old value.
            sw a1, 4(t1)     # No smaller than new value.
            sw a0, 0(t1)     # New value.

3.3. Machine-Mode Privileged Instructions

3.3.1. Environment Call and Breakpoint

Diagram

The ECALL instruction is used to make a request to the supporting execution environment. When executed in U-mode, S-mode, or M-mode, it generates an environment-call-from-U-mode exception, environment-call-from-S-mode exception, or environment-call-from-M-mode exception, respectively, and performs no other operation.

ECALL generates a different exception for each originating privilege mode so that environment call exceptions can be selectively delegated. A typical use case for Unix-like operating systems is to delegate to S-mode the environment-call-from-U-mode exception but not the others.

The EBREAK instruction is used by debuggers to cause control to be transferred back to a debugging environment. Unless overridden by an external debug environment, EBREAK raises a breakpoint exception and performs no other operation.

As described in the "C" Standard Extension for Compressed Instructions in Volume I of this manual, the C.EBREAK instruction performs the same operation as the EBREAK instruction.

ECALL and EBREAK cause the receiving privilege mode’s epc register to be set to the address of the ECALL or EBREAK instruction itself, not the address of the following instruction. As ECALL and EBREAK cause synchronous exceptions, they are not considered to retire, and should not increment the minstret CSR.

3.3.2. Trap-Return Instructions

Instructions to return from trap are encoded under the PRIV minor opcode.

Diagram

To return after handling a trap, there are separate trap return instructions per privilege level, MRET and SRET. MRET is always provided. SRET must be provided if supervisor mode is supported, and should raise an illegal-instruction exception otherwise. SRET should also raise an illegal-instruction exception when TSR=1 in mstatus, as described in Section 3.1.6.6. An xRET instruction can be executed in privilege mode x or higher, where executing a lower-privilege xRET instruction will pop the relevant lower-privilege interrupt enable and privilege mode stack. In addition to manipulating the privilege stack as described in Section 3.1.6.1, xRET sets the pc to the value stored in the xepc register.

If the A extension is supported, the xRET instruction is allowed to clear any outstanding LR address reservation but is not required to. Trap handlers should explicitly clear the reservation if required (e.g., by using a dummy SC) before executing the xRET.

If xRET instructions always cleared LR reservations, it would be impossible to single-step through LR/SC sequences using a debugger.

3.3.3. Wait for Interrupt

The Wait for Interrupt instruction (WFI) informs the implementation that the current hart can be stalled until an interrupt might need servicing. Execution of the WFI instruction can also be used to inform the hardware platform that suitable interrupts should preferentially be routed to this hart. WFI is available in all privileged modes, and optionally available to U-mode. This instruction may raise an illegal-instruction exception when TW=1 in mstatus, as described in Section 3.1.6.6.

Diagram

If an enabled interrupt is present or later becomes present while the hart is stalled, the interrupt trap will be taken on the following instruction, i.e., execution resumes in the trap handler and mepc = pc + 4.

The following instruction takes the interrupt trap so that a simple return from the trap handler will execute code after the WFI instruction.

Implementations are permitted to resume execution for any reason, even if an enabled interrupt has not become pending. Hence, a legal implementation is to simply implement the WFI instruction as a NOP.

If the implementation does not stall the hart on execution of the instruction, then the interrupt will be taken on some instruction in the idle loop containing the WFI, and on a simple return from the handler, the idle loop will resume execution.

The WFI instruction can also be executed when interrupts are disabled. The operation of WFI must be unaffected by the global interrupt bits in mstatus (MIE and SIE) and the delegation register mideleg (i.e., the hart must resume if a locally enabled interrupt becomes pending, even if it has been delegated to a less-privileged mode), but should honor the individual interrupt enables (e.g, MTIE) (i.e., implementations should avoid resuming the hart if the interrupt is pending but not individually enabled). WFI is also required to resume execution for locally enabled interrupts pending at any privilege level, regardless of the global interrupt enable at each privilege level.

If the event that causes the hart to resume execution does not cause an interrupt to be taken, execution will resume at pc + 4, and software must determine what action to take, including looping back to repeat the WFI if there was no actionable event.

By allowing wakeup when interrupts are disabled, an alternate entry point to an interrupt handler can be called that does not require saving the current context, as the current context can be saved or discarded before the WFI is executed.

As implementations are free to implement WFI as a NOP, software must explicitly check for any relevant pending but disabled interrupts in the code following an WFI, and should loop back to the WFI if no suitable interrupt was detected. The mip or sip registers can be interrogated to determine the presence of any interrupt in machine or supervisor mode respectively.

The operation of WFI is unaffected by the delegation register settings.

WFI is defined so that an implementation can trap into a higher privilege mode, either immediately on encountering the WFI or after some interval to initiate a machine-mode transition to a lower power state, for example.


The same "wait-for-event" template might be used for possible future extensions that wait on memory locations changing, or message arrival.

3.3.4. Custom SYSTEM Instructions

The subspace of the SYSTEM major opcode shown in Figure 29 is designated for custom use. It is recommended that these instructions use bits 29:28 to designate the minimum required privilege mode, as do other SYSTEM instructions.

Diagram
Figure 29. SYSTEM instruction encodings designated for custom use.

3.4. Reset

Upon reset, a hart’s privilege mode is set to M. The mstatus fields MIE and MPRV are reset to 0. If little-endian memory accesses are supported, the mstatus/mstatush field MBE is reset to 0. The misa register is reset to enable the maximal set of supported extensions, as described in Section 3.1.1. For implementations with the "A" standard extension, there is no valid load reservation. The pc is set to an implementation-defined reset vector. The mcause register is set to a value indicating the cause of the reset. Writable PMP registers’ A and L fields are set to 0, unless the platform mandates a different reset value for some PMP registers’ A and L fields. If the hypervisor extension is implemented, the hgatp.MODE and vsatp.MODE fields are reset to 0. If the Smrnmi extension is implemented, the mnstatus.NMIE field is reset to 0. No WARL field contains an illegal value. All other hart state is UNSPECIFIED.

The mcause values after reset have implementation-specific interpretation, but the value 0 should be returned on implementations that do not distinguish different reset conditions. Implementations that distinguish different reset conditions should only use 0 to indicate the most complete reset.

Some designs may have multiple causes of reset (e.g., power-on reset, external hard reset, brownout detected, watchdog timer elapse, sleep-mode wakeup), which machine-mode software and debuggers may wish to distinguish.

mcause reset values may alias mcause values following synchronous exceptions. There should be no ambiguity in this overlap, since on reset the pc is typically set to a different value than on other traps.

3.5. Non-Maskable Interrupts

Non-maskable interrupts (NMIs) are only used for hardware error conditions, and cause an immediate jump to an implementation-defined NMI vector running in M-mode regardless of the state of a hart’s interrupt enable bits. The mepc register is written with the virtual address of the instruction that was interrupted, and mcause is set to a value indicating the source of the NMI. The NMI can thus overwrite state in an active machine-mode interrupt handler.

The values written to mcause on an NMI are implementation-defined. The high Interrupt bit of mcause should be set to indicate that this was an interrupt. An Exception Code of 0 is reserved to mean "unknown cause" and implementations that do not distinguish sources of NMIs via the mcause register should return 0 in the Exception Code.

Unlike resets, NMIs do not reset processor state, enabling diagnosis, reporting, and possible containment of the hardware error.

3.6. Physical Memory Attributes

The physical memory map for a complete system includes various address ranges, some corresponding to memory regions and some to memory-mapped control registers, portions of which might not be accessible. Some memory regions might not support reads, writes, or execution; some might not support subword or subblock accesses; some might not support atomic operations; and some might not support cache coherence or might have different memory models. Similarly, memory-mapped control registers vary in their supported access widths, support for atomic operations, and whether read and write accesses have associated side effects. In RISC-V systems, these properties and capabilities of each region of the machine’s physical address space are termed physical memory attributes (PMAs). This section describes RISC-V PMA terminology and how RISC-V systems implement and check PMAs.

PMAs are inherent properties of the underlying hardware and rarely change during system operation. Unlike physical memory protection values described in Section 3.7, PMAs do not vary by execution context. The PMAs of some memory regions are fixed at chip design time—for example, for an on-chip ROM. Others are fixed at board design time, depending, for example, on which other chips are connected to off-chip buses. Off-chip buses might also support devices that could be changed on every power cycle (cold pluggable) or dynamically while the system is running (hot pluggable). Some devices might be configurable at run time to support different uses that imply different PMAs—for example, an on-chip scratchpad RAM might be cached privately by one core in one end-application, or accessed as a shared non-cached memory in another end-application.

Most systems will require that at least some PMAs are dynamically checked in hardware later in the execution pipeline after the physical address is known, as some operations will not be supported at all physical memory addresses, and some operations require knowing the current setting of a configurable PMA attribute. While many other architectures specify some PMAs in the virtual memory page tables and use the TLB to inform the pipeline of these properties, this approach injects platform-specific information into a virtualized layer and can cause system errors unless attributes are correctly initialized in each page-table entry for each physical memory region. In addition, the available page sizes might not be optimal for specifying attributes in the physical memory space, leading to address-space fragmentation and inefficient use of expensive TLB entries.

For RISC-V, we separate out specification and checking of PMAs into a separate hardware structure, the PMA checker. In many cases, the attributes are known at system design time for each physical address region, and can be hardwired into the PMA checker. Where the attributes are run-time configurable, platform-specific memory-mapped control registers can be provided to specify these attributes at a granularity appropriate to each region on the platform (e.g., for an on-chip SRAM that can be flexibly divided between cacheable and uncacheable uses). PMAs are checked for any access to physical memory, including accesses that have undergone virtual to physical memory translation. To aid in system debugging, we strongly recommend that, where possible, RISC-V processors precisely trap physical memory accesses that fail PMA checks. Precisely trapped PMA violations manifest as instruction, load, or store access-fault exceptions, distinct from virtual-memory page-fault exceptions. Precise PMA traps might not always be possible, for example, when probing a legacy bus architecture that uses access failures as part of the discovery mechanism. In this case, error responses from peripheral devices will be reported as imprecise bus-error interrupts.

PMAs must also be readable by software to correctly access certain devices or to correctly configure other hardware components that access memory, such as DMA engines. As PMAs are tightly tied to a given physical platform’s organization, many details are inherently platform-specific, as is the means by which software can learn the PMA values for a platform. Some devices, particularly legacy buses, do not support discovery of PMAs and so will give error responses or time out if an unsupported access is attempted. Typically, platform-specific machine-mode code will extract PMAs and ultimately present this information to higher-level less-privileged software using some standard representation.

Where platforms support dynamic reconfiguration of PMAs, an interface will be provided to set the attributes by passing requests to a machine-mode driver that can correctly reconfigure the platform. For example, switching cacheability attributes on some memory regions might involve platform-specific operations, such as cache flushes, that are available only to machine-mode.

3.6.1. Main Memory versus I/O Regions

The most important characterization of a given memory address range is whether it holds regular main memory or I/O devices. Regular main memory is required to have a number of properties, specified below, whereas I/O devices can have a much broader range of attributes. Memory regions that do not fit into regular main memory, for example, device scratchpad RAMs, are categorized as I/O regions.

What previous versions of this specification termed vacant regions are no longer a distinct category; they are now described as I/O regions that are not accessible (i.e. lacking read, write, and execute permissions). Main memory regions that are not accessible are also allowed.

3.6.2. Supported Access Type PMAs

Access types specify which access widths, from 8-bit byte to long multi-word burst, are supported, and also whether misaligned accesses are supported for each access width.

Although software running on a RISC-V hart cannot directly generate bursts to memory, software might have to program DMA engines to access I/O devices and might therefore need to know which access sizes are supported.

Main memory regions always support read and write of all access widths required by the attached devices, and can specify whether instruction fetch is supported.

Some platforms might mandate that all of main memory support instruction fetch. Other platforms might prohibit instruction fetch from some main memory regions.


In some cases, the design of a processor or device accessing main memory might support other widths, but must be able to function with the types supported by the main memory.

I/O regions can specify which combinations of read, write, or execute accesses to which data widths are supported.

For systems with page-based virtual memory, I/O and memory regions can specify which combinations of hardware page-table reads and hardware page-table writes are supported.

Unix-like operating systems generally require that all of cacheable main memory supports page-table walks.

3.6.3. Atomicity PMAs

Atomicity PMAs describes which atomic instructions are supported in this address region. Support for atomic instructions is divided into two categories: LR/SC and AMOs.

Some platforms might mandate that all of cacheable main memory support all atomic operations required by the attached processors.

3.6.3.1. AMO PMA

Within AMOs, there are four levels of support: AMONone, AMOSwap, AMOLogical, and AMOArithmetic. AMONone indicates that no AMO operations are supported. AMOSwap indicates that only amoswap instructions are supported in this address range. AMOLogical indicates that swap instructions plus all the logical AMOs (amoand, amoor, amoxor) are supported. AMOArithmetic indicates that all RISC-V AMOs are supported. For each level of support, naturally aligned AMOs of a given width are supported if the underlying memory region supports reads and writes of that width. Main memory and I/O regions may only support a subset or none of the processor-supported atomic operations.

Table 17. Classes of AMOs supported by I/O regions.
AMO Class Supported Operations

AMONone
AMOSwap
AMOLogical
AMOArithmetic

None
amoswap
above + amoand, amoor, amoxor
above + amoadd, amomin, amomax, amominu, amomaxu

We recommend providing at least AMOLogical support for I/O regions where possible.

3.6.3.2. Reservability PMA

For LR/SC, there are three levels of support indicating combinations of the reservability and eventuality properties: RsrvNone, RsrvNonEventual, and RsrvEventual. RsrvNone indicates that no LR/SC operations are supported (the location is non-reservable). RsrvNonEventual indicates that the operations are supported (the location is reservable), but without the eventual success guarantee described in the unprivileged ISA specification. RsrvEventual indicates that the operations are supported and provide the eventual success guarantee.

We recommend providing RsrvEventual support for main memory regions where possible. Most I/O regions will not support LR/SC accesses, as these are most conveniently built on top of a cache-coherence scheme, but some may support RsrvNonEventual or RsrvEventual.


When LR/SC is used for memory locations marked RsrvNonEventual, software should provide alternative fall-back mechanisms used when lack of progress is detected.

3.6.4. Misaligned Atomicity Granule PMA

The misaligned atomicity granule PMA provides constrained support for misaligned AMOs. This PMA, if present, specifies the size of a misaligned atomicity granule, a naturally aligned power-of-two number of bytes. Specific supported values for this PMA are represented by MAGNN, e.g., MAG16 indicates the misaligned atomicity granule is at least 16 bytes.

The misaligned atomicity granule PMA applies only to AMOs, loads and stores defined in the base ISAs, and loads and stores of no more than MXLEN bits defined in the F, D, and Q extensions. For an instruction in that set, if all accessed bytes lie within the same misaligned atomicity granule, the instruction will not raise an exception for reasons of address alignment, and the instruction will give rise to only one memory operation for the purposes of RVWMO—​i.e., it will execute atomically.

If a misaligned AMO accesses a region that does not specify a misaligned atomicity granule PMA, or if not all accessed bytes lie within the same misaligned atomicity granule, then an exception is raised. For regular loads and stores that access such a region or for which not all accessed bytes lie within the same atomicity granule, then either an exception is raised, or the access proceeds but is not guaranteed to be atomic. Implementations may raise access-fault exceptions instead of address-misaligned exceptions for some misaligned accesses, indicating the instruction should not be emulated by a trap handler.

LR/SC instructions are unaffected by this PMA and so always raise an exception when misaligned. Vector memory accesses are also unaffected, so might execute non-atomically even when contained within a misaligned atomicity granule. Implicit accesses are similarly unaffected by this PMA.

3.6.5. Memory-Ordering PMAs

Regions of the address space are classified as either main memory or I/O for the purposes of ordering by the FENCE instruction and atomic-instruction ordering bits.

Accesses by one hart to main memory regions are observable not only by other harts but also by other devices with the capability to initiate requests in the main memory system (e.g., DMA engines). Coherent main memory regions always have either the RVWMO or RVTSO memory model. Incoherent main memory regions have an implementation-defined memory model.

Accesses by one hart to an I/O region are observable not only by other harts and bus mastering devices but also by the targeted I/O devices, and I/O regions may be accessed with either relaxed or strong ordering. Accesses to an I/O region with relaxed ordering are generally observed by other harts and bus mastering devices in a manner similar to the ordering of accesses to an RVWMO memory region, as discussed in Section A.4.2 in Volume I of this specification. By contrast, accesses to an I/O region with strong ordering are generally observed by other harts and bus mastering devices in program order.

Each strongly ordered I/O region specifies a numbered ordering channel, which is a mechanism by which ordering guarantees can be provided between different I/O regions. Channel 0 is used to indicate point-to-point strong ordering only, where only accesses by the hart to the single associated I/O region are strongly ordered.

Channel 1 is used to provide global strong ordering across all I/O regions. Any accesses by a hart to any I/O region associated with channel 1 can only be observed to have occurred in program order by all other harts and I/O devices, including relative to accesses made by that hart to relaxed I/O regions or strongly ordered I/O regions with different channel numbers. In other words, any access to a region in channel 1 is equivalent to executing a fence io,io instruction before and after the instruction.

Other larger channel numbers provide program ordering to accesses by that hart across any regions with the same channel number.

Systems might support dynamic configuration of ordering properties on each memory region.

Strong ordering can be used to improve compatibility with legacy device driver code, or to enable increased performance compared to insertion of explicit ordering instructions when the implementation is known to not reorder accesses.

Local strong ordering (channel 0) is the default form of strong ordering as it is often straightforward to provide if there is only a single in-order communication path between the hart and the I/O device.

Generally, different strongly ordered I/O regions can share the same ordering channel without additional ordering hardware if they share the same interconnect path and the path does not reorder requests.

3.6.6. Coherence and Cacheability PMAs

Coherence is a property defined for a single physical address, and indicates that writes to that address by one agent will eventually be made visible to other coherent agents in the system. Coherence is not to be confused with the memory consistency model of a system, which defines what values a memory read can return given the previous history of reads and writes to the entire memory system. In RISC-V platforms, the use of hardware-incoherent regions is discouraged due to software complexity, performance, and energy impacts.

The cacheability of a memory region should not affect the software view of the region except for differences reflected in other PMAs, such as main memory versus I/O classification, memory ordering, supported accesses and atomic operations, and coherence. For this reason, we treat cacheability as a platform-level setting managed by machine-mode software only.

Where a platform supports configurable cacheability settings for a memory region, a platform-specific machine-mode routine will change the settings and flush caches if necessary, so the system is only incoherent during the transition between cacheability settings. This transitory state should not be visible to lower privilege levels.

Coherence is straightforward to provide for a shared memory region that is not cached by any agent. The PMA for such a region would simply indicate it should not be cached in a private or shared cache.

Coherence is also straightforward for read-only regions, which can be safely cached by multiple agents without requiring a cache-coherence scheme. The PMA for this region would indicate that it can be cached, but that writes are not supported.

Some read-write regions might only be accessed by a single agent, in which case they can be cached privately by that agent without requiring a coherence scheme. The PMA for such regions would indicate they can be cached. The data can also be cached in a shared cache, as other agents should not access the region.

If an agent can cache a read-write region that is accessible by other agents, whether caching or non-caching, a cache-coherence scheme is required to avoid use of stale values. In regions lacking hardware cache coherence (hardware-incoherent regions), cache coherence can be implemented entirely in software, but software coherence schemes are notoriously difficult to implement correctly and often have severe performance impacts due to the need for conservative software-directed cache-flushing. Hardware cache-coherence schemes require more complex hardware and can impact performance due to the cache-coherence probes, but are otherwise invisible to software.

For each hardware cache-coherent region, the PMA would indicate that the region is coherent and which hardware coherence controller to use if the system has multiple coherence controllers. For some systems, the coherence controller might be an outer-level shared cache, which might itself access further outer-level cache-coherence controllers hierarchically.

Most memory regions within a platform will be coherent to software, because they will be fixed as either uncached, read-only, hardware cache-coherent, or only accessed by one agent.

If a PMA indicates non-cacheability, then accesses to that region must be satisfied by the memory itself, not by any caches.

For implementations with a cacheability-control mechanism, the situation may arise that a program uncacheably accesses a memory location that is currently cache-resident. In this situation, the cached copy must be ignored. This constraint is necessary to prevent more-privileged modes’ speculative cache refills from affecting the behavior of less-privileged modes’ uncacheable accesses.

3.6.7. Idempotency PMAs

Idempotency PMAs describe whether reads and writes to an address region are idempotent. Main memory regions are assumed to be idempotent. For I/O regions, idempotency on reads and writes can be specified separately (e.g., reads are idempotent but writes are not). If accesses are non-idempotent, i.e., there is potentially a side effect on any read or write access, then speculative or redundant accesses must be avoided.

For the purposes of defining the idempotency PMAs, changes in observed memory ordering created by redundant accesses are not considered a side effect.

While hardware should always be designed to avoid speculative or redundant accesses to memory regions marked as non-idempotent, it is also necessary to ensure software or compiler optimizations do not generate spurious accesses to non-idempotent memory regions.

Non-idempotent regions might not support misaligned accesses. Misaligned accesses to such regions should raise access-fault exceptions rather than address-misaligned exceptions, indicating that software should not emulate the misaligned access using multiple smaller accesses, which could cause unexpected side effects.

For non-idempotent regions, implicit reads and writes must not be performed early or speculatively, with the following exceptions. When a non-speculative implicit read is performed, an implementation is permitted to additionally read any of the bytes within a naturally aligned power-of-2 region containing the address of the non-speculative implicit read. Furthermore, when a non-speculative instruction fetch is performed, an implementation is permitted to additionally read any of the bytes within the next naturally aligned power-of-2 region of the same size (with the address of the region taken modulo 2XLEN. The results of these additional reads may be used to satisfy subsequent early or speculative implicit reads. The size of these naturally aligned power-of-2 regions is implementation-defined, but, for systems with page-based virtual memory, must not exceed the smallest supported page size.

3.7. Physical Memory Protection

To support secure processing and contain faults, it is desirable to limit the physical addresses accessible by software running on a hart. 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. The PMP values are checked in parallel with the PMA checks described in Section 3.6.

The granularity of PMP access control settings are platform-specific, but the standard PMP encoding supports regions as small as four bytes. Certain regions’ privileges can be hardwired—for example, some regions might only ever be visible in machine mode but in no lower-privilege layers.

Platforms vary widely in demands for physical memory protection, and some platforms may provide other PMP structures in addition to or instead of the scheme described in this section.

PMP checks are applied to all accesses whose effective privilege mode is S or U, including instruction fetches and data accesses in S and U mode, and data accesses in M-mode when the MPRV bit in mstatus is set and the MPP field in mstatus contains S or U. PMP checks are also applied to page-table accesses for virtual-address translation, for which the effective privilege mode is S. Optionally, PMP checks may additionally apply to M-mode accesses, in which case the PMP registers themselves are locked, so that even M-mode software cannot change them until the hart is reset. 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.

PMP violations are always trapped precisely at the processor.

3.7.1. Physical Memory Protection CSRs

PMP entries are described by an 8-bit configuration register and one MXLEN-bit address register. Some PMP settings additionally use the address register associated with the preceding PMP entry. Up to 64 PMP entries are supported. Implementations may implement zero, 16, or 64 PMP entries; the lowest-numbered PMP entries must be implemented first. All PMP CSR fields are WARL and may be read-only zero. PMP CSRs are only accessible to M-mode.

The PMP configuration registers are densely packed into CSRs to minimize context-switch time. For RV32, sixteen CSRs, pmpcfg0pmpcfg15, hold the configurations pmp0cfgpmp63cfg for the 64 PMP entries, as shown in Figure 30. For RV64, eight even-numbered CSRs, pmpcfg0, pmpcfg2, …, pmpcfg14, hold the configurations for the 64 PMP entries, as shown in Figure 31. For RV64, the odd-numbered configuration registers, pmpcfg1, pmpcfg3, …, pmpcfg15, are illegal.

RV64 harts use pmpcfg2, rather than pmpcfg1, to hold configurations for PMP entries 8-15. This design reduces the cost of supporting multiple MXLEN values, since the configurations for PMP entries 8-11 appear in pmpcfg2[31:0] for both RV32 and RV64.

Diagram
Figure 30. RV32 PMP configuration CSR layout.
Diagram
Figure 31. RV64 PMP configuration CSR layout.

The PMP address registers are CSRs named pmpaddr0-pmpaddr63. Each PMP address register encodes bits 33-2 of a 34-bit physical address for RV32, as shown in Figure 32. For RV64, each PMP address register encodes bits 55-2 of a 56-bit physical address, as shown in Figure 33. Not all physical address bits may be implemented, and so the pmpaddr registers are WARL.

The Sv32 page-based virtual-memory scheme described in Section 11.3 supports 34-bit physical addresses for RV32, so the PMP scheme must support addresses wider than XLEN for RV32. The Sv39 and Sv48 page-based virtual-memory schemes described in Section 11.4 and Section 11.5 support a 56-bit physical address space, so the RV64 PMP address registers impose the same limit.

Diagram
Figure 32. PMP address register format, RV32.
Diagram
Figure 33. PMP address register format, RV64.

Figure 34 shows the layout of a PMP configuration register. The R, W, and X bits, when set, indicate that the PMP entry permits read, write, and instruction execution, respectively. When one of these bits is clear, the corresponding access type is denied. The R, W, and X fields form a collective WARL field for which the combinations with R=0 and W=1 are reserved. The remaining two fields, A and L, are described in the following sections.

Diagram
Figure 34. PMP configuration register format.

Attempting to fetch an instruction from a PMP region that does not have execute permissions raises an instruction access-fault exception. Attempting to execute a load or load-reserved instruction which accesses a physical address within a PMP region without read permissions raises a load access-fault exception. Attempting to execute a store, store-conditional, or AMO instruction which accesses a physical address within a PMP region without write permissions raises a store access-fault exception.

3.7.1.1. Address Matching

The A field in a PMP entry’s configuration register encodes the address-matching mode of the associated PMP address register. The encoding of this field is shown in Table 18. When A=0, this PMP entry is disabled and matches no addresses. Two other address-matching modes are supported: naturally aligned power-of-2 regions (NAPOT), including the special case of naturally aligned four-byte regions (NA4); and the top boundary of an arbitrary range (TOR). These modes support four-byte granularity.

Table 18. Encoding of A field in PMP configuration registers.
A Name Description

0
1
2
3

OFF
TOR
NA4
NAPOT

Null region (disabled)
Top of range
Naturally aligned four-byte region
Naturally aligned power-of-two region, ≥8 bytes

NAPOT ranges make use of the low-order bits of the associated address register to encode the size of the range, as shown in Table 19.

Table 19. NAPOT range encoding in PMP address and configuration registers.
pmpaddr pmpcfg.A Match type and size

yyyy…​yyyy
yyyy…​yyy0
yyyy…​yy01
yyyy…​y011
…​
yy01…​1111
y011…​1111
0111…​1111
1111…​1111

NA4
NAPOT
NAPOT
NAPOT
…​
NAPOT
NAPOT
NAPOT
NAPOT

4-byte NAPOT range
8-byte NAPOT range
16-byte NAPOT range
32-byte NAPOT range

2XLEN-byte NAPOT range
2XLEN+1-byte NAPOT range
2XLEN+2-byte NAPOT range
2XLEN+3-byte NAPOT range

If TOR is selected, the associated address register forms the top of the address range, and the preceding PMP address register forms the bottom of the address range. If PMP entry i's A field is set to TOR, the entry matches any address y such that pmpaddri-1y<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.

If pmpaddri-1pmpaddri and pmpcfgi.A=TOR, then PMP entry i matches no addresses.

Although the PMP mechanism supports regions as small as four bytes, platforms may specify coarser PMP regions. In general, the PMP grain is stem 50c2d22972bd4d3042e2106e11a4f768 bytes and must be the same across all PMP regions. When stem 455f095ec98c57486370d8897c063d21, the NA4 mode is not selectable. When stem 2d1e292b70a7c400833da494a4a48c66 and stem a0acc94b70acb4e7dd3c8c0039ee033e.A[1] is set, i.e. the mode is NAPOT, then bits stem 7fb2b94c3cf4f2fa76e8b8950724e8d0[G-2:0] read as all ones. When stem 455f095ec98c57486370d8897c063d21 and stem a0acc94b70acb4e7dd3c8c0039ee033e.A[1] is clear, i.e. the mode is OFF or TOR, then bits stem 7fb2b94c3cf4f2fa76e8b8950724e8d0[G-1:0] read as all zeros. Bits stem a3b10e0eeee1f1506964ab171629e445[G-1:0] do not affect the TOR address-matching logic. Although changing stem a0acc94b70acb4e7dd3c8c0039ee033e.A[1] affects the value read from stem 7fb2b94c3cf4f2fa76e8b8950724e8d0, it does not affect the underlying value stored in that register—in particular, stem 7fb2b94c3cf4f2fa76e8b8950724e8d0[G-1] retains its original value when stem a0acc94b70acb4e7dd3c8c0039ee033e.A is changed from NAPOT to TOR/OFF then back to NAPOT.

Software may determine the PMP granularity by writing zero to pmp0cfg, then writing all ones to pmpaddr0, then reading back pmpaddr0. If G is the index of the least-significant bit set, the PMP granularity is 2G+2 bytes.

If the current XLEN is greater than MXLEN, the PMP address registers are zero-extended from MXLEN to XLEN bits for the purposes of address matching.

3.7.1.2. Locking and Privilege Mode

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. If PMP entry i is locked, writes to pmpicfg and pmpaddri are ignored. Additionally, if PMP entry i is locked and pmpicfg.A is set to TOR, writes to pmpaddri-1 are ignored.

Setting the L bit locks the PMP entry even when the A field is set to OFF.

In addition to locking the PMP entry, the L bit indicates whether the R/W/X permissions are enforced on M-mode accesses. 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.

3.7.1.3. Priority and Matching Logic

PMP entries are statically prioritized. The lowest-numbered PMP entry that matches any byte of an access determines whether that access succeeds or fails. The matching PMP entry must match all bytes of an access, or the access fails, irrespective of the L, R, W, and X bits. For example, if a PMP entry is configured to match the four-byte range 0xC0xF, then an 8-byte access to the range 0x80xF will fail, assuming that PMP entry is the highest-priority entry that matches those addresses.

If a PMP entry matches all bytes of an access, then the L, R, W, and X bits determine whether the access succeeds or fails. If the L bit is clear and the privilege mode of the access is M, the access succeeds. Otherwise, if the L bit is set or the privilege mode of the access is S or U, then the access succeeds only if the R, W, or X bit corresponding to the access type is set.

If no PMP entry matches an M-mode access, the access succeeds. If no PMP entry matches an S-mode or U-mode access, but at least one PMP entry is implemented, the access fails.

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.

Failed accesses generate an instruction, load, or store access-fault exception. Note that a single instruction may generate multiple accesses, which may not be mutually atomic. An access-fault exception is generated if at least one access generated by an instruction fails, though other accesses generated by that instruction may succeed with visible side effects. Notably, instructions that reference virtual memory are decomposed into multiple accesses.

On some implementations, misaligned loads, stores, and instruction fetches may also be decomposed into multiple accesses, some of which may succeed before an access-fault exception occurs. In particular, a portion of a misaligned store that passes the PMP check may become visible, even if another portion fails the PMP check. The same behavior may manifest for stores wider than XLEN bits (e.g., the FSD instruction in RV32D), even when the store address is naturally aligned.

3.7.2. Physical Memory Protection and Paging

The Physical Memory Protection mechanism is designed to compose with the page-based virtual memory systems described in Chapter 11. When paging is enabled, instructions that access virtual memory may result in multiple physical-memory accesses, including implicit references to the page tables. The PMP checks apply to all of these accesses. The effective privilege mode for implicit page-table accesses is S.

Implementations with virtual memory are permitted to perform address translations speculatively and earlier than required by an explicit memory access, and are permitted to cache them in address translation cache structures—including possibly caching the identity mappings from effective address to physical address used in Bare translation modes and M-mode. The PMP settings for the resulting physical address may be checked (and possibly cached) at any point between the address translation and the explicit memory access. Hence, 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. See Section 19.5.3 for additional synchronization requirements when the hypervisor extension is implemented.

If page-based virtual memory is not implemented, memory accesses check the PMP settings synchronously, so no SFENCE.VMA is needed.

4. "Smstateen/Ssstateen" Extensions, Version 1.0

The implementation of optional RISC-V extensions has the potential to open covert channels between separate user threads, or between separate guest OSes running under a hypervisor. The problem occurs when an extension adds processor state — usually explicit registers, but possibly other forms of state — that the main OS or hypervisor is unaware of (and hence won’t context-switch) but that can be modified/written by one user thread or guest OS and perceived/examined/read by another.

For example, the Advanced Interrupt Architecture (AIA) for RISC-V adds to a hart as many as ten supervisor-level CSRs (siselect, sireg, stopi, sseteipnum, sclreipnum, sseteienum, sclreienum, sclaimei, sieh, and siph) and provides also the option for hardware to be backward-compatible with older, pre-AIA software. Because an older hypervisor that is oblivious to the AIA will not know to swap any of the AIA’s new CSRs on context switches, the registers may then be used as a covert channel between multiple guest OSes that run atop this hypervisor. Although traditional practices might consider such a communication channel harmless, the intense focus on security today argues that a means be offered to plug such channels.

The f registers of the RISC-V floating-point extensions and the v registers of the vector extension would similarly be potential covert channels between user threads, except for the existence of the FS and VS fields in the sstatus register. Even if an OS is unaware of, say, the vector extension and its v registers, access to those registers is blocked when the VS field is initialized to zero, either at machine level or by the OS itself initializing sstatus.

Obviously, one way to prevent the use of new user-level CSRs as covert channels would be to add to mstatus or sstatus an "XS" field for each relevant extension, paralleling the V extension’s VS field. However, this is not considered a general solution to the problem due to the number of potential future extensions that may add small amounts of state. Even with a 64-bit sstatus (necessitating adding sstatush for RV32), it is not certain there are enough remaining bits in sstatus to accommodate all future user-level extensions. In any event, there is no need to strain sstatus (and add sstatush) for this purpose. The "enable" flags that are needed to plug covert channels are not generally expected to require swapping on context switches of user threads, making them a less-than-compelling candidate for inclusion in sstatus. Hence, a new place is provided for them instead.

4.1. State Enable Extensions

The Smstateen and Ssstateen extensions collectively specify machine-mode and supervisor-mode features. The Smstateen extension specification comprises the mstateen*, sstateen*, and hstateen* CSRs and their functionality. The Ssstateen extension specification comprises only the sstateen* and hstateen* CSRs and their functionality.

For RV64 harts, this extension adds four new 64-bit CSRs at machine level: mstateen0 (Machine State Enable 0), mstateen1, mstateen2, and mstateen3.

If supervisor mode is implemented, another four CSRs are defined at supervisor level: sstateen0, sstateen1, sstateen2, and sstateen3.

And if the hypervisor extension is implemented, another set of CSRs is added: hstateen0, hstateen1, hstateen2, and hstateen3.

For RV32, the registers listed above are 32-bit, and for the machine-level and hypervisor CSRs there is a corresponding set of high-half CSRs for the upper 32 bits of each register: mstateen0h, mstateen1h, mstateen2h, mstateen3h, hstateen0h, hstateen1h, hstateen2h, and hstateen3h.

For the supervisor-level sstateen registers, high-half CSRs are not added at this time because it is expected the upper 32 bits of these registers will always be zeros, as explained later below.

Each bit of a stateen CSR controls less-privileged access to an extension’s state, for an extension that was not deemed "worthy" of a full XS field in sstatus like the FS and VS fields for the F and V extensions. The number of registers provided at each level is four because it is believed that 4 * 64 = 256 bits for machine and hypervisor levels, and 4 * 32 = 128 bits for supervisor level, will be adequate for many years to come, perhaps for as long as the RISC-V ISA is in use. The exact number four is an attempted compromise between providing too few bits on the one hand and going overboard with CSRs that will never be used on the other. A possible future doubling of the number of stateen CSRs is covered later.

The stateen registers at each level control access to state at all less-privileged levels, but not at its own level. This is analogous to how the existing counteren CSRs control access to performance counter registers. Just as with the counteren CSRs, when a stateen CSR prevents access to state by less-privileged levels, an attempt in one of those privilege modes to execute an instruction that would read or write the protected state raises an illegal instruction exception, or, if executing in VS or VU mode and the circumstances for a virtual instruction exception apply, raises a virtual instruction exception instead of an illegal instruction exception.

When this extension is not implemented, all state added by an extension is accessible as defined by that extension.

When a stateen CSR prevents access to state for a privilege mode, attempting to execute in that privilege mode an instruction that implicitly updates the state without reading it may or may not raise an illegal instruction or virtual instruction exception. Such cases must be disambiguated by being explicitly specified one way or the other.

In some cases, the bits of the stateen CSRs will have a dual purpose as enables for the ISA extensions that introduce the controlled state.

Each bit of a supervisor-level sstateen CSR controls user-level access (from U-mode or VU-mode) to an extension’s state. The intention is to allocate the bits of sstateen CSRs starting at the least-significant end, bit 0, through to bit 31, and then on to the next-higher-numbered sstateen CSR.

For every bit with a defined purpose in an sstateen CSR, the same bit is defined in the matching mstateen CSR to control access below machine level to the same state. The upper 32 bits of an mstateen CSR (or for RV32, the corresponding high-half CSR) control access to state that is inherently inaccessible to user level, so no corresponding enable bits in the supervisor-level sstateen CSR are applicable. The intention is to allocate bits for this purpose starting at the most-significant end, bit 63, through to bit 32, and then on to the next-higher mstateen CSR. If the rate that bits are being allocated from the least-significant end for sstateen CSRs is sufficiently low, allocation from the most-significant end of mstateen CSRs may be allowed to encroach on the lower 32 bits before jumping to the next-higher mstateen CSR. In that case, the bit positions of "encroaching" bits will remain forever read-only zeros in the matching sstateen CSRs.

With the hypervisor extension, the hstateen CSRs have identical encodings to the mstateen CSRs, except controlling accesses for a virtual machine (from VS and VU modes).

Each standard-defined bit of a stateen CSR is WARL and may be read-only zero or one, subject to the following conditions.

Bits in any stateen CSR that are defined to control state that a hart doesn’t implement are read-only zeros for that hart. Likewise, all reserved bits not yet given a defined meaning are also read-only zeros. For every bit in an mstateen CSR that is zero (whether read-only zero or set to zero), the same bit appears as read-only zero in the matching hstateen and sstateen CSRs. For every bit in an hstateen CSR that is zero (whether read-only zero or set to zero), the same bit appears as read-only zero in sstateen when accessed in VS-mode.

A bit in a supervisor-level sstateen CSR cannot be read-only one unless the same bit is read-only one in the matching mstateen CSR and, if it exists, in the matching hstateen CSR. A bit in an hstateen CSR cannot be read-only one unless the same bit is read-only one in the matching mstateen CSR.

On reset, all writable mstateen bits are initialized by the hardware to zeros. If machine-level software changes these values, it is responsible for initializing the corresponding writable bits of the hstateen and sstateen CSRs to zeros too. Software at each privilege level should set its respective stateen CSRs to indicate the state it is prepared to allow less-privileged software to access. For OSes and hypervisors, this usually means the state that the OS or hypervisor is prepared to swap on a context switch, or to manage in some other way.

For each mstateen CSR, bit 63 is defined to control access to the matching sstateen and hstateen CSRs. That is, bit 63 of mstateen0 controls access to sstateen0 and hstateen0; bit 63 of mstateen1 controls access to sstateen1 and hstateen1; etc. Likewise, bit 63 of each hstateen correspondingly controls access to the matching sstateen CSR.

A hypervisor may need this control over accesses to the sstateen CSRs if it ever must emulate for a virtual machine an extension that is supposed to be affected by a bit in an sstateen CSR. Even if such emulation is uncommon, it should not be excluded.

Machine-level software needs identical control to be able to emulate the hypervisor extension. That is, machine level needs control over accesses to the supervisor-level sstateen CSRs in order to emulate the hstateen CSRs, which have such control.

Bit 63 of each mstateen CSR may be read-only zero only if the hypervisor extension is not implemented and the matching supervisor-level sstateen CSR is all read-only zeros. In that case, machine-level software should emulate attempts to access the affected sstateen CSR from S-mode, ignoring writes and returning zero for reads. Bit 63 of each hstateen CSR is always writable (not read-only).

4.2. State Enable 0 Registers

Diagram
Figure 35. Machine State Enable 0 Register (mstateen0)
Diagram
Figure 36. Hypervisor State Enable 0 Register (hstateen0)
Diagram
Figure 37. Supervisor State Enable 0 Register (sstateen0)

The C bit controls access to any and all custom state. This bit is not custom state itself. The C bit of these registers is not custom state itself; it is a standard field of a standard CSR, either mstateen0, hstateen0, or sstateen0.

The requirements that non-standard extensions must meet to be conforming are not relaxed due solely to changes in the value of this bit. In particular, if software sets this bit but does not execute any custom instructions or access any custom state, the software must continue to execute as specified by all relevant RISC-V standards, or the hardware is not standard-conforming.

The FCSR bit controls access to fcsr for the case when floating-point instructions operate on x registers instead of f registers as specified by the Zfinx and related extensions (Zdinx, etc.). Whenever misa.F = 1, FCSR bit of mstateen0 is read-only zero (and hence read-only zero in hstateen0 and sstateen0 too). For convenience, when the stateen CSRs are implemented and misa.F = 0, then if the FCSR bit of a controlling stateen0 CSR is zero, all floating-point instructions cause an illegal instruction trap (or virtual instruction trap, if relevant), as though they all access fcsr, regardless of whether they really do.

The JVT bit controls access to the jvt CSR provided by the Zcmt extension.

The SE0 bit in mstateen0 controls access to the hstateen0, hstateen0h, and the sstateen0 CSRs. The SE0 bit in hstateen0 controls access to the sstateen0 CSR.

The ENVCFG bit in mstateen0 controls access to the henvcfg, henvcfgh, and the senvcfg CSRs. The ENVCFG bit in hstateen0 controls access to the senvcfg CSRs.

The CSRIND bit in mstateen0 controls access to the siselect, sireg*, vsiselect, and the vsireg* CSRs provided by the Sscsrind extensions. The CSRIND bit in hstateen0 controls access to the siselect and the sireg*, (really vsiselect and vsireg*) CSRs provided by the Sscsrind extensions.

The IMSIC bit in mstateen0 controls access to the IMSIC state, including CSRs stopei and vstopei, provided by the Ssaia extension. The IMSIC bit in hstateen0 controls access to the guest IMSIC state, including CSRs stopei (really vstopei), provided by the Ssaia extension.

Setting the IMSIC bit in hstateen0 to zero prevents a virtual machine from accessing the hart’s IMSIC the same as setting hstatus.VGEIN = 0.

The AIA bit in mstateen0 controls access to all state introduced by the Ssaia extension and not controlled by either the CSRIND or the IMSIC bits. The AIA bit in hstateen0 controls access to all state introduced by the Ssaia extension and not controlled by either the CSRIND or the IMSIC bits of hstateen0.

The CONTEXT bit in mstateen0 controls access to the scontext and hcontext CSRs provided by the Sdtrig extension. The CONTEXT bit in hstateen0 controls access to the scontext CSR provided by the Sdtrig extension.

The P1P13 bit in mstateen0 controls access to the hedelegh introduced by Privileged Specification Version 1.13.

4.3. Usage

After the writable bits of the machine-level mstateen CSRs are initialized to zeros on reset, machine-level software can set bits in these registers to enable less-privileged access to the controlled state. This may be either because machine-level software knows how to swap the state or, more likely, because machine-level software isn’t swapping supervisor-level environments. (Recall that the main reason the mstateen CSRs must exist is so machine level can emulate the hypervisor extension. When machine level isn’t emulating the hypervisor extension, it is likely there will be no need to keep any implemented mstateen bits zero.)

If machine level sets any writable mstateen bits to nonzero, it must initialize the matching hstateen CSRs, if they exist, by writing zeros to them. And if any mstateen bits that are set to one have matching bits in the sstateen CSRs, machine-level software must also initialize those sstateen CSRs by writing zeros to them. Ordinarily, machine-level software will want to set bit 63 of all mstateen CSRs, necessitating that it write zero to all hstateen CSRs.

Software should ensure that all writable bits of sstateen CSRs are initialized to zeros when an OS at supervisor level is first entered. The OS can then set bits in these registers to enable user-level access to the controlled state, presumably because it knows how to context-swap the state.

For the sstateen CSRs whose access by a guest OS is permitted by bit 63 of the corresponding hstateen CSRs, a hypervisor must include the sstateen CSRs in the context it swaps for a guest OS. When it starts a new guest OS, it must ensure the writable bits of those sstateen CSRs are initialized to zeros, and it must emulate accesses to any other sstateen CSRs.

If software at any privilege level does not support multiple contexts for less-privilege levels, then it may choose to maximize less-privileged access to all state by writing a value of all ones to the stateen CSRs at its level (the mstateen CSRs for machine level, the sstateen CSRs for an OS, and the hstateen CSRs for a hypervisor), without knowing all the state to which it is granting access. This is justified because there is no risk of a covert channel between execution contexts at the less-privileged level when only one context exists at that level. This situation is expected to be common for machine level, and it might also arise, for example, for a type-1 hypervisor that hosts only a single guest virtual machine.

If a need is anticipated, the set of stateen CSRs could in the future be doubled by adding these:

  • 0x38C mstateen4, 0x39C mstateen4h

  • 0x38D mstateen5, 0x39D mstateen5h

  • 0x38E mstateen6, 0x39E mstateen6h

  • 0x38F mstateen7, 0x39F mstateen7h

  • 0x18C sstateen4

  • 0x18D sstateen5

  • 0x18E sstateen6

  • 0x18F sstateen7

  • 0x68C hstateen4, 0x69C hstateen4h

  • 0x68D hstateen5, 0x69D hstateen5h

  • 0x68E hstateen6, 0x69E hstateen6h

  • 0x68F hstateen7, 0x69F hstateen7h

These additional CSRs are not a definite part of the original proposal because it is unclear whether they will ever be needed, and it is believed the rate of consumption of bits in the first group, registers numbered 0-3, will be slow enough that any looming shortage will be perceptible many years in advance. At the moment, it is not known even how many years it may take to exhaust just mstateen0, sstateen0, and hstateen0.

5. "Smcsrind/Sscsrind" Indirect CSR Access, Version 1.0

5.1. Introduction

Smcsrind/Sscsrind is an ISA extension that extends the indirect CSR access mechanism originally defined as part of the Smaia/Ssaia extensions, in order to make it available for use by other extensions without creating an unnecessary dependence on Smaia/Ssaia.

This extension confers two benefits:

  1. It provides a means to access an array of registers via CSRs without requiring allocation of large chunks of the limited CSR address space.

  2. It enables software to access each of an array of registers by index, without requiring a switch statement with a case for each register.

CSRs are accessed indirectly via this extension using select values, in contrast to being accessed directly using standard CSR numbers. A CSR accessible via one method may or may not be accessible via the other method. Select values are a separate address space from CSR numbers, and from tselect values in the Sdtrig extension. If a CSR is both directly and indirectly accessible, the CSR’s select value is unrelated to its CSR number.

Further, Machine-level and Supervisor-level select values are separate address spaces from each other; however, Machine-level and Supervisor-level CSRs with the same select value may be defined by an extension as partial or full aliases with respect to each other. This typically would be done for CSRs that can be delegated from Machine-level to Supervisor-level.

The machine-level extension Smcsrind encompasses all added CSRs and all behavior modifications for a hart, over all privilege levels. For a supervisor-level environment, extension Sscsrind is essentially the same as Smcsrind except excluding the machine-level CSRs and behavior not directly visible to supervisor level.

5.2. Machine-level CSRs

Number Privilege Width Name Description

0x350

MRW

XLEN

miselect

Machine indirect register select

0x351

MRW

XLEN

mireg

Machine indirect register alias

0x352

MRW

XLEN

mireg2

Machine indirect register alias 2

0x353

MRW

XLEN

mireg3

Machine indirect register alias 3

0x355

MRW

XLEN

mireg4

Machine indirect register alias 4

0x356

MRW

XLEN

mireg5

Machine indirect register alias 5

0x357

MRW

XLEN

mireg6

Machine indirect register alias 6

The mireg* CSR numbers are not consecutive because miph is CSR number 0x354.

The CSRs listed in the table above provide a window for accessing register state indirectly. The value of miselect determines which register is accessed upon read or write of each of the machine indirect alias CSRs (mireg*). miselect value ranges are allocated to dependent extensions, which specify the register state accessible via each miregi register, for each miselect value. miselect is a WARL register.

The miselect register implements at least enough bits to support all implemented miselect values (corresponding to the implemented extensions that utilize miselect/mireg* to indirectly access register state). The miselect register may be read-only zero if there are no extensions implemented that utilize it.

Values of miselect with the most-significant bit set (bit XLEN - 1 = 1) are designated only for custom use, presumably for accessing custom registers through the alias CSRs. Values of miselect with the most-significant bit clear are designated only for standard use and are reserved until allocated to a standard architecture extension. If XLEN is changed, the most-significant bit of miselect moves to the new position, retaining its value from before.

An implementation is not required to support any custom values for miselect.

The behavior upon accessing mireg* from M-mode, while miselect holds a value that is not implemented, is UNSPECIFIED.

It is expected that implementations will typically raise an illegal instruction exception for such accesses, so that, for example, they can be identified as software bugs. Platform specs, profile specs, and/or the Privileged ISA spec may place more restrictions on behavior for such accesses.

Attempts to access mireg* while miselect holds a number in an allocated and implemented range results in a specific behavior that, for each combination of miselect and miregi, is defined by the extension to which the miselect value is allocated.

Ordinarily, each miregi will access register state, access read-only 0 state, or raise an illegal instruction exception.

For RV32, if an extension defines an indirectly accessed register as 64 bits wide, it is recommended that the lower 32 bits of the register are accessed through one of mireg, mireg2, or mireg3, while the upper 32 bits are accessed through mireg4, mireg5, or mireg6, respectively.

Six *ireg* registers are defined in order to ensure that the needs of extensions in development are covered, with some room for growth. For example, for an siselect value associated with counter X, sireg/sireg2 could be used to access mhpmcounterX/mhpmeventX, while sireg4/sireg5 could access mhpmcounterXh/mhpmeventXh. Six *ireg* registers allows for accessing up to 3 CSR arrays per index (*iselect) with RV32-only CSRs, or up to 6 CSR arrays per index value without RV32-only CSRs.

5.3. Supervisor-level CSRs

Number Privilege Width Name Description

0x150

SRW

XLEN

siselect

Supervisor indirect register select

0x151

SRW

XLEN

sireg

Supervisor indirect register alias

0x152

SRW

XLEN

sireg2

Supervisor indirect register alias 2

0x153

SRW

XLEN

sireg3

Supervisor indirect register alias 3

0x155

SRW

XLEN

sireg4

Supervisor indirect register alias 4

0x156

SRW

XLEN

sireg5

Supervisor indirect register alias 5

0x157

SRW

XLEN

sireg6

Supervisor indirect register alias 6

The CSRs in the table above are required if S-mode is implemented.

The siselect register will support the value range 0..0xFFF at a minimum. A future extension may define a value range outside of this minimum range. Only if such an extension is implemented will siselect be required to support larger values.

Requiring a range of 0–0xFFF for siselect, even though most or all of the space may be reserved or inaccessible, permits M-mode to emulate indirectly accessed registers in this implemented range, including registers that may be standardized in the future.

Values of siselect with the most-significant bit set (bit XLEN - 1 = 1) are designated only for custom use, presumably for accessing custom registers through the alias CSRs. Values of siselect with the most-significant bit clear are designated only for standard use and are reserved until allocated to a standard architecture extension. If XLEN is changed, the most-significant bit of siselect moves to the new position, retaining its value from before.

The behavior upon accessing sireg* from M-mode or S-mode, while siselect holds a value that is not implemented at supervisor level, is UNSPECIFIED.

It is recommended that implementations raise an illegal instruction exception for such accesses, to facilitate possible emulation (by M-mode) of these accesses.

An extension is considered not to be implemented at supervisor level if machine level has disabled the extension for S-mode, such as by the settings of certain fields in CSR menvcfg, for example.

Otherwise, attempts to access sireg* from M-mode or S-mode while siselect holds a number in a standard-defined and implemented range result in specific behavior that, for each combination of siselect and siregi, is defined by the extension to which the siselect value is allocated.

Ordinarily, each siregi will access register state, access read-only 0 state, or, unless executing in a virtual machine (covered in the next section), raise an illegal instruction exception.

Note that the widths of siselect and sireg* are always the current XLEN rather than SXLEN. Hence, for example, if MXLEN = 64 and SXLEN = 32, then these registers are 64 bits when the current privilege mode is M (running RV64 code) but 32 bits when the privilege mode is S (RV32 code).

5.4. Virtual Supervisor-level CSRs

Number Privilege Width Name Description

0x250

HRW

XLEN

vsiselect

Virtual supervisor indirect register select

0x251

HRW

XLEN

vsireg

Virtual supervisor indirect register alias

0x252

HRW

XLEN

vsireg2

Virtual supervisor indirect register alias 2

0x253

HRW

XLEN

vsireg3

Virtual supervisor indirect register alias 3

0x255

HRW

XLEN

vsireg4

Virtual supervisor indirect register alias 4

0x256

HRW

XLEN

vsireg5

Virtual supervisor indirect register alias 5

0x257

HRW

XLEN

vsireg6

Virtual supervisor indirect register alias 6

The CSRs in the table above are required if the hypervisor extension is implemented. These VS CSRs all match supervisor CSRs, and substitute for those supervisor CSRs when executing in a virtual machine (in VS-mode or VU-mode).

The vsiselect register will support the value range 0..0xFFF at a minimum. A future extension may define a value range outside of this minimum range. Only if such an extension is implemented will vsiselect be required to support larger values.

Requiring a range of 0–0xFFF for vsiselect, even though most or all of the space may be reserved or inaccessible, permits a hypervisor to emulate indirectly accessed registers in this implemented range, including registers that may be standardized in the future.

More generally it is recommended that vsiselect and siselect be implemented with the same number of bits. This also avoids creation of a virtualization hole due to observable differences between vsiselect and siselect widths.

Values of vsiselect with the most-significant bit set (bit XLEN - 1 = 1) are designated only for custom use, presumably for accessing custom registers through the alias CSRs. Values of vsiselect with the most-significant bit clear are designated only for standard use and are reserved until allocated to a standard architecture extension. If XLEN is changed, the most-significant bit of vsiselect moves to the new position, retaining its value from before.

For alias CSRs sireg* and vsireg*, the hypervisor extension’s usual rules for when to raise a virtual instruction exception (based on whether an instruction is HS-qualified) are not applicable. The rules given in this section for sireg and vsireg apply instead, unless overridden by the requirements specified in the section below, which take precedence over this section when extension Smstateen is also implemented.

A virtual instruction exception is raised for attempts from VS-mode or VU-mode to directly access vsiselect or vsireg*, or attempts from VU-mode to access siselect or sireg*.

The behavior upon accessing vsireg* from M-mode or HS-mode, or accessing sireg* (really vsireg*) from VS-mode, while vsiselect holds a value that is not implemented at HS level, is UNSPECIFIED.

It is recommended that implementations raise an illegal instruction exception for such accesses, to facilitate possible emulation (by M-mode) of these accesses.

Otherwise, while vsiselect holds a number in a standard-defined and implemented range, attempts to access vsireg* from a sufficiently privileged mode, or to access sireg* (really vsireg*) from VS-mode, result in specific behavior that, for each combination of vsiselect and vsiregi, is defined by the extension to which the vsiselect value is allocated.

Ordinarily, each vsiregi will access register state, access read-only 0 state, or raise an exception (either an illegal instruction exception or, for select accesses from VS-mode, a virtual instruction exception). When vsiselect holds a value that is implemented at HS level but not at VS level, attempts to access sireg* (really vsireg*) from VS-mode will typically raise a virtual instruction exception. But there may be cases specific to an extension where different behavior is more appropriate.

Like siselect and sireg*, the widths of vsiselect and vsireg* are always the current XLEN rather than VSXLEN. Hence, for example, if HSXLEN = 64 and VSXLEN = 32, then these registers are 64 bits when accessed by a hypervisor in HS-mode (running RV64 code) but 32 bits for a guest OS in VS-mode (RV32 code).

5.5. Access control by the state-enable CSRs

If extension Smstateen is implemented together with Smcsrind, bit 60 of state-enable register mstateen0 controls access to siselect, sireg*, vsiselect, and vsireg*. When mstateen0[60]=0, an attempt to access one of these CSRs from a privilege mode less privileged than M-mode results in an illegal instruction exception. As always, the state-enable CSRs do not affect the accessibility of any state when in M-mode, only in less privileged modes. For more explanation, see the documentation for extension Smstateen.

Other extensions may specify that certain mstateen bits control access to registers accessed indirectly through siselect + sireg*, and/or vsiselect + vsireg*. However, regardless of any other mstateen bits, if mstateen0[60] = 1, a virtual instruction exception is raised as described in the previous section for all attempts from VS-mode or VU-mode to directly access vsiselect or vsireg*, and for all attempts from VU-mode to access siselect or sireg*.

If the hypervisor extension is implemented, the same bit is defined also in hypervisor CSR hstateen0, but controls access to only siselect and sireg* (really vsiselect and vsireg*), which is the state potentially accessible to a virtual machine executing in VS or VU-mode. When hstateen0[60]=0 and mstateen0[60]=1, all attempts from VS or VU-mode to access siselect or sireg* raise a virtual instruction exception, not an illegal instruction exception, regardless of the value of vsiselect or any other mstateen bit.

Extension Ssstateen is defined as the supervisor-level view of Smstateen. Therefore, the combination of Sscsrind and Ssstateen incorporates the bit defined above for hstateen0 but not that for mstateen0, since machine-level CSRs are not visible to supervisor level.

CSR address space is reserved for a possible future "Sucsrind" extension that extends indirect CSR access to user mode.

6. "Smepmp" Extension for PMP Enhancements for memory access and execution prevention in Machine mode, Version 1.0

6.1. Introduction

Being able to access the memory of a process running at a high privileged execution mode, such as the Supervisor or Machine mode, from a lower privileged mode such as the User mode, introduces an obvious attack vector since it allows for an attacker to perform privilege escalation, and tamper with the code and/or data of that process. A less obvious attack vector exists when the reverse happens, in which case an attacker instead of tampering with code and/or data that belong to a high-privileged process, can tamper with the memory of an unprivileged / less-privileged process and trick the high-privileged process to use or execute it.

To prevent this attack vector, two mechanisms known as Supervisor Memory Access Prevention (SMAP) and Supervisor Memory Execution Prevention (SMEP) were introduced in recent systems. The first one prevents the OS from accessing the memory of an unprivileged process unless a specific code path is followed, and the second one prevents the OS from executing the memory of an unprivileged process at all times. RISC-V already includes support for SMAP, through the sstatus.SUM bit, and for SMEP by always denying execution of virtual memory pages marked with the U bit, with Supervisor mode (OS) privileges, as mandated on the Privilege Spec.

Terms:

  • PMP Entry: A pair of pmpcfg[i] / pmpaddr[i] registers.

  • PMP Rule: The contents of a pmpcfg register and its associated pmpaddr register(s), that encode a valid protected physical memory region, where pmpcfg[i].A != OFF, and if pmpcfg[i].A == TOR, pmpaddr[i-1] < pmpaddr[i].

  • Ignored: Any permissions set by a matching PMP rule are ignored, and all accesses to the requested address range are allowed.

  • Enforced: Only access types configured in the PMP rule matching the requested address range are allowed; failures will cause an access-fault exception.

  • Denied: Any permissions set by a matching PMP rule are ignored, and no accesses to the requested address range are allowed.; failures will cause an access-fault exception.

  • Locked: A PMP rule/entry where the pmpcfg.L bit is set.

  • PMP reset: A reset process where all PMP settings of the hart, including locked rules/settings, are re-initialized to a set of safe defaults, before releasing the hart (back) to the firmware / OS / application.

6.1.1. Threat model

However, there are no such mechanisms available on Machine mode in the current (v1.11) Privileged Spec. It is not possible for a PMP rule to be enforced only on non-Machine modes and denied on Machine mode, to only allow access to a memory region by less-privileged modes. it is only possible to have a locked rule that will be enforced on all modes, or a rule that will be enforced on non-Machine modes and be ignored by Machine mode. So for any physical memory region which is not protected with a Locked rule, Machine mode has unlimited access, including the ability to execute it.

Without being able to protect less-privileged modes from Machine mode, it is not possible to prevent the mentioned attack vector. This becomes even more important for RISC-V than on other architectures, since implementations are allowed where a hart only has Machine and User modes available, so the whole OS will run on Machine mode instead of the non-existent Supervisor mode. In such implementations the attack surface is greatly increased, and the same kind of attacks performed on Supervisor mode and mitigated through SMAP/SMEP, can be performed on Machine mode without any available mitigations. Even on implementations with Supervisor mode present attacks are still possible against the Firmware and/or the Secure Monitor running on Machine mode.

6.2. Proposal

  1. Machine Security Configuration (mseccfg) is a new RW Machine mode CSR, used for configuring various security mechanisms present on the hart, and only accessible to Machine mode. It is 64 bits wide, and is at address 0x747 on RV64 and 0x747 (low 32bits), 0x757 (high 32bits) on RV32. All mseccfg fields defined on this proposal are WARL, and the remaining bits are reserved for future standard use and should always read zero. The reset value of mseccfg is implementation-specific, otherwise if backwards compatibility is a requirement it should reset to zero on hard reset.

  2. On mseccfg we introduce a field on bit 2 called Rule Locking Bypass (mseccfg.RLB) with the following functionality:

    1. When mseccfg.RLB is 1 locked PMP rules may be removed/modified and locked PMP entries may be edited.

    2. When mseccfg.RLB is 0 and pmpcfg.L is 1 in any rule or entry (including disabled entries), then mseccfg.RLB remains 0 and any further modifications to mseccfg.RLB are ignored until a PMP reset.

      Note that this feature is intended to be used as a debug mechanism, or as a temporary workaround during the boot process for simplifying software, and optimizing the allocation of memory and PMP rules. Using this functionality under normal operation, after the boot process is completed, should be avoided since it weakens the protection of M-mode-only rules. Vendors who don’t need this functionality may hardwire this field to 0.

  3. On mseccfg we introduce a field in bit 1 called Machine-Mode alloWlist Policy (mseccfg.MMWP). This is a sticky bit, meaning that once set it cannot be unset until a PMP reset. When set it changes the default PMP policy for M-mode when accessing memory regions that don’t have a matching PMP rule, to denied instead of ignored.

  4. On mseccfg we introduce a field in bit 0 called Machine Mode Lockdown (mseccfg.MML). This is a sticky bit, meaning that once set it cannot be unset until a PMP reset. When mseccfg.MML is set the system’s behavior changes in the following way:

    1. The meaning of pmpcfg.L changes: Instead of marking a rule as locked and enforced in all modes, it now marks a rule as M-mode-only when set and S/U-mode-only when unset. The formerly reserved encoding of pmpcfg.RW=01, and the encoding pmpcfg.LRWX=1111, now encode a Shared-Region.

      An M-mode-only rule is enforced on Machine mode and denied in Supervisor or User mode. It also remains locked so that any further modifications to its associated configuration or address registers are ignored until a PMP reset, unless mseccfg.RLB is set.

      An S/U-mode-only rule is enforced on Supervisor and User modes and denied on Machine mode.

      A Shared-Region rule is enforced on all modes, with restrictions depending on the pmpcfg.L and pmpcfg.X bits:

      • A Shared-Region rule where pmpcfg.L is not set can be used for sharing data between M-mode and S/U-mode, so is not executable. M-mode has read/write access to that region, and S/U-mode has read access if pmpcfg.X is not set, or read/write access if pmpcfg.X is set.

      • A Shared-Region rule where pmpcfg.L is set can be used for sharing code between M-mode and S/U-mode, so is not writeable. Both M-mode and S/U-mode have execute access on the region, and M-mode also has read access if pmpcfg.X is set. The rule remains locked so that any further modifications to its associated configuration or address registers are ignored until a PMP reset, unless mseccfg.RLB is set.

      • The encoding pmpcfg.LRWX=1111 can be used for sharing data between M-mode and S/U mode, where both modes only have read-only access to the region. The rule remains locked so that any further modifications to its associated configuration or address registers are ignored until a PMP reset, unless mseccfg.RLB is set.

    2. Adding a rule with executable privileges that either is M-mode-only or a locked Shared-Region is not possible and such pmpcfg writes are ignored, leaving pmpcfg unchanged. This restriction can be temporarily lifted by setting mseccfg.RLB e.g. during the boot process.

    3. Executing code with Machine mode privileges is only possible from memory regions with a matching M-mode-only rule or a locked Shared-Region rule with executable privileges. Executing code from a region without a matching rule or with a matching S/U-mode-only rule is denied.

    4. If mseccfg.MML is not set, the combination of pmpcfg.RW=01 remains reserved for future standard use.

6.2.1. Truth table when mseccfg.MML is set

Bits on pmpcfg register Result

L

R

W

X

M Mode

S/U Mode

0

0

0

0

Inaccessible region (Access Exception)

0

0

0

1

Access Exception

Execute-only region

0

0

1

0

Shared data region: Read/write on M mode, read-only on S/U mode

0

0

1

1

Shared data region: Read/write for both M and S/U mode

0

1

0

0

Access Exception

Read-only region

0

1

0

1

Access Exception

Read/Execute region

0

1

1

0

Access Exception

Read/Write region

0

1

1

1

Access Exception

Read/Write/Execute region

1

0

0

0

Locked inaccessible region* (Access Exception)

1

0

0

1

Locked Execute-only region*

Access Exception

1

0

1

0

Locked Shared code region: Execute only on both M and S/U mode.*

1

0

1

1

Locked Shared code region: Execute only on S/U mode, read/execute on M mode.*

1

1

0

0

Locked Read-only region*

Access Exception

1

1

0

1

Locked Read/Execute region*

Access Exception

1

1

1

0

Locked Read/Write region*

Access Exception

1

1

1

1

Locked Shared data region: Read only on both M and S/U mode.*

: *Locked rules cannot be removed or modified until a PMP reset, unless mseccfg.RLB is set.

6.2.2. Visual representation of the proposal

smepmp visual representation

6.3. Smepmp software discovery

Since all fields defined on mseccfg as part of this proposal are locked when set (MMWP/MML) or locked when cleared (RLB), software can’t poll them for determining the presence of Smepmp. It is expected that BootROM will set mseccfg.MMWP and/or mseccfg.MML during early boot, before jumping to the firmware, so that the firmware will be able to determine the presence of Smepmp by reading mseccfg and checking the state of mseccfg.MMWP and mseccfg.MML.

6.4. Rationale

  1. Since a CSR for security and / or global PMP behavior settings is not available with the current spec, we needed to define a new one. This new CSR will allow us to add further security configuration options in the future and also allow developers to verify the existence of the new mechanisms defined on this proposal.

  2. There are use cases where developers want to enforce PMP rules in M-mode during the boot process, that are also able to modify, merge, and / or remove later on. Since a rule that is enforced in M-mode also needs to be locked (or else badly written or malicious M-mode software can remove it at any time), the only way for developers to approach this is to keep adding PMP rules to the chain and rely on rule priority. This is a waste of PMP rules and since it’s only needed during boot, mseccfg.RLB is a simple workaround that can be used temporarily and then disabled and locked down.

    Also when mseccfg.MML is set, according to 4b it’s not possible to add a Shared-Region rule with executable privileges. So RLB can be set temporarily during the boot process to register such regions. Note that it’s still possible to register executable Shared-Region rules using initial register settings (that may include mseccfg.MML being set and the rule being set on PMP registers) on PMP reset, without using RLB.

    Be aware that RLB introduces a security vulnerability if left set after the boot process is over and in general it should be used with caution, even when used temporarily. Having editable PMP rules in M-mode gives a false sense of security since it only takes a few malicious instructions to lift any PMP restrictions this way. It doesn’t make sense to have a security control in place and leave it unprotected. Rule Locking Bypass is only meant as a way to optimize the allocation of PMP rules, catch errors durring debugging, and allow the bootrom/firmware to register executable Shared-Region rules. If developers / vendors have no use for such functionality, they should never set mseccfg.RLB and if possible hard-wire it to 0. In any case RLB should be disabled and locked as soon as possible.

    If mseccfg.RLB is not used and left unset, it wil be locked as soon as a PMP rule/entry with the pmpcfg.L bit set is configured.

    Since PMP rules with a higher priority override rules with a lower priority, locked rules must precede non-locked rules.

  3. With the current spec M-mode can access any memory region unless restricted by a PMP rule with the pmpcfg.L bit set. There are cases where this approach is overly permissive, and although it’s possible to restrict M-mode by adding PMP rules during the boot process, this can also be seen as a waste of PMP rules. Having the option to block anything by default, and use PMP as an allowlist for M-mode is considered a safer approach. This functionality may be used during the boot process or upon PMP reset, using initial register settings.

  4. The current dual meaning of the pmpcfg.L bit that marks a rule as Locked and enforced on all modes is neither flexible nor clean. With the introduction of Machine Mode Lock-down the pmpcfg.L bit distinguishes between rules that are enforced only in M-mode (M-mode-only) or only in S/U-modes (S/U-mode-only). The rule locking becomes part of the definition of an M-mode-only rule, since when a rule is added in M mode, if not locked, can be modified or removed in a few instructions. On the other hand, S/U modes can’t modify PMP rules anyway so locking them doesn’t make sense.

    1. This separation between M-mode-only and S/U-mode-only rules also allows us to distinguish which regions are to be used by processes in Machine mode (pmpcfg.L == 1) and which by Supervisor or User mode processes (pmpcfg.L == 0), in the same way the U bit on the Virtual Memory’s PTEs marks which Virtual Memory pages are to be used by User mode applications (U=1) and which by the Supervisor / OS (U=0). With this distinction in place we are able to implement memory access and execution prevention in M-mode for any physical memory region that is not M-mode-only.

      An attacker that manages to tamper with a memory region used by S/U mode, even after successfully tricking a process running in M-mode to use or execute that region, will fail to perform a successful attack since that region will be S/U-mode-only hence any access when in M-mode will trigger an access exception.

      In order to support zero-copy transfers between M-mode and S/U-mode we need to either allow shared memory regions, or introduce a mechanism similar to the sstatus.SUM bit to temporary allow the high-privileged mode (in this case M-mode) to be able to perform loads and stores on the region of a less-privileged process (in this case S/U-mode). In our case after discussion within the group it seemed a better idea to follow the first approach and have this functionality encoded on a per-rule basis to avoid the risk of leaving a temporary, global bypass active when exiting M-mode, hence rendering memory access prevention useless.

      Although it’s possible to use mstatus.MPRV in M-mode to read/write data on an S/U-mode-only region using general purpose registers for copying, this will happen with S/U-mode permissions, honoring any MMU restrictions put in place by S-mode. Of course it’s still possible for M-mode to tamper with the page tables and / or add S/U-mode-only rules and bypass the protections put in place by S-mode but if an attacker has managed to compromise M-mode to such extent, no security guarantees are possible in any way. Also note that the threat model we present here assumes buggy software in M-mode, not compromised software. We considered disabling mstatus.MPRV but it seemed too much and out of scope.

      Shared-region rules can be used both for zero-copy data transfers and for sharing code segments. The latter may be used for example to allow S/U-mode to execute code by the vendor, that makes use of some vendor-specific ISA extension, without having to go through the firmware with an ecall. This is similar to the vDSO approach followed on Linux, that allows userspace code to execute kernel code without having to perform a system call.

      To make sure that shared data regions can’t be executed and shared code regions can’t be modified, the encoding changes the meaning of the pmpcfg.X bit. In case of shared data regions, with the exception of the pmpcfg.LRWX=1111 encoding, the pmpcfg.X bit marks the capability of S/U-mode to write to that region, so it’s not possible to encode an executable shared data region. In case of shared code regions, the pmpcfg.X bit marks the capability of M-mode to read from that region, and since pmpcfg.RW=01 is used for encoding the shared region, it’s not possible to encode a shared writable code region.

      For adding Shared-region rules with executable privileges to share code segments between M-mode and S/U-mode, mseccfg.RLB needs to be implemented, or else such rules can only be added together with mseccfg.MML being set on PMP Reset. That’s because the reserved encoding pmpcfg.RW=01 being used for Shared-region rules is only defined when mseccfg.MML is set, and 4b prevents the adition of rules with executable privileges on M-mode after mseccfg.MML is set unless mseccfg.RLB is also set.

      Using the pmpcfg.LRWX=1111 encoding for a locked shared read-only data region was decided later on, its initial meaning was an M-mode-only read/write/execute region. The reason for that change was that the already defined shared data regions were not locked, so r/w access to M-mode couldn’t be restricted. In the same way we have execute-only shared code regions for both modes, it was decided to also be able to allow a least-privileged shared data region for both modes. This approach allows for example to share the .text section of an ELF with a shared code region and the .rodata section with a locked shared data region, without allowing M-mode to modify .rodata. We also decided that having a locked read/write/execute region in M-mode doesn’t make much sense and could be dangerous, since M-mode won’t be able to add further restrictions there (as in the case of S/U-mode where S-mode can further limit access to an pmpcfg.LWRX=0111 region through the MMU), leaving the possibility of modifying an executable region in M-mode open.

      For encoding Shared-region rules initially we used one of the two reserved bits on pmpcfg (bit 5) but in order to avoid allocating an extra bit, since those bits are a very limited resource, it was decided to use the reserved R=0,W=1 combination.

    2. The idea with this restriction is that after the Firmware or the OS running in M-mode is initialized and mseccfg.MML is set, no new code regions are expected to be added since nothing else is expected to run in M-mode (everything else will run in S/U mode). Since we want to limit the attack surface of the system as much as possible, it makes sense to disallow any new code regions which may include malicious code, to be added/executed in M-mode.

    3. In case mseccfg.MMWP is not set, M-mode can still access and execute any region not covered by a PMP rule. Since we try to prevent M-mode from executing malicious code and since an attacker may manage to place code on some region not covered by PMP (e.g. a directly-addressable flash memory), we need to ensure that M-mode can only execute the code segments initialized during firmware / OS initialization.

    4. We are only using the encoding pmpcfg.RW=01 together with mseccfg.MML, if mseccfg.MML is not set the encoding remains usable for future use.

7. "Smcntrpmf" Cycle and Instret Privilege Mode Filtering, Version 1.0

7.1. Introduction

The cycle and instret counters serve to support user mode self-profiling usages, wherein a user can read the counter(s) twice and compute the delta(s) to evaluate user software performance and behavior. By default, these counters are not filtered by privilege mode, and thus they continue to increment while traps (e.g., page faults or interrupts) to more privileged code are handled. This causes two problems:

  • It introduces unpredictable noise to the counter values observed by the user.

  • It leaks information about privileged software execution to user mode.

Smcntrpmf remedies these issues by introducing privilege mode filtering for the cycle and instret counters.

7.2. CSRs

7.2.1. Machine Counter Configuration (mcyclecfg, minstretcfg) Registers

mcyclecfg and minstretcfg are 64-bit registers that configure privilege mode filtering for the cycle and instret counters, respectively.

63 62 61 60 59 58 57:0

0

MINH

SINH

UINH

VSINH

VUINH

WPRI

Field Description

MINH

If set, then counting of events in M-mode is inhibited

SINH

If set, then counting of events in S/HS-mode is inhibited

UINH

If set, then counting of events in U-mode is inhibited

VSINH

If set, then counting of events in VS-mode is inhibited

VUINH

If set, then counting of events in VU-mode is inhibited

When all xINH bits are zero, event counting is enabled in all modes.

For each bit in 61:58, if the associated privilege mode is not implemented, the bit is read-only zero. Bits 57:56 are reserved for possible future modes.

For RV32, bits 63:32 of mcyclecfg can be accessed via the mcyclecfgh CSR, and bits 63:32 of minstretcfg can be accessed via the minstretcfgh CSR.

The CSR numbers are 0x321 for mcyclecfg, 0x322 for minstretcfg, 0x721 for mcyclecfgh, and 0x722 for minstretcfgh.

The content of these registers may be accessible from Supervisor level if the Smcdeleg/Ssccfg extensions are implemented.

The more natural CSR number for mcyclecfg would be 0x320, but that was allocated to mcountinhibit.

This register format matches that specified for programmable counters by Sscofpmf. The bit position for the OF bit (bit 63) is read-only 0, since these counters do not generate local counter overflow interrupts on overflow.

7.3. Counter Behavior

The fundamental behavior of cycle and instret is modified in that counting does not occur while executing in an inhibited privilege mode. Further, the following defines how transitions between a non-inhibited privilege mode and an inhibited privilege mode are counted.

The cycle counter will simply count CPU cycles while the CPU is in a non-inhibited privilege mode. Mode transition operations (traps and trap returns) may take multiple clock cycles, and the change of privilege mode may be reported as occurring in any one of those cycles (possibly different for each occurrence of a trap or trap return).

The RISC-V ISA has no requirement that the number of cycles for a trap or trap return be the same for all occurrences. Implementations are free to determine the extent to which this number may be consistent and predictable (or not), and the same is true for the specific cycle in which privilege mode changes.

For the instret counter, most instructions do not affect mode transitions, so for those the behavior is clear: instructions that retire in a non-inhibited mode increment instret, and instructions that retire in an inhibited mode do not. There are two types of instructions that can affect a privilege mode change: instructions that cause synchronous exceptions to a more privileged mode, and xRET instructions that return to a less privileged mode. The former are not considered to retire, and hence do not increment instret. The latter do retire, and should increment instret only if the originating privilege mode is not inhibited.

The instret definition above is intended to ensure that the counter increments in a predictable fashion. For example, consider a scenario where minstretcfg is configured such that all modes other than U-mode are inhibited. A user mode load should increment only once, even if it takes a page fault or other exception. With this definition, the faulting execution of the load will not increment (it does not retire), the handler instructions will not increment (they execute in an inhibited mode), including the xRET (it arguably retires in a non-inhibited mode, but it originates in an inhibited mode). Only once the load is re-executed and retires will it increment instret.

In cases where an instruction is emulated by software running in a privilege mode that is inhibited in minstretcfg, the emulation routine must emulate the instret increment.

8. "Smrnmi" Extension for Resumable Non-Maskable Interrupts, Version 1.0

The base machine-level architecture supports only unresumable non-maskable interrupts (UNMIs), where the NMI jumps to a handler in machine mode, overwriting the current mepc and mcause register values. If the hart had been executing machine-mode code in a trap handler, the previous values in mepc and mcause would not be recoverable and so execution is not generally resumable.

The Smrnmi extension adds support for resumable non-maskable interrupts (RNMIs) to RISC-V. The extension adds four new CSRs (mnepc, mncause, mnstatus, and mnscratch) to hold the interrupted state, and one new instruction, MNRET, to resume from the RNMI handler.

8.1. RNMI Interrupt Signals

The rnmi interrupt signals are inputs to the hart. These interrupts have higher priority than any other interrupt or exception on the hart and cannot be disabled by software. Specifically, they are not disabled by clearing the mstatus.MIE register.

8.2. RNMI Handler Addresses

The RNMI interrupt trap handler address is implementation-defined.

RNMI also has an associated exception trap handler address, which is implementation defined.

For example, some implementations might use the address specified in mtvec as the RNMI exception trap handler.

8.3. RNMI CSRs

This proposal adds additional M-mode CSRs to enable a resumable non-maskable interrupt (RNMI).

Diagram
Figure 38. Resumable NMI scratch register mnscratch

The mnscratch CSR holds an MXLEN-bit read-write register which enables the NMI trap handler to save and restore the context that was interrupted.

Diagram
Figure 39. Resumable NMI program counter mnepc.

The mnepc CSR is an MXLEN-bit read-write register which on entry to the NMI trap handler holds the PC of the instruction that took the interrupt.

The low bit of mnepc (mnepc[0]) is always zero. On implementations that support only IALIGN=32, the two low bits (mnepc[1:0]) are always zero.

If an implementation allows IALIGN to be either 16 or 32 (by changing CSR misa, for example), then, whenever IALIGN=32, bit mnepc[1] is masked on reads so that it appears to be 0. This masking occurs also for the implicit read by the MRET instruction. Though masked, mnepc[1] remains writable when IALIGN=32.

mnepc is a WARL register that must be able to hold all valid virtual addresses. It need not be capable of holding all possible invalid addresses. Prior to writing mnepc, implementations may convert an invalid address into some other invalid address that mnepc is capable of holding.