Key points of this post
- Delegation is a way to choose, with one bit in
medelegormideleg, "this trap, when taken from S or U, is handled by S". A delegatedebreakwent to the S handler, and the M handler saw only theecallthat returned control (two traps if not delegated). A trap taken in M stayed in M even when delegated, andmedeleg[11] (M'secall) read back 0 after writing 1. When S takes a trap,scause,sepc,stvalandsstatus.SPP,SPIE,SIEchange, whilemepc,mcause,mtvalandMPPare left alone. - Whether an interrupt is taken depends on the current mode and the mode it goes to. All 24 combinations (3 modes x 2 sources x 4
MIE/SIEsettings) followed the rule. In M, MSI neededMIE=1 and a delegated SSI was never taken. In S, SSI was taken only withSIE=1, and in U both were always taken. For interrupts pending at once, the spec order is MSI, MTI, SEI, SSI, STI, but QEMU's default configuration went lowest number first (SSI, MSI, STI, MTI, SEI). Turning onsmaiaandssaiagave the spec order. - WFI is a hint that an implementation may build as a NOP. WFI in M-mode and in S-mode with
TW=0 waited for the 20,000-tick timer and woke up (mepc=WFI+4), while S-mode withTW=1 and U-mode (even withTW=0) raised an illegal-instruction exception within 70 to 420 ticks. A delegated STI withsstatus.SIE=0 woke WFI without a trap.
Part 25 opened up M-mode's set of trap state (mepc, mcause, mtval, MIE/MPIE/MPP, mtvec, mret). There every trap came into M. An operating system does not want to go through firmware for common traps such as system calls, page faults and timers, so the spec defines delegation, where M hands such traps straight to S. This post covers delegation itself, the S-mode trap CSRs, which traps can be delegated, priority when more than one is pending (for synchronous exceptions and for interrupts separately), the global bits that filter interrupts (MIE and SIE), and WFI, all checked with the same QEMU experiments. How to build this in a pipeline is Part 27.
The setup is the same as in Part 25: QEMU 11.1.3 virt, riscv64-elf-gcc 16.2, specification version 20240411, RV64 only, with -cpu rv64,c=false,h=false (C and H off) as the default configuration. The test code is probe.c (181 lines) and start.S (279 lines). start.S has an M handler and an S handler, and both write the traps they receive into rec[] (M) and srec[] (S) and the order received into seq[]. check.py runs it under three configurations (base, h with H on, and aia with the AIA extensions on), compares 86 expected values, and writes results.json (section 7).
1. Delegation: medeleg and mideleg
By default every trap, from any mode, is taken in M (Privileged 3.1.8). An M handler can send it back to S with mret, but that is slow. So a hart with S has two registers.
| Register | Width | Meaning of bit i |
|---|---|---|
medeleg |
64 bits (on RV32, medelegh is the upper 32 bits) |
delegate the synchronous exception with mcause=i |
mideleg |
MXLEN | delegate the interrupt that is bit i of mip |
Setting a bit sends that trap, "when taken from S or U", to S's handler. Item by item, what the spec defines:
| Item | When a delegated trap enters S |
|---|---|
| Written | scause, sepc, stval, mstatus.SPP (previous mode), SPIE <- SIE, SIE <- 0 |
| Not written | mcause, mepc, mtval, MPP, MPIE |
pc |
stvec (direct or vectored) |
| Direction | Traps only go to higher modes. A trap taken in M stays in M even if delegated. A trap taken in S can be taken by S (a horizontal trap) |
| Interrupts | A delegated interrupt is masked at the delegating mode (M) |
The last row matters. For example, if STI is delegated (mideleg[5]=1), an STI is not taken while M is running. If it is not delegated, it goes to M from any mode. This leads to the gating rules of section 3.
What can and cannot be delegated
An implementation may subset the delegatable traps, and which bits work is found by "writing ones to every bit and reading back" (3.1.8). Two things are fixed by the spec. medeleg may not have read-only-one bits (a delegatable exception must also be possible to leave undelegated), and bits for exceptions that cannot occur in lower modes must be read-only zero. The typical case is medeleg[11], because an M-mode ecall has nowhere to be delegated to. Writing all ones on QEMU and reading back gave:
| Register | Configuration | Read value | Bits set |
|---|---|---|---|
medeleg |
h=false |
0xf4b7ff |
0 to 10, 12, 13, 15, 18, 20 to 23 |
mideleg |
h=false |
0x666 |
1, 2, 5, 6, 9, 10 |
mideleg |
h=true |
0x1666 |
1, 2, 5, 6, 9, 10, 12 |
mie |
h=false |
0xffffffffffff0aaa |
1, 3, 5, 7, 9, 11, 16 to 63 |
How to read it: bit 11 is missing from medeleg, as the spec says (M's ecall). Reserved numbers 14, 16, 17 and 19 are also missing. But QEMU set 10 (VS-mode ecall) and 20 to 23 (guest page faults) even in a configuration with H off, bits that are useless on a hart without H. That is an implementation choice. In a design, making absent bits read-only zero lets software that reads them discover the implementation's range. In mideleg, 3, 7 and 11 (M-mode software, timer and external interrupts) are missing, so M's own interrupts cannot be delegated (the spec says M interrupt bits may not be read-only one). 1, 5 and 9 (SSI, STI, SEI) are the delegation bits for S interrupts, 2, 6 and 10 are VS-mode interrupts (numbers from the H extension), and turning H on adds 12 (SGEI).
Checking the delegation path directly
We raised four triggers (ebreak, an illegal instruction, ecall, and a lw from an unmapped address) in M, S and U, with the matching medeleg bit set and clear, and recorded which handler (M or S) took it.

A few additions:
- For a delegated trap from S or U, the M handler recorded exactly one trap: the
ecallthe test used to get back to M. Without delegation there are two (the original trap plus theecall). So "mcause,mepcandmtvalwere not written" was confirmed through the M handler not running at all. Readingmcauseafter the trap was not possible, because the returningecallitself overwritesmcause. - A delegated trap's
scause,sepcandstvalequalled themcause,mepcandmtvalof the undelegated case (3 forebreak,sepcthe instruction,stvalits address). With the same shape, the S handler can share code with the M handler. - An
ecallfrom S is taken by S itself whenmedeleg[9] is set. The note in 3.3.1 says thatecallcauses differ by mode because of selective delegation, and gives as the typical Unix-like use delegating only U'secall(8) to S and nothing else. That is why our test used an MSI (a write to CLINTmsip) as the way back instead ofecall: with 9 delegated, S'secallnever reaches M.
2. S-mode trap CSRs
S has four CSRs with the same structure as M's (Privileged 10.1.2 and 10.1.6 to 10.1.9).
| S-mode | M-mode | What it does |
|---|---|---|
stvec |
mtvec |
trap entry address (direct or vectored) |
sepc |
mepc |
return address |
scause |
mcause |
cause; top bit is the interrupt flag |
stval |
mtval |
address or instruction bits |
sscratch |
mscratch |
scratch CSR for handlers |
It is not only the names. The meaning of the values is the same. The low bits of sepc, the WLRL field of scause (it must hold the numbers 0 to 31), and what stval holds for each exception follow the same rules as mepc, mcause and mtval in Part 25. The vectored mode of stvec is the same too. The spec's example: "a supervisor-mode timer interrupt causes the pc to be set to BASE+0x14."
The corresponding mstatus fields appear in sstatus (the views of Part 24). Where M had MIE/MPIE/MPP (two bits), S has SIE/SPIE/SPP. SPP is one bit because the previous mode for a trap into S can only be U or S. We delegated the same ebreak to S, raised it from S and from U, and recorded the values right after entry and after sret. The "after" value is the mstatus at the moment the returning trap entered M.
from SIE | entry: SPP SPIE SIE | sret: SPP SPIE SIE
S 1 | 1 1 0 | 0 1 1
S 0 | 1 0 0 | 0 1 0
U 1 | 0 1 0 | 0 1 1
U 0 | 0 0 0 | 0 1 0
The table's rule in one line: on entry SPP = the origin mode (0 for U, else 1), SPIE = old SIE, SIE = 0. sret restores SIE = SPIE, mode = SPP, SPIE = 1, SPP = 0 (U) (10.1.1). It has the same shape as M's mret, with the two-bit MPP shrunk to one bit. In every row SPP is 0 after sret, the same safety measure as MPP going to U after mret in Part 25.
We also checked the vectored mode of stvec. We delegated SEI (9) and SSI (1), wrote stvec = svtable|1, and ran in U. The S handler took two traps, and the last slot entered was 9. The rule that the slot number is the cause number (BASE+4 x cause) is the same as in M. The order is covered in section 4.
3. When an interrupt is taken: MIE and SIE
Two things must hold for an interrupt i to become a trap (Privileged 3.1.9 and 10.1.3).
- Bit
iofmipand bitiofmieare both 1. - The global condition holds for the mode the interrupt goes to. If
mideleg[i]=0 it goes to M: when the current mode is M,MIEmust be 1, and in S and U it always passes. Ifmideleg[i]=1 it goes to S: when the current mode is S,SIEmust be 1, in U it always passes, and in M it is not taken.
For the current mode x, the global bits are used like this (3.1.6.1). Interrupts for x are enabled only when xIE=1. Interrupts for lower modes w<x are always disabled, whatever wIE says. Interrupts for higher modes y>x are always enabled, whatever yIE says. That is why in U the SIE of S is ignored and S interrupts are always enabled (the sstatus description), and M's MIE is not used in S and U.
We ran all combinations: three modes, two interrupt sources (the undelegated MSI, and SSI delegated to S), and the four settings of MIE and SIE. With the interrupt held pending, we ran 64 nops in that mode and counted how often the M handler and the S handler took it.

Each cell in the figure was run with the other bit at both 0 and 1 and gave the same result. What stands out is that SSI is masked in all four cells of the M row. It is delegated through mideleg, so M does not take it whatever SIE or MIE is. That same SSI is pending in mip and, according to the spec, wakes WFI (section 6; this combination was not tested).
There is one timing rule. These conditions must be evaluated within a bounded time after an interrupt becomes or ceases to be pending, and immediately after an xRET or a write to a dependent CSR such as mstatus, mie, mip or mideleg. It is the same reason as the mret rule in Part 25.
4. Interrupt priority
When several interrupts are pending at once, only one is taken. The spec's order has two levels. Interrupts going to M come before those going to S, and within one mode the order is fixed.
| Taken by | Highest first |
|---|---|
| M | MEI, MSI, MTI, SEI, SSI, STI, LCOFI (counter overflow) |
| S | SEI, SSI, STI, LCOFI |
Platform interrupts numbered 16 and above have platform-defined priority and are usually placed highest. The reasons are in a spec note. Higher-mode interrupts must be served first to support preemption, external interrupts come before internal ones because devices need quick service, and software interrupts (inter-processor messages) come before timers (time slicing).
There are two experiments. (a) In M, we made MSI, MTI, SEI, SSI and STI all pending (MEI was left out because it needs an interrupt controller) and turned on MIE. (b) We delegated SEI, SSI and STI to S, made MSI and MTI pending as well, and ran in U. The handler clears the mie bit of the interrupt it received and returns, so the order received is the priority.

What the results show:
- The mode split (interrupts for M first) was right even in the default configuration. In (b), MSI and MTI came first, then the three for S.
- The order within a mode differed from the spec in QEMU's default configuration. It took them lowest number first. The same held with H on. With
-cpu rv64,smaia=true,ssaia=true(the AIA extensions) the order matched the spec (MSI, MTI, SEI, SSI, STI). The spec decides which is right (the table above), and we report that QEMU 11.1.3's default path does not follow this order. - A priority encoder for interrupts is simple in hardware. Compute
pending & mie, split it into an M part and an S part, and pass each through a fixed-order priority encoder. In a design you use the table above as is, with nothing new to decide. The order among synchronous exceptions is set by the table in section 5, and how to handle an interrupt and an exception meeting at one instruction boundary is covered in Part 27 together with the pipeline stages.
5. Synchronous exception priority
Order matters only when one instruction has more than one exception condition. The spec puts an order table in the mcause section (3.1.15). From highest:
| Order | Cause | Condition |
|---|---|---|
| 1 | 3 | instruction address breakpoint |
| 2 | 12, 1 | during instruction address translation: first page or access fault encountered |
| 3 | 1 | access fault on the physical address of the instruction |
| 4 | 2, 0, 8/9/11, 3, 3 | illegal instruction, instruction address misaligned, environment call, ebreak, load/store address breakpoint |
| 5 | 4, 6 | (optional) load/store/AMO address misaligned |
| 6 | 13, 15, 5, 7 | during address translation of an explicit access: first page or access fault encountered |
| 7 | 5, 7 | access fault on the physical address of an explicit access |
| 8 | 4, 6 | load/store/AMO address misaligned, if not already taken above |
The spec puts the misaligned exception in two places in this table. A load/store/AMO misaligned exception may come before or after translation and protection checks (rows 5 and 8, "up to the implementation"). The reasoning: an implementation that never supports misaligned accesses can raise the exception without translating, while one that supports misaligned access only at some physical addresses must translate and check first. And an instruction address misaligned exception is raised by "the control-flow instruction", not by fetching, so it ranks below other instruction-address exceptions (row 4).
We tested cases where one instruction had two conditions on QEMU. In S-mode we ran lw, lr.w and amoadd.w at the same address, an odd address (a) combined with an address (b) that gives an access fault or a page fault. For the faulting address we tried four causes: a nonexistent physical address, RAM that PMP denies, an invalid PTE, and a valid PTE whose physical address does not exist. The numbers in the table are mcause.
| Address situation | lw |
lr.w |
amoadd.w |
|---|---|---|---|
| nonexistent physical, odd | 5 | 4 | 6 |
| PMP denied, odd | 5 | 4 | 6 |
| PMP denied, even | 5 | 5 | 7 |
| invalid PTE, odd | 13 | 4 | 6 |
| invalid PTE, even | 13 | 13 | 15 |
| valid PTE, no physical, odd | 5 | 4 | 6 |
| valid PTE, no physical, even | 5 | 5 | 7 |
| RAM, odd (only one condition) | none | 4 | 6 |
Reading it is simple. At odd addresses, atomic instructions (lr, sc, AMO) raised the misaligned exception (4 or 6) before the access fault or page fault. That is the choice in row 5 of the spec table: the alignment check comes before translation. At even addresses they got the fault (5, 13, 7, 15). A plain lw or sw never raises a misaligned exception at an odd address (section 4 of Part 25), so only the fault appeared, which means row 8 ("if not taken above") never happens for QEMU's lw. In the same last row, RAM at an odd address raised no trap for lw (and the same for sw). This choice is the implementation's freedom and the spec allows it.
We also tested a jump. jalr to a target of odd+2 at an unmapped address (0x20002), an invalid-PTE address, and a valid address with no physical memory. All three gave mcause=0 (instruction address misaligned) with mepc equal to the jalr. The jump instruction raises the misaligned exception before the target is checked, the same result as the spec note's "misaligned is raised by the control-flow instruction".
Two things could not be tested. Breakpoints (rows 1 and 4) need debug triggers (Sdtrig), covered in Part 37. And sc.w without a reservation fails and does not touch memory, so it raised no trap at an even address, a valid PTE and a nonexistent physical address (whether an sc that fails without a reservation can raise an access fault seems to be a corner the spec does not settle; this is a guess).
6. WFI
wfi is a hint that "the hart may be stalled until an interrupt might need servicing" (Privileged 3.3.3). A summary of what the spec says:
- An implementation may build
wfias a NOP. The reason for waking need not be an interrupt. So software should putwfiin a loop and check after waking what happened, usingmipandsip. - The wake-up condition is the individual interrupt enable (
mie). The global bits (MIE,SIE) andmidelegdo not affect WFI. An interrupt delegated to a lower mode wakes it, and so does one that is globally disabled. - If the waking interrupt is taken, the trap happens on the following instruction, so
mepc=pc+ 4. If the hart woke without taking an interrupt, execution just continues atpc+ 4. - If
mstatus.TW(Timeout Wait, bit 21; 3.1.6.5) is 1, awfiexecuted in a less-privileged mode that does not complete within an implementation-specific bounded time raises an illegal-instruction exception. An implementation may simply raise it always. With S implemented, awfiin U-mode raises an illegal-instruction exception regardless ofTWunless it completes within the bounded time.
The test has two parts. We set the MTI timer for 20,000 ticks ahead (the device tree's timebase-frequency is 10 MHz, so that is 2 ms) and ran wfi in the modes below, recording the difference of the time CSR. The last two rows delegate STI with the Sstc extension's stimecmp and set sstatus.SIE to 0 and 1.
| Case | Result | Ticks |
|---|---|---|
M, MIE=0 |
woke without a trap | about 30,000 |
M, MIE=1 |
MTI trap, mepc=WFI+4 |
about 24,000 |
M, TW=1 |
woke without a trap (TW does not apply to M) |
about 30,000 |
S, TW=0 |
MTI trap, mepc=WFI+4 |
about 30,000 |
S, TW=1 |
illegal instruction (mcause=2) |
90 |
U, TW=0 |
illegal instruction | 420 |
U, TW=1 |
illegal instruction | 70 |
S, STI delegated, SIE=0 |
woke without a trap, sip.STIP=1 |
about 30,000 |
S, STI delegated, SIE=1 |
S trap scause=0x8000000000000005, sepc=WFI+4 |
about 30,000 |
Wake-ups took longer than the 20,000-tick target (24,000 to 31,000) because QEMU waits in host time, and it varies from run to run. All this test can say is "it waited longer than 20,000 ticks". The cases that ended in an illegal instruction (70 to 420 ticks) did not wait.
Three things to read in the table. First, TW had no effect on M and made wfi illegal only in S. QEMU treated wfi with TW=1 in S-mode as illegal immediately (no waiting), the simplest reading of "bounded time". That choice fits the use case of virtualization, trapping wfi to switch to another guest. Second, in U with S present, wfi was illegal even with TW=0. Third, the last two rows show that the wake condition is the individual enable and the global bit does not matter. With sstatus.SIE=0, a delegated STI that was pending with sie.STIE set woke wfi (without a trap), and with SIE=1 the same moment went to the S handler.
In a design WFI can be as simple as you like. A common implementation stalls the pipeline at wfi and releases it when (mip & mie) != 0 (with no global bits or mideleg), and a core that wants to save power gates the clock. The simplest way to implement TW is to raise an illegal instruction always for wfi in lower modes when TW=1 (the spec allows it). If an interrupt is already pending during the wait, release immediately on the spot.
7. Summary of the experiments
The method is the same as in Part 25. start.S has an M handler (trap_entry) and an S handler (strap_entry) that record traps into rec[] and srec[] and record the order into seq[]. When an interrupt arrives, the mie bit of its source is cleared and the handler returns. There are two ways back to M: ecall (a7=0) and MSI (leave_flag). The heart of the delegation test in probe.c:
/* origin org (0=M, 1=S, 2=U), delegation dl */
WR("medeleg", dl ? (1UL << cause_bit) : 0);
if (org == 0) trig(); /* directly in M */
else enter_mode(org == 1 ? 1 : 0, wrap); /* S or U */
/* handler that took the first trap: bit 62 set means S */
by = (seq[0] >> 62) & 1 ? 'S' : 'M';
check.py confirmed all 86 expected values computed from the spec.
| Expectation | Result |
|---|---|
| a delegated trap from S or U goes to S, everything else to M (24 cases) | matched |
on entry SPP=origin mode, SPIE=SIE, SIE=0 / after sret SIE=SPIE, SPIE=1, SPP=0 |
matched (four cases) |
| interrupt gating, 24 cells | matched |
| interrupt order (spec order) | matched only in the AIA configuration; the default is ascending number |
WFI: M independent of TW, S illegal with TW=1, U always illegal |
matched |
| delegated STI and WFI | SIE=0 only wakes, SIE=1 gives an S trap |
The only disagreement with the spec was interrupt priority, and it matched in the configuration with the AIA extensions on. Where QEMU is not cycle accurate (the waiting time of WFI) we did not compare an upper bound, and only judged "waited" or "did not wait".
8. Design checklist: delegation, S traps, priority, WFI
| Item | Rule |
|---|---|
| Delegation bits | A delegatable exception must also be undelegatable (no read-only one). Exceptions that cannot occur in lower modes (M's ecall, 11) are read-only zero. Unimplemented bits are read-only zero as well |
mideleg |
M interrupts (3, 7, 11) cannot be delegated, only SSI, STI and SEI (1, 5, 9). A delegated interrupt is masked in M |
| Trap direction | Only to higher modes. A trap taken in M goes to M whatever the delegation bit says. Delegation test: "current mode < M and bit = 1" |
| Entering S | scause, sepc, stval, SPP <- origin mode (0 for U, else 1), SPIE <- SIE, SIE <- 0. M-side CSRs, MPP and MPIE untouched |
sret |
SIE <- SPIE, mode <- SPP, SPIE <- 1, SPP <- U. With TSR=1, sret in S is illegal |
| Global interrupt enable | For current mode x: interrupts for x follow xIE, lower modes always off, higher modes always on. SIE is ignored in U |
| When to evaluate | Right after writes to mip, mie, mstatus, mideleg, sip, sie, and after mret and sret |
| Interrupt priority | M side first. M: MEI > MSI > MTI > SEI > SSI > STI > LCOFI, S: SEI > SSI > STI > LCOFI. 16 and above are the platform's |
| Exception priority | The table of section 5. The order of misaligned versus access and page faults is an implementation choice; document it |
| Instruction address misaligned | Raised by the jump, not by fetching. Ranks below an access fault on the same instruction address |
| WFI | A NOP is legal. The wake condition is mie & mip != 0 (ignoring global bits and mideleg). After waking the trap is taken on the next instruction, mepc=pc+4. After waking, software checks the cause |
TW and WFI in U |
With TW=1, wfi in lower modes is illegal after a time limit. Always raising it is allowed. With S present, wfi in U is illegal regardless of TW |
Virtualization bits in mstatus |
TW, TVM and TSR are read-only zero without S (3.1.6.5) |
Summary
- Delegation uses the
medelegandmidelegbits so that S takes traps raised in S and U. When delegated, M'smcause,mepc,mtvalandMPPare not written, and S'sscause,sepc,stval,SPP,SPIEandSIEare. A trap taken in M stays in M even if delegated, and M'secall(11) and M interrupts have no delegation bit. - With a lower current mode, interrupts for M are always taken, and with a higher one the delegated ones are masked. In the same mode the global bit (
MIEorSIE) decides. All 24 combinations followed the rule, andSIEwas ignored in U. - For interrupt priority, M's come first, then MEI > MSI > MTI > SEI > SSI > STI. QEMU's default configuration was ascending by number, and only turning on
smaiaandssaiagave the spec order. In synchronous exception priority, the order between misaligned and faults is an implementation choice, and QEMU raised misaligned only for atomic instructions, and it came before the fault. - WFI is a hint that may be a NOP, and the wake condition is the individual enable. With
TW=1, WFI in S and in U became illegal. A delegated STI woke WFI even withSIE=0.
Next: Part 27 puts these rules into a pipeline. We look at what a precise exception is, at which stage a trap is detected, how to flush and redirect pc, at which instruction boundary interrupts are taken, and how the priority table above turns into per-stage detection signals.
References
- The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Version 20240411. 3.1.6.1 Privilege and global interrupt-enable stack, 3.1.6.5
TVM,TWandTSRinmstatus, 3.1.8medelegandmideleg, 3.1.9mipandmie(interrupt conditions and priority), 3.1.15mcause(synchronous exception priority table), 3.3.1ecallandebreak, 3.3.2 Trap-return instructions, 3.3.3 WFI, 10.1.1sstatus, 10.1.2stvec, 10.1.3sipandsie, 10.1.6 to 10.1.9sscratch,sepc,scause,stval. https://github.com/riscv/riscv-isa-manual - The RISC-V Instruction Set Manual, Volume I: Unprivileged Architecture, Version 20240411. 2.5 Control transfer instructions (instruction address misaligned), 2.6 Load and store (misaligned accesses), chapter 14 A extension (misaligned exception and access fault).
- D. Harris et al., RISC-V System-on-Chip Design, 2023. Trap delegation and privileged unit implementation (CORE-V Wally)
- QEMU documentation: RISC-V
virtboard, CPU options (smaia,ssaia,sstc). https://www.qemu.org/docs/master/system/target-riscv.html

