Skip to content
systemcoding.dev
Kernels

RISC-V Privilege Modes: M, S and U Explained

Learn what machine, supervisor and user mode each control on RISC-V, how traps are delegated between them, and how firmware drops into S mode with mret.

8 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the RISC-V, Linux and Intel logos.

Every RISC-V program runs in one of a small number of privilege modes, and the mode decides which instructions work, which registers can be touched and who handles a fault. A kernel author meets this on the first day, because the code that boots the machine, the code that is the operating system and the code that is an application all run in different modes. This post explains the three modes a kernel cares about, the one extra that hypervisors add, how the hardware moves between them, and how firmware hands control to a supervisor-mode kernel with a single instruction. No prior RISC-V knowledge is assumed beyond what a register is.

Everything here comes from the RISC-V Instruction Set Manual, Volume II: Privileged Architecture. The code examples are the short pieces of machine-mode setup that a firmware performs before it starts a kernel, as OpenSBI does on QEMU's virt machine.

Three modes, three jobs

RISC-V defines privilege levels as numbers, stored in two-bit fields: user is 0, supervisor is 1, and machine is 3. Level 2 was reserved for an older hypervisor design and is unused. A processor must implement machine mode, and the other two are optional, which is how the same architecture covers a tiny microcontroller and a server.

Machine mode (M) is the only mandatory one and the most powerful. Code here can read and write every register and every address, and it handles every trap unless it passes them down. Firmware lives here: it initializes the board, sets up memory protection, and offers services to the layer above. A microcontroller with only M mode runs all its code there.

Supervisor mode (S) is for operating system kernels. It has its own set of control registers, the s-prefixed CSRs, and its own trap handling and virtual memory. It cannot touch machine-mode state, and it cannot touch physical memory that machine mode has fenced off. An operating system kernel sits here.

User mode (U) is for applications. It can run ordinary instructions and nothing else: no access to any privileged register, no direct device access, and memory limited to what the kernel mapped for it. Anything beyond that is a request to the kernel through the ecall instruction.

A useful way to hold the three together: each mode trusts the one above it and protects itself from the one below. Firmware trusts nothing it did not write, the kernel trusts the firmware, and applications are trusted by nobody.

ModeLevelRunsCan access
Machine3Firmware, bootloader stagesEverything
Supervisor1Operating system kernels* CSRs, memory allowed by M mode, page tables
User0ApplicationsOnly mapped user pages, plus ecall

Hypervisor extension in one paragraph

Modern cores can also implement the hypervisor extension, which adds a virtualization mode. It splits supervisor mode into a hypervisor-extended supervisor mode (HS) and virtual modes, VS and VU, for a guest operating system and its applications, with a second stage of address translation. A kernel written for plain S mode runs unchanged as a guest. You do not need the extension to write a kernel, and a guest kernel never sees it, so this post ignores it from here on.

How the CPU moves between modes

The CPU changes mode in exactly two ways: a trap raises privilege, and a return instruction lowers it. There is no instruction that says "switch to supervisor mode".

A trap is an exception, such as an illegal instruction, or an interrupt, such as a timer. By default a trap goes to machine mode. The hardware stores the previous mode, sets the program counter to the trap handler's address in mtvec, and records the cause in mcause and the faulting address in mepc. A trap from a lower mode to machine mode is the architecture's only way to enter M.

A return goes the other way. mret returns from a machine-mode trap, restoring the mode that the mstatus.MPP field recorded, and sret returns from a supervisor-mode trap, restoring the mode that sstatus.SPP recorded. Because the return instruction reads the previous mode from a register you can write, software enters a lower mode by writing the target mode into that field and then executing the return. That is the whole mechanism behind starting a kernel or a user program.

The ecall instruction deliberately causes a trap whose cause depends on the mode it executed in: cause 8 from user mode, 9 from supervisor mode and 11 from machine mode. That is how an application asks the kernel for something, and how the kernel asks the firmware.

Delegation: who handles which trap

If every trap went to machine mode, the firmware would have to forward every system call and every page fault to the kernel, wasting thousands of cycles. RISC-V avoids this with delegation. Two machine-mode registers, medeleg and mideleg, hold one bit per exception and per interrupt. A set bit sends that trap straight to supervisor mode if it happened in S or U mode, and clears machine mode out of the path.

For a typical kernel, the firmware delegates the traps that the kernel can handle: page faults, system calls from user mode, and the supervisor timer, software and external interrupts. It deliberately leaves the others, such as an ecall from S mode, with itself, because that one is the kernel asking the firmware for service.

firmware.cc
// Machine-mode setup performed before starting a supervisor-mode kernel.
#define MSTATUS_MPP_MASK (3UL << 11)
#define MSTATUS_MPP_S    (1UL << 11)

void drop_to_supervisor(unsigned long kernel_entry, unsigned long hartid, unsigned long dtb)
{
    // Return to S mode when mret runs.
    unsigned long x = csr_read(mstatus);
    x &= ~MSTATUS_MPP_MASK;
    x |= MSTATUS_MPP_S;
    csr_write(mstatus, x);

    // Where mret will jump.
    csr_write(mepc, kernel_entry);

    // The kernel starts with paging off.
    csr_write(satp, 0);

    // Delegate nearly every exception and every interrupt to S mode...
    csr_write(medeleg, 0xFFFFUL & ~(1UL << 9) & ~(1UL << 11));   // keep ecall from S and M in M mode
    csr_write(mideleg, 0xFFFFUL);

    // ...let S mode use the supervisor interrupt sources.
    csr_set(sie, (1UL << 1) | (1UL << 5) | (1UL << 9));

    // Physical memory protection: give S and U mode the whole address space.
    csr_write(pmpaddr0, 0x3FFFFFFFFFFFFFUL);
    csr_write(pmpcfg0, 0xF);                                    // TOR, read, write, execute

    asm volatile("mv a0, %0; mv a1, %1; mret" : : "r"(hartid), "r"(dtb));
}

That function is what a firmware does in a few lines. Setting mstatus.MPP to 1 and mepc to the kernel's entry address, then mret, lands in supervisor mode at that address. The values in a0 and a1 pass the hart ID and device tree to the kernel, which is the convention every RISC-V kernel entry point expects.

Physical memory protection

Supervisor mode has virtual memory, and machine mode has something simpler for the layer below: Physical Memory Protection. A handful of region registers, pmpaddr0 to pmpaddr15 with configuration bytes packed into pmpcfg0 and up, define address ranges and the read, write and execute permissions that S and U mode have inside them. Machine mode is exempt by default. If a region does not cover an address, supervisor and user code cannot touch it, and the access faults.

The setup above gives S mode everything, because the top-of-range region ending at 0x3FFFFFFFFFFFFF shifted covers all of physical memory. A real firmware shrinks that: OpenSBI protects its own code and data so the kernel cannot overwrite the firmware that provides its services. That protection is the point of having a mode below machine mode.

Seeing delegation work

The clearest demonstration of the layering is an ecall from supervisor mode, since it must trap to M mode, and the handler can say so. Suppose a tiny machine-mode trap handler is installed in mtvec:

firmware.cc
void m_trap(void)
{
    unsigned long cause = csr_read(mcause);
    if (cause == 9) {
        puts("M-mode: ecall from S-mode, service request in a7\n");
        csr_write(mepc, csr_read(mepc) + 4);          // resume after the ecall
    } else {
        puts("M-mode: unexpected trap\n");
    }
}

The kernel executes ecall once. The handler runs in machine mode, because medeleg bit 9 was left clear, and prints:

Text
M-mode: ecall from S-mode, service request in a7

Had bit 9 been set, the same ecall would have trapped into the kernel's own handler instead, and the firmware would never have seen it. The mechanism is the same for every cause, which is why the delegation registers are the main configuration a firmware performs.

How a kernel finds out what it can touch

A supervisor-mode kernel cannot read mstatus or any other machine register. Executing csrr a0, mstatus in S mode raises an illegal instruction exception. This restriction is by design, and it means the kernel learns about the machine from its two arguments, the device tree pointer in a1 and the services in SBI. It also means any attempt to read hardware state that firmware has not exposed fails visibly, rather than returning a stale value.

In the other direction, the kernel controls what user mode may do through sstatus bits and through page table permissions. The user bit in each page table entry decides whether user code may touch the page, and the SUM bit in sstatus decides whether the kernel may touch user pages at all. Each mode manages the one below it with the tools it was given.

Boundaries

This three-mode picture is accurate for a general-purpose system with firmware, a kernel and applications. It does not describe every RISC-V part. A small microcontroller may implement only M mode, or M and U, with no supervisor mode and so no virtual memory. A kernel for it, an RTOS for example, runs in M mode and treats U as an optional sandbox. The hypervisor extension reshapes the picture again for virtualization.

The practical rule for a first kernel is simple: write for S mode, expect firmware to have done the machine-mode work, and learn the M-mode details only when you target hardware with no firmware or when you decide to write that firmware yourself.

Also inAssembly
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.