5. Traps, the frame, the UART
Why this layer exists
A hypervisor is a trap handler with opinions. A nested page fault, a guest’s ecall, a virtio doorbell, the KVM_RUN loop returning to userspace: each is “something happened to the guest, here is its state, decide.” The state arrives as a frame the handler built, and the decision is made by reading a cause register and branching. This chapter builds that machinery for a kernel with no guest yet, on one hart, in S-mode: what the hardware does when a trap is taken, what sret undoes, the 280-byte frame the software adds around it (frozen here and reused in later parts), and the first device that interrupts, the UART, with the platform-level interrupt controller (PLIC) in front of it.
The chapter has a second job. Chapter 3 defined the three words (trap, exception, interrupt), the delegation registers and the registers a delegated trap writes, and chapter 4 named scause and stval for page faults. Nothing yet says what order the hardware does things in, why the return needs no frame, or how a device’s wire becomes scause 9. The Mechanism derives each step from the privileged specification, the PLIC specification and the 16550 datasheet, with the board’s own behaviour kept apart and tied to a captured run under labs/ch05/ex/. The last Mechanism section answers a question the syllabus asks of this chapter: why a driver is not a library.
Mechanism
Two kinds of event, and the register that tells them apart
Chapter 3 defined the three words, and the difference it drew (synchronous with an instruction, or arriving between instructions) is what the rest of this chapter uses. Which of the two a given trap was is recorded in one bit. The specification for scause: “The Interrupt bit in the scause register is set if the trap was caused by an interrupt. The Exception Code field contains a code identifying the last exception or interrupt.” On RV64 the Interrupt bit is bit 63, so an interrupt makes scause negative as a signed value, and a handler separates the two with one comparison.
The codes this book uses in S-mode, from the specification’s tables, are:
scause |
Interrupt bit | Code | Meaning | Where this book meets it |
|---|---|---|---|---|
0x2 |
0 | 2 | illegal instruction | the probe of this chapter |
0x3 |
0 | 3 | breakpoint | delegated; ember never executes ebreak, the breakpoint instruction |
0x8 |
0 | 8 | environment call from U-mode | chapter 7 |
0xc, 0xd, 0xf |
0 | 12, 13, 15 | instruction, load, store/AMO page fault | chapter 4’s faults, now taken in S |
0x8000000000000001 |
1 | 1 | supervisor software interrupt | chapter 6’s tick |
0x8000000000000005 |
1 | 5 | supervisor timer interrupt | named in chapter 6, not used |
0x8000000000000009 |
1 | 9 | supervisor external interrupt | this chapter’s UART |
The two kinds ask different things of the handler, and the difference comes from synchrony. An exception has an instruction that did not complete. The handler can repair the cause and return, so the instruction runs again; it can step past the instruction by changing the return address; or it can give up. An interrupt has no guilty instruction: the one that was executing is innocent, and returning with the same address resumes the interrupted code exactly where it was. The specification’s sentence for sepc covers both: “When a trap is taken into S-mode, sepc is written with the virtual address of the instruction that was interrupted or that encountered the exception.” An exception handler that must make progress past the instruction therefore changes sepc before it returns, as skip_illegal below does; an interrupt handler leaves it alone.
Asynchrony has a second consequence. Interrupted code did not agree to be interrupted, so every register it held is live. The handler has to preserve all of them, which is what the frame is for.
ecall: an exception on purpose
Chapter 2 glossed ecall as the instruction a program executes to ask the kernel for service, and chapters 2 and 3 pointed here. The specification’s text: “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 it “performs no other operation.” It is a synchronous exception that the program causes deliberately, so everything above applies, with one detail that chapter 3 noted for mepc: the saved address is the ecall itself, “not the address of the following instruction”, and the handler adds 4 before returning if it means to resume after it.
There is one cause code per originating mode, 8 for U, 9 for S and 11 for M, and the specification gives the reason: “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.” That is this chapter’s delegation set: bit 8 is in it, bit 9 is not. Nothing in this chapter executes an ecall from U-mode, because the first U program arrives in chapter 7; the bit is set now so that the trap entry and the cause table are final by then. An ecall executed in S-mode is cause 9, is not delegated, and so reaches M, which is how a supervisor asks the firmware under it for service (chapter 2’s OpenSBI owns that role by default; with -bios none the M shim of chapter 3 would be the receiver).
What the hardware does on a trap into S
The decision comes first: does this trap go to S or to M? Chapter 3 gave the rule and the specification’s words for it. A trap goes to M “unless delegated”; a bit set in medeleg or mideleg delegates the matching trap “when occurring in S-mode or U-mode, to the S-mode trap handler”; and “traps never transition from a more-privileged mode to a less-privileged mode”, so a trap that arises in M stays in M whatever the bits say. In ember’s run that means a delegated trap from S or U lands in S.
When the trap does go to S, the hart does the following, listed here in an order meant for reading. The specification states the writes without sequencing them, and no instruction executes between two of them: the trap is one event.
sepcis written with the virtual address of the instruction that was interrupted or that took the exception.scauseis written with the code, interrupt bit included.stvalis written with “exception-specific information to assist software in handling the trap”, the faulting address for an address fault and the instruction word for an illegal instruction on a hart that does so (chapter 3 sorted what is required from what is optional). For other traps it is zero.sstatus.SPPis written with the privilege mode the trap came from: “SPP is set to 0 if the trap originated from user mode, or 1 otherwise.”sstatus.SPIEis written with the valuesstatus.SIEhad.sstatus.SIEis cleared.- The program counter is loaded from
stvec, by the rule in the next section.
Items 4 to 6 are the privilege stack chapter 3 quoted, “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”, with x = S. The stack is one level deep for S: SPIE and SPP hold exactly one previous state. Item 6 is what keeps the handler from being interrupted by another interrupt destined for S (a machine-level one is gated by M’s own rules, as chapter 3 showed). A second S-level interrupt arriving while the first is being handled waits, because SIE is 0 in S, until the handler returns and sret restores it. A handler that wants to be interrupted by a later event has to save sepc and the SPIE and SPP fields first, since a nested trap would overwrite them; ember never does this.
This hart has the H extension, and ember’s S-mode is its HS-mode (chapter 3). The hypervisor chapter’s trap-entry text adds to the list: V is set to 0, hstatus.SPV records the previous virtualization state, and the trap also writes hstatus.GVA and the CSRs htval and htinst: “A trap into HS-mode also writes field GVA in hstatus, fields SPIE and SIE in sstatus, and CSRs sepc, scause, stval, htval, and htinst.” Chapter 18 defines those; every trap this chapter takes comes from V=0.
The side run trap-sstatus reads sstatus inside the handler for two traps, and shows items 4 to 6 on the board. Its patch deletes the thread-context drain from uart_irq_on, so the first byte arrives as an interrupt. The mask 0x122 keeps SIE (bit 1), SPIE (bit 5) and SPP (bit 8):
S: trap sepc=probe scause=0x2 stval=0xf14022f3
S: exception: sstatus & 0x122 = 0x100
S: interrupt: scause=0x8000000000000009 sip=0x200 sstatus & 0x122 = 0x120
The probe trap came from S with SIE clear: SPP is 1, SPIE took the old SIE (0) and SIE is 0. The external interrupt came from S with SIE set, which the lab turns on last: SPP is 1, SPIE is 1 (the stacked copy), SIE is 0 (cleared on entry). The interrupt line also shows sip, the S view of the pending interrupts (the section on the three gates below), with only bit 9 set, the external-interrupt bit SEIP, when the handler runs.
What the hardware does not do matters as much. It saves no general-purpose register and does not touch sp: the first instruction of the handler runs with every register as the interrupted code left it, on the stack the interrupted code was using. It does not change satp, so the handler runs under the same translation as the code it interrupted, and stvec, a virtual address while satp is active, has to be mapped in that translation (ember’s identity map makes it so). Chapter 3’s x86 table says what the other architecture does on a privilege change: it loads the destination ring’s stack from the TSS. RISC-V’s trap switches no stack, and a frame is the handler’s own business.
What sret undoes
sret is the return from a trap taken in S. The specification gives it in four places, as it did for mret, counting the hypervisor chapter. The status text: “When an SRET instruction ... is executed to return from the trap handler, the privilege level is set to user mode if the SPP bit is 0, or supervisor mode if the SPP bit is 1; SPP is then set to 0”, and “When an SRET instruction is executed, SIE is set to SPIE, then SPIE is set to 1.” The privilege-stack rule adds MPRV: “If y≠M, xRET also sets MPRV=0”. The trap-return text adds the program counter, “xRET sets the pc to the value stored in the xepc register”. And the hypervisor chapter’s account for an SRET executed with V=0, which is the case here: “SRET first determines what the new privilege mode will be according to the values in hstatus.SPV and sstatus.SPP ... SRET then sets hstatus.SPV=0, and in sstatus sets SPP=0, SIE=SPIE, and SPIE=1. Lastly, SRET sets the privilege mode as previously determined, and sets pc=sepc.”
Put together, sret does these things as one step:
- The new mode comes from SPP (and, with H, SPV): 1 returns to S, 0 to U.
pcbecomessepc.- SIE takes SPIE’s value.
- SPIE becomes 1.
- SPP becomes 0, the least-privileged mode. The reason is the one chapter 3 quoted for
mret: it “helps identify software bugs in the management of the two-level privilege-mode stack”, since ansretwith no trap behind it returns to U. - MPRV becomes 0, because the new mode is not M.
- With H, SPV becomes 0.
Two consequences matter below. The first is the timing rule from the interrupt text: the conditions for taking an interrupt “must also be evaluated immediately following the execution of an SRET instruction”. If an enabled interrupt is already pending when sret restores SIE to 1, the hart takes it at once, before the next instruction of the interrupted code runs. A handler does not need to loop and re-check.
The second is what sret leaves alone. It reads sepc and sstatus and writes sstatus. It reads no general-purpose register and no memory, restores nothing from a stack, and does not touch scause or stval. Whatever the handler used has to be put back by the handler, and the frame is where it is saved.
stvec: direct and vectored
stvec (CSR 0x105) holds the trap vector: “a vector base address (BASE) and a vector mode (MODE)”. The register keeps only bits XLEN-1 through 2 of the base, “When used as an address, the lower two bits are filled with zeroes”, so a handler’s address is always 4-byte aligned, and MODE is bits 1:0. The modes, from the specification’s table: 0 is Direct, “All exceptions set pc to BASE” (the text under it says “all traps into supervisor mode cause the pc to be set to the address in the BASE field”), and 1 is Vectored, “Asynchronous interrupts set pc to BASE+4×cause”; 2 and above are reserved. In Vectored mode “all synchronous exceptions into supervisor 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.” The specification’s own example is the supervisor timer interrupt, cause 5, which lands at BASE+0x14. By the same arithmetic the supervisor software interrupt (cause 1) is BASE+0x4 and the supervisor external interrupt (cause 9) is BASE+0x24.
The alignment rule has two halves. The base is 4-byte aligned by construction. And “MODE settings other than Direct might impose additional alignment constraints on the value in the BASE field”, which the specification leaves to the implementation. The register is WARL (chapter 3), and the board’s answers come from the side run stvec-probe, which writes ten values from S and reads each back:
S: stvec at reset 0x0
S: stvec wrote 0x80001000 read 0x80001000
S: stvec wrote 0x80001001 read 0x80001001
S: stvec wrote 0x80001004 read 0x80001004
S: stvec wrote 0x80001005 read 0x80001005
S: stvec wrote 0x80001010 read 0x80001010
S: stvec wrote 0x80001011 read 0x80001011
S: stvec wrote 0x80001002 read 0x80001011
S: stvec wrote 0x80001003 read 0x80001011
S: stvec wrote 0x80001100 read 0x80001100
S: stvec wrote 0x80001101 read 0x80001101
stvec resets to 0, as chapter 3 found. Direct and Vectored writes are kept whole at every 4-byte-aligned base tried, including 0x80001004 with MODE 1, so this board asks for nothing beyond the 4-byte alignment in either mode. A write whose low bits are 2 or 3, the reserved MODEs, leaves the register unchanged, base included; this is the same whole-write refusal mtvec showed in chapter 3, and it is the board’s choice. One consequence for trap.S: its .align 2 is what keeps the low bits of the entry address zero. An entry at an address ending in 2 would be written with MODE 2 and, on this board, not written at all.
Vectored mode saves the interrupt dispatch and nothing else. Each slot is four bytes, so it holds one jump to a real handler, and that handler still has to save what it uses. Exceptions, which are every page fault and ecall, and most hypervisor exits, of the later parts, all share BASE in either mode, so the entry has to dispatch on scause anyway. ember uses Direct mode: one entry, trap_entry, saves the frame once, and trapper branches on the cause.
The side run vectored shows the vectored rules on the board. Its table has sixteen jumps in slots 0 to 15. Slot 0 goes to trap_entry. Slot 9 goes to a handler that prints which way it was reached. Every other slot goes to a stub that prints “wrong slot” and halts, so that an exception routed by its cause number would reveal itself:
S: trap sepc=probe scause=0x2 stval=0xf14022f3
S: vectored: scause=0x8000000000000009 came in through slot 9
ember
chars=0x6
PASS
The probe is cause 2, which would be BASE+0x8 if exceptions were routed by cause; it reached trap_entry at BASE, the stub at slot 2 stayed silent, and trapper printed its usual line. The first UART interrupt, cause 9, reached the handler at BASE+0x24. The handler for slot 9 is a C function with GCC’s interrupt("supervisor") attribute, which makes the compiler save what the function uses and return with sret. The side run removes the thread-context drain from uart_irq_on (a later section explains it) so that the first byte can only arrive as an interrupt.
Interrupts into S: three gates
An interrupt has to get through three conditions to become a trap in S, and the first two are per-source.
The first is the pending bit. sip holds “information on pending interrupts”, and bit i of it is interrupt cause i. sip is not a register of its own: “The sip and sie registers are subsets of the mip and mie registers.” What S sees of mip is restricted by delegation: “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.” So the supervisor external interrupt, bit 9, is visible to S only because mideleg bit 9 is set, and the software interrupt, bit 1, only because bit 1 is set. Who sets the bit differs. SSIP is “writable in mip”, which is how chapter 6’s M code injects a tick (it writes mip), and it is writable in sip, which is how S clears it. SEIP is not: “If implemented, SEIP is read-only in sip, and is set and cleared by the execution environment, typically through a platform-specific interrupt controller.” S cannot clear a pending external interrupt by writing sip. It clears when the interrupt controller stops asserting it, and on this board that is the claim described below.
The second is the enable bit: bit i of sie, with SEIE at bit 9 and SSIE at bit 1. The third is the global gate, and the specification states all three at once: “An interrupt i will trap to S-mode if both of the following are true: (a) either the current privilege mode is S and the SIE bit in the sstatus register is set, or the current privilege mode has less privilege than S-mode; and (b) bit i is set in both sip and sie.” Two details sit in it. When the hart is in U-mode “the value in SIE is ignored, and supervisor-level interrupts are enabled”: a user program is preemptible whatever sstatus.SIE says. And delegation masks at the other end: “Delegated interrupts result in the interrupt being masked at the delegator privilege level.” While the hart is in M, as it is inside the shim, a delegated interrupt is not taken at all; it stays pending until the hart is back in S.
When several S-destined interrupts are pending the order is fixed: “SEI, SSI, STI, LCOFI” (the last is the local counter-overflow interrupt, outside this book). And “Interrupts to S-mode take priority over any interrupts to lower privilege modes.”
The evaluation rule from the last section applies to each gate. The conditions “must also be evaluated immediately following ... an explicit write to a CSR on which these interrupt trap conditions expressly depend (including sip, sie and sstatus).” The trap therefore arrives right after the csrs sstatus that opens the last gate, not at some later point, a fact the next sections use.
The frame: why software, why 280, why sstatus at 272
Everything above leaves the handler with a problem. It is C code, which will clobber ra, t0 to t6 and a0 to a7 at once, and it may be entered between any two instructions of code that was using all 31 registers. The register file is the part of the interrupted state the hardware saves nothing of, so the entry code saves it. It does so on the stack, in a fixed layout that is also the interface the handler’s C code uses to read, and change, the interrupted state. That layout is struct trapframe, and the figure shows it.
The arithmetic is short. Register x0 is constant zero and needs no slot, so 31 registers, x1 to x31, are saved. Each slot is 8 bytes, and the slot for register xn is at offset : ra (x1) at 0, sp (x2) at 8, gp at 16, up to t6 (x31) at 240. The 31 slots end at 248. Four CSR slots follow, sepc at 248, scause at 256, stval at 264 and sstatus at 272, and 272 + 8 = 280. The frame is bytes.
That is also why sstatus sits at 272, and why the frame cannot be 272 bytes. The entry begins with addi sp, sp, -N and stores into slots at positive offsets from the new sp. With N = 272 the store sd t0, 272(sp) lands at the old sp itself, the lowest word of the interrupted code’s own stack, one slot outside the frame, and the exit never restores it. The sstatus slot is last because struct trapframe lists it last and later chapters read tf->sstatus; the order, once chosen, is frozen with the code.
The sp slot holds a computed value. By the time the CSR reads run, sp has been moved down by 280, so storing it as is would save a number that means nothing to the handler. The entry stores sp + 280 instead: the stack pointer the interrupted code had, the value that addi sp, sp, 280 at the exit reconstructs.
The two halves of the frame differ in who consumes them. On the way out the restore code loads the 31 registers from their slots and does not touch the four CSR slots. sret does not read the frame at all (see above): it reads the CSRs sepc and sstatus directly. The CSR slots in the frame are copies for the handler’s C code to read. This exit does not copy them back, so a handler that wants to change the return address writes the CSR, as skip_illegal does, and a write to the frame’s sepc slot has no effect. Whether the frame is copied back is the entry and exit code’s choice and not the hardware’s: chapter 7’s user return does write sepc from the frame, because its system calls advance tf->sepc. Exercise (d) runs the case for this entry.
The frame is pushed on the stack the interrupted code was using. For S-mode code with a kernel stack that is fine. For code that interrupted U-mode, sp would be a user address that the kernel cannot trust, which is why chapter 7 builds a second entry that swaps in a kernel stack with sscratch first. This chapter has only the one entry.
One property of the frozen layout is wrong. 280 is not a multiple of 16: the frame is 8 bytes short of 288. The interrupted sp is 16-byte aligned, so the sp that trapper runs on is 8 bytes off, and the calling convention asks for more. The RISC-V psABI (the processor-specific ABI, the calling convention chapter 2 introduced) says “the stack pointer shall be aligned to a 128-bit boundary upon procedure entry” and “In the standard ABI, the stack pointer must remain aligned throughout procedure execution. Non-standard ABI code must realign the stack pointer prior to invoking standard ABI procedures.” trap_entry is not standard ABI code: it moves an aligned sp by 280 and then calls trapper. The side run frame-align prints the frame’s address and the saved sp, both modulo 16:
S: frame address mod 16 = 0x8, saved sp mod 16 = 0x0
Nothing in this chapter’s handler needs the missing alignment, since rv64ima has no stack access wider than 8 bytes, but that is a property of this instruction set and this code, not a guarantee. The frame is frozen and used as it stands through the later parts. A handler that needs a 16-byte-aligned object, or a compiler that emits a 16-byte access to the stack, would hit this. Exercise (e) shows the fix and its cost.
Delegation, switched on
Chapter 3 derived medeleg and mideleg and left them untouched, so every trap there went to M. trap_init_m writes both, from M, before the drop. They are M CSRs, and S writing one is an illegal instruction by chapter 3’s CSR access rule; before trap_init_m’s medeleg write that trap goes to M, and after it bit 2 sends it to S. Each bit has a reason:
| Register | Bit | Cause | Why it is delegated |
|---|---|---|---|
medeleg |
2 | illegal instruction | the probe, and every instruction S may not run |
medeleg |
3 | breakpoint | an S-mode debugger’s ebreak |
medeleg |
8 | ecall from U |
chapter 7’s system calls |
medeleg |
12, 13, 15 | instruction, load, store/AMO page fault | chapter 4’s faults, now S’s to handle |
mideleg |
1 | supervisor software interrupt | chapter 6’s injected tick |
mideleg |
9 | supervisor external interrupt | this chapter’s UART |
Bits not set stay with M. medeleg bit 9, the ecall from S, is the one the earlier section named. Bit 11, an ecall from M, is read-only zero (“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”), and the access faults (causes 1, 5, 7), which PMP and the platform raise, are not in the set either: they reach M. The mideleg write reads back 0x1646 on this board, as chapter 3’s delegation-probe run shows, because the reset value 0x1444 already holds bits 2, 6, 10 and 12. Bit 9 of mideleg, as above, is what makes SEIP visible in sip.
The ordering within main matters. trap_init_m runs in M before the drop, so the delegation is in place for S’s first trap. trap_init then runs in S, after mem_init and before anything can trap, because stvec is 0 until it is written. What a trap does before that depends on the image. Chapter 3’s exercise (d) ran with translation off and only cause 2 delegated: the fetch at address 0 was an instruction access fault, cause 1, which is not delegated and went to M. In this image translation is on and address 0 is unmapped, so the fetch at 0 is an instruction page fault, cause 12, which is delegated: it vectors to stvec, which is still 0, faults again, and repeats in S with nothing printed and M never entered. The side run stvec-unset removes the trap_init() call and shows the silence:
S: second map
qemu-system-riscv64: terminating on signal 15 from pid N (timeout)
The probe’s own trap never prints its line, so the loop starts at the probe. That the loop is the page fault, and not something else, follows from the steps above and from the delegation table; the transcript shows only that the hart stops reporting.
The 16550’s receive side
Chapter 2 gave the UART’s registers and used the transmit side and the polling read. This chapter uses the receive side with interrupts, so three registers get a closer look, from the Texas Instruments PC16550D datasheet. The board’s UART is QEMU’s model of this chip (ns16550a in the device tree), and what the model does is a board fact kept apart from the datasheet below.
LSR bit 0, DR (data ready). “Bit 0 is set to a logic 1 whenever a complete incoming character has been received and transferred into the Receiver Buffer Register or the FIFO. Bit 0 is reset to a logic 0 by reading all of the data in the Receiver Buffer Register or the FIFO.” uart_getc from chapter 2 tests it before every read.
IER bit 0. “This bit enables the Received Data Available Interrupt (and timeout interrupts in the FIFO mode) when set to logic 1.” The chip has four interrupt types with a fixed priority, and the datasheet names the order: “Receiver Line Status; Received Data Ready; Transmitter Holding Register Empty; and MODEM Status.” Only the second is enabled here. The datasheet also says disabling an interrupt “prevents it from being indicated as active in the IIR and from activating the INTR output signal”, so IER is what gates the chip’s output line, and nothing in the chip’s data path changes.
IIR. The interrupt identification register reports which interrupt is pending. “When bit 0 is a logic 0, an interrupt is pending”, and the datasheet’s table encodes each type in the register’s low four bits, 0100 for received data available. The same table gives the reset for each type; for this one it is “Reading the Receiver Buffer Register” (in FIFO mode, “or the FIFO drops below the trigger level”). The interrupt is a state the chip reports while its source condition holds, and reading RBR ends it. On that description the INTR output stays asserted until the read. ember never reads IIR: handle_uart loops on LSR.DR instead, which is correct because the received-data interrupt is the only one enabled, and a driver with a second source would have to read IIR to tell them apart.
On the board, QEMU’s model recomputes its output from the chip’s state in serial_update_irq: the received-data interrupt is asserted while IER bit 0 and LSR.DR are set and, with the FIFO disabled, nothing else is needed (QEMU v11.1.1, hw/char/serial.c). That is the level the PLIC sees.
The code warns against writing FCR: “QEMU already stuffed input.txt, and a FIFO enable/reset drops the first byte.” Two sources stand behind it. The datasheet: “Writing a 1 to FCR0 enables both the XMIT and RCVR FIFOs. Resetting FCR0 will clear all bytes in both FIFOs. When changing from the FIFO Mode to the 16450 Mode and vice versa, data is automatically cleared from the FIFOs.” And QEMU’s model, in the FCR write path: “Did the enable/disable flag change? If so, make sure FIFOs get flushed”, after which the receive FIFO and DR are cleared. By the time uart_irq_on runs, the lab’s first input byte is already waiting in the receive register; clearing the FIFO throws it away. Exercise (b) runs it.
The PLIC as a protocol
The PLIC is the device between every wire that can interrupt a hart and the hart’s interrupt input. In the specification’s terms, gateways turn device signals into requests, the PLIC core ranks the pending ones for each target, and a target claims one at a time. The target is a hart context, “a given privilege mode on a given hart”, and the notification arrives in the context’s own bit of mip: “Interrupt notifications generated by the PLIC appear in the meip/seip bits of the mip/sip registers for M/S modes respectively”, with the qualifier that “The notification only appear in lower-privilege xip registers if external interrupts have been delegated to the lower-privilege modes.” That is mideleg bit 9 again.
The PLIC spec (1.0.0) lays out the registers from a platform-chosen base. Per the specification’s memory map, with source s and context c:
| Register | Offset from the base | Meaning |
|---|---|---|
| source priority | 4 × s | 32-bit; 0 means “never interrupt”, 1 is the lowest active priority |
| pending | 0x1000 + 4 × (s div 32), bit s mod 32 |
one bit per source |
| enable | 0x2000 + 0x80 × c + 4 × (s div 32), bit s mod 32 |
one bit per source, per context |
| threshold | 0x200000 + 0x1000 × c |
per context |
| claim / complete | 0x200004 + 0x1000 × c |
per context; one register, read to claim, write to complete |
Three board facts set the numbers. The base is 0xc000000 (“virt_memmap” in QEMU’s hw/riscv/virt.c, and the PLIC node’s reg in the device tree). Which context is which is outside the PLIC specification: “How PLIC organizes interrupts for the contexts (Hart and privilege mode) is out of RISC-V PLIC specification scope, however it must be spec-out in vendor’s PLIC specification.” On QEMU’s virt, the device tree states it. The PLIC node’s interrupts-extended is a list of (interrupt controller, cause) pairs, one entry per context in order, as the Linux binding describes, and the side script plic-dtb.sh dumps the board’s:
interrupt-controller@c000000 {
phandle = <0x03>;
riscv,ndev = <0x5f>;
reg = <0x00 0xc000000 0x00 0x600000>;
interrupts-extended = <0x02 0x0b 0x02 0x09>;
interrupt-controller;
compatible = "sifive,plic-1.0.0", "riscv,plic0";
#address-cells = <0x00>;
#interrupt-cells = <0x01>;
};
serial@10000000 {
interrupts = <0x0a>;
interrupt-parent = <0x03>;
reg = <0x00 0x10000000 0x00 0x100>;
compatible = "ns16550a";
};
Entry 0 is the hart’s interrupt controller with cause 11, machine external; entry 1 is the same controller with cause 9, supervisor external. So context 0 is M on hart 0, and context 1 is S on hart 0. QEMU builds this from a per-hart configuration string, “MS” for a hart with S-mode, so hart h has M at context 2h and S at context 2h+1 (riscv_plic_hart_config_string in hw/riscv/boot.c; with KVM the string is “S” alone and the numbering shifts, which is why code should read it from the tree and not from a constant). The UART is source 10: its node’s interrupts is 0xa with the PLIC as parent, and UART0_IRQ = 10 in include/hw/riscv/virt.h. riscv,ndev, 0x5f here, is the binding’s count of external interrupts the controller supports, 95.
Substituting, source 10 for context 1:
- priority register:
0x0c000000+ 40 =0x0c000028, in the first page of the PLIC; - enable word:
0x0c000000+0x2000+0x80=0x0c002080, bit 10 (the word is the first of the context’s block, covering sources 0 to 31); - threshold:
0x0c201000; - claim and complete:
0x0c201004.
The enable and claim addresses are far from the base: 0xc002080 is two pages up and 0xc201004 is over 2 MiB up. Chapter 4’s identity map covers the PLIC’s first 4 MiB for that reason, and a map of only the base page makes the first access beyond it fault with scause 13. Exercise (c) runs it and says which access that is.
The protocol has three conditions on the PLIC side. A source reaches a context when “the priority of the pending interrupts exceeds a per-target threshold”, and the threshold text is “The PLIC will mask all PLIC interrupts of a priority less than or equal to threshold. For example, a threshold value of zero permits all interrupts with non-zero priority.” The source must also be enabled for that context, by its enable bit. And ties between sources of the same priority go to the lowest ID: “interrupts with the lowest ID have the highest effective priority.” plic_init_uart sets priority 1, the lowest active level, sets the context-1 enable bit for source 10 and sets context 1’s threshold to 0, so priority 1 exceeds 0. All three are written because the code does not assume the board’s reset values; the order is free, since IER is not yet set and the UART’s line is low.
Between the device and the PLIC’s core sits the gateway, and its rule is the center of the protocol. “At most one interrupt request per interrupt source can be pending in the PLIC core at any time ... The gateway only forwards a new interrupt request to the PLIC core after receiving notification that the interrupt handler servicing the previous interrupt request from the same source has completed.” For a level-sensitive source, “On receiving an interrupt completion message, if the interrupt is level-triggered and the interrupt is still asserted, a new interrupt request will be forwarded to the PLIC core.” The hart does two things with its context, claim and complete. A claim is a load from the context’s claim register: “the PLIC core will atomically determine the ID of the highest-priority pending interrupt for the target and then clear down the corresponding source’s IP bit. The PLIC core will then return the ID to the target. The PLIC core will return an ID of zero, if there were no pending interrupts for the target when the claim was serviced.” A complete is a store of the ID to the same register: “The PLIC signals it has completed executing an interrupt handler by writing the interrupt ID it received from the claim to the claim/complete register.” The spec adds that “The PLIC does not check whether the completion ID is the same as the last claim ID for that target. If the completion ID does not match an interrupt source that is currently enabled for the target, the completion is silently ignored.” ID 0 means no interrupt, so a claim that returns 0 has nothing to complete.
The side run skip-complete takes the first UART interrupt through the claim and the complete. Its patch deletes the thread-context drain, so the first byte can only arrive as an interrupt, and it writes nothing to the UART between the claim and the complete: a write to the UART would itself raise the line and confuse the reading. It records sip at three points and the LSR at the first two, and prints them at the end:
S: claimed: lsr=0x61 sip=0x0
S: read one byte, next byte arrived, no complete: lsr=0x61 sip=0x0
S: after complete: lsr=0x61 sip=0x200
The first line follows the claim. A byte is waiting (LSR 0x61 has DR, bit 0, set) and sip is 0: the claim consumed the notification, and the SEIP bit, read-only to S, went with it. By the second line the handler has read one byte and the next has arrived (DR is set again), a new request from the same source while the first is still claimed, and sip is still 0. The third line follows the complete, and sip is 0x200. A request that arrives while its source is claimed is held back until the complete, which is the gateway rule above. A handler that never completes would be notified of nothing further from this source, and the hart would sit in wfi while the UART had bytes waiting. QEMU models the hold with a per-source “claimed” bit: set at claim and cleared at complete, with claimed sources excluded from delivery, while the pending bit is latched on every raise from the device (sifive_plic.c). The specification goes further for a level source (“if the interrupt is level-triggered and the interrupt is still asserted, a new interrupt request will be forwarded”); this run does not test that sentence, and QEMU’s complete does not sample the line.
Two details of the spec explain code in trapper. A claim can return 0, so trapper completes only if (src). And the notification “is only guaranteed to hold an EIP value that was valid at some point in the past”: an interrupt can have been notified and then found already taken or gone, which is the reason a claim must be tolerated when it returns nothing, or returns a source whose device has nothing left to say.
Drain, then unmask
uart_irq_on has to bring up the interrupt path from nothing. Its order is the lesson: the first version of this function had it wrong. The order is:
- Program the PLIC: priority, enable, threshold.
- Set IER bit 0, so the UART starts asserting its line when data is waiting.
- Clear
sstatus.SIE. - Drain the UART in thread context, by calling
handle_uart. - Set
sie.SEIE. - Set
sstatus.SIE.
After step 2 the line is high for as long as a byte is waiting, and the lab starts with bytes waiting, so from that moment the PLIC context has SEIP raised toward the hart. Gates 2 and 3 (SEIE and SIE) are what hold the interrupt off, which is why the unmask is last. If the unmask came first, the interrupt would be taken the instant gate 3 opened, by the evaluation rule above, and every byte would be read inside the trap handler. That works. It does not work when the same drain also runs in thread context, which is what the first version did, because the two then run the same code on the same device with no mutual exclusion.
The race is a property of the code. Look at uart_getc from chapter 2, which handle_uart calls in a loop:
if ((uart[LSR] & LSR_DR) == 0)
return -1;
return uart[RBR];
The check and the read are two device accesses, and nothing makes the pair atomic against an interrupt. If an interrupt is taken between them and its handler drains the byte, the interrupted uart_getc resumes and reads RBR for a byte that has been consumed. The thread’s read returns something the handler has already echoed or something out of order, and the output has a repeated or misplaced character. Two labs showed the symptoms, embeer and HELLLLOO, both repeated characters. A second path to the same situation: from chapter 11 a block driver sets sstatus.SIE itself, so a console brought up after it would find SIE already set and the drain would run with the UART’s line live. The comment in the listing says so, and that is why step 3 clears SIE instead of assuming it is clear: the function does not know what the caller left open.
The window depends on when the host delivers a byte relative to the vCPU thread, so the rate is host-timing dependent. QEMU’s receive-buffer read returns the register’s last value whether or not DR is set when the FIFO is off, as here (serial_ioport_read, hw/char/serial.c), which is why the stale read is a repeated character. The script race.sh boots the current order and the first version 40 times each and counts the boots whose echo line is not exactly ember. One run on straylight (QEMU 11.1.1), saved in labs/ch05/ex/race.txt:
current order (drain with SIE clear, then unmask): garbled 0 of 40
first version (unmask, then drain): garbled 3 of 40
The counts are not diffed by make ex, and rerunning race.sh prints a fresh run without touching the saved one (--record replaces it); the claim is that the first version garbles some boots and the current order none of the 40 measured.
With the drain first, there is no interrupt for the drain to race with, since SIE is clear throughout. Step 4 drains whatever the chip holds when it runs, one byte at a time while LSR.DR is set. Steps 5 and 6 then open the gates. A byte that arrives after step 4 raises the line, and the interrupt is taken when step 6 runs or later. A byte that was waiting at step 2, which is the lab’s own premise, or that arrived during step 4, and was drained leaves the PLIC with a request that was notified and whose device has nothing waiting. Step 6 is then followed at once by one interrupt that finds nothing. The claim returns 10, handle_uart finds DR clear and returns, and the handler completes. That is the case the spec describes for a level source that deasserts before service: the handler “will then have to determine that the interrupt device no longer requires service”. handle_uart is written so that finding nothing is a normal outcome.
Why a driver is not a library
A library function is called: the caller runs, the call starts at a point the caller chose, and it ends by returning a value to that caller, with the callee’s work done at the caller’s request. This chapter’s code has a different shape in five ways, each visible in the listings below.
First, a driver is entered by the device on the device’s schedule. Nothing in the kernel calls handle_uart at a time of its own choosing in steady state. A byte arrives, the PLIC raises SEIP, and the hart is in trap_entry between two instructions of whatever it was doing. There is no call site. The entry has to build a call context from nothing (the frame) and the return is an sret to an arbitrary place. A library function can assume the registers the caller left; a driver has to save and restore all of them, which is why the frame exists.
Second, a driver owns state that two paths share, and nothing in its interface says so. handle_uart updates nread and guard, the counters behind the lab’s terminator, and drives the UART through one pair of device registers. uart_irq_on calls it from thread context and trapper calls it from the trap path, so the function runs in two contexts with different interrupt state and no lock. The race above is that sharing coming due. A library’s data is its callers’ arguments; a driver’s data is the device and the globals the interrupt path also touches.
Third, its initialization is a protocol among several agents, not a function’s own business. uart_irq_on touches the PLIC, the UART, sie and sstatus. Each of those has a gate, the gates have an order that matters, and the correct order depends on state the function did not set up (whether SIE is already set). A library’s init can be made independent of the caller’s state. This one needed a line that clears sstatus.SIE because the caller’s state could not be assumed.
Fourth, it has no return value. The result of an interrupt handler is a change in state: a byte echoed, a counter advanced, a source completed. The kernel never reads an answer. It acts through shared state, and chapter 10 adds a line buffer and chapter 11 a block completion, and both are state changes.
Fifth, the driver is a trap handler too. When handle_uart runs under trapper it runs with SIE clear, on the stack the interrupted code was using, so it cannot block, cannot take a long time, and must not fault. A library function has no such restrictions.
A hypervisor’s device model has the same shape on the far side of the guest: it is entered on the guest’s schedule, by a write to a doorbell that the hypervisor traps, it owns state the guest also reaches, and it is brought up by a protocol with the guest’s driver. This chapter is the small version of that shape.
Walkthrough
The listings show the code as the chapter 5 image compiles it. The files also carry branches for later chapters (the system call, the block device, the hypervisor), which are not shown here.
The boot path
trap_init_m runs in M-mode: chapter 3’s ch3_drop calls it just before drop_to_s.
static void ch3_drop(unsigned long hartid)
{
unsigned long s = csr_read(mstatus);
unsigned long mpp = (s & MSTATUS_MPP) >> MSTATUS_MPP_SHIFT;
uart_puts("M: hart ");
uart_puthex(hartid);
uart_puts("\r\n");
uart_puts("M: mstatus MPP=");
uart_putc(mpp == 3 ? 'M' : mpp == 1 ? 'S' : 'U');
uart_puts("\r\n");
trap_init_m();
drop_to_s(s_entry);
}
The chapter 5 change here is the trap_init_m() call before drop_to_s. The set bits are the ones in the table above.
void trap_init_m(void)
{
unsigned long medeleg = (1UL << 2) | (1UL << 3) | (1UL << 8) |
(1UL << 12) | (1UL << 13) | (1UL << 15);
csr_write(medeleg, medeleg);
csr_write(mideleg, (1UL << 1) | (1UL << 9));
}
void trap_init(void)
{
csr_write(stvec, (unsigned long)trap_entry);
}
These two writes are the only code in this chapter that touches the delegation registers. 1UL << n builds each bit from its cause number, so the numbers in the table above are the numbers in the source. trap_init is the S-mode half: it writes stvec with the address of trap_entry, whose low two bits are zero by .align 2, so the written MODE is 0, Direct.
S-mode runs this next, after ch3_drop’s drop:
mem_init();
trap_init();
/* The probe. Its address is what the delegated trap must report. */
__asm__ volatile(".globl ember_probe\n"
"ember_probe:\n"
" csrr t0, mhartid");
uart_irq_on();
for (;;)
__asm__ volatile("wfi");
mem_init turns translation on (chapter 4); trap_init then installs the handler, so it exists before anything can trap. The __asm__ block defines a global label, ember_probe, and places a csrr t0, mhartid at it. mhartid is an M-only CSR (chapter 3), so S executing it takes an illegal-instruction exception, delegated now, which lands in trap_entry; the label marks the instruction whose address sepc must equal. uart_irq_on brings the UART path up, and the loop parks the hart in wfi. The specification lets a hart resume from wfi for any reason, so the loop executes it again and again. Chapter 6 gives the instruction’s contract.
The frame in assembly
The struct is what C sees:
struct trapframe {
unsigned long ra, sp, gp, tp;
unsigned long t0, t1, t2, s0, s1;
unsigned long a0, a1, a2, a3, a4, a5, a6, a7;
unsigned long s2, s3, s4, s5, s6, s7, s8, s9, s10, s11;
unsigned long t3, t4, t5, t6;
unsigned long sepc, scause, stval, sstatus;
};
sp is the second field, which puts it at offset 8; the CSRs are last.
The entry then saves the frame:
/*
* S-mode trap entry. Direct stvec. Saves the integer file and the
* four CSRs the handler reads, calls trapper, restores, sret.
*
* Layout matches struct trapframe: 31 saved GPRs (sp at 8 is the
* pre-trap stack), then sepc, scause, stval, sstatus. 280 bytes.
* sret consumes the CSRs, not these slots; the slots exist so later
* chapters can read tf->sstatus.
*/
.section .text
.align 2
.globl trap_entry
trap_entry:
addi sp, sp, -280
sd ra, 0(sp)
sd gp, 16(sp)
sd tp, 24(sp)
sd t0, 32(sp)
sd t1, 40(sp)
sd t2, 48(sp)
sd s0, 56(sp)
sd s1, 64(sp)
sd a0, 72(sp)
sd a1, 80(sp)
sd a2, 88(sp)
sd a3, 96(sp)
sd a4, 104(sp)
sd a5, 112(sp)
sd a6, 120(sp)
sd a7, 128(sp)
sd s2, 136(sp)
sd s3, 144(sp)
sd s4, 152(sp)
sd s5, 160(sp)
sd s6, 168(sp)
sd s7, 176(sp)
sd s8, 184(sp)
sd s9, 192(sp)
sd s10, 200(sp)
sd s11, 208(sp)
sd t3, 216(sp)
sd t4, 224(sp)
sd t5, 232(sp)
sd t6, 240(sp)
addi t0, sp, 280
sd t0, 8(sp)
csrr t0, sepc
sd t0, 248(sp)
csrr t0, scause
sd t0, 256(sp)
csrr t0, stval
sd t0, 264(sp)
csrr t0, sstatus
sd t0, 272(sp)
mv a0, sp
call trapper
The header comment is the contract: 31 saved registers, sp at offset 8 holding the pre-trap value, the four CSRs after them, 280 bytes, and sret consuming CSRs rather than slots. .align 2 is the 4-byte alignment stvec needs. addi sp, sp, -280 allocates the whole frame at once, so every sd that follows is at a positive offset inside it. The 30 stores from ra to t6 skip the sp slot, because sp has changed and a store of it would save the wrong number. The register order is the numeric order of x1 to x31, which is why s0 and s1, registers x8 and x9, sit after t0 to t2 (x5 to x7) and before a0 (x10).
Once t0 is saved it is free to use. addi t0, sp, 280 computes the interrupted stack pointer, and sd t0, 8(sp) fills the sp slot. The four csrr and sd pairs read each CSR through t0 and store it. The order matters here: t0 is already in its slot when the CSR reads borrow it. mv a0, sp puts the frame’s address in the first argument register, and call trapper runs the C handler with that pointer, the tf it takes.
The restore side mirrors the saves:
ld ra, 0(sp)
ld gp, 16(sp)
ld tp, 24(sp)
ld t0, 32(sp)
ld t1, 40(sp)
ld t2, 48(sp)
ld s0, 56(sp)
ld s1, 64(sp)
ld a0, 72(sp)
ld a1, 80(sp)
ld a2, 88(sp)
ld a3, 96(sp)
ld a4, 104(sp)
ld a5, 112(sp)
ld a6, 120(sp)
ld a7, 128(sp)
ld s2, 136(sp)
ld s3, 144(sp)
ld s4, 152(sp)
ld s5, 160(sp)
ld s6, 168(sp)
ld s7, 176(sp)
ld s8, 184(sp)
ld s9, 192(sp)
ld s10, 200(sp)
ld s11, 208(sp)
ld t3, 216(sp)
ld t4, 224(sp)
ld t5, 232(sp)
ld t6, 240(sp)
addi sp, sp, 280
sret
There is no ld for sp and none for the CSR slots. addi sp, sp, 280 rebuilds the interrupted sp from the frame’s address, which is why the stored copy at offset 8 is for the handler’s reading and not for the exit. The 30 ld lines restore exactly the registers the 30 sd lines saved, and a handler that changes a frame slot changes what the interrupted code sees when it resumes. Chapter 7’s system call returns its result through tf->a0 this way, in its own copy of this layout.
The handler
The constants and skip_illegal come first:
#define SCAUSE_ILLEGAL 2UL
#define SCAUSE_SSI (MCAUSE_INT | 1UL)
#define SCAUSE_SEI (MCAUSE_INT | 9UL)
#define SCAUSE_ECALL_U 8UL
#define SIE_SEIE (1UL << 9)
static unsigned char nread;
static unsigned char guard;
static unsigned char saw_illegal;
static unsigned char ticks;
static void skip_illegal(struct trapframe *tf)
{
(void)tf;
csr_write(sepc, csr_read(sepc) + 4);
}
SCAUSE_SSI and SCAUSE_SEI build the interrupt causes by or-ing bit 63 (MCAUSE_INT) onto the code, so they compare directly to what scause returns. SCAUSE_ECALL_U is defined now for chapter 7, where it is first used. nread counts bytes echoed; guard bounds the drain loop, so a stuck device ends in halt(1) and not in an endless loop; saw_illegal makes the probe print once; ticks belongs to chapter 6.
skip_illegal is the handler half of exercise (d). It reads sepc from the CSR, adds 4 and writes the CSR. The (void)tf is deliberate, since the frame is not used. Four is the length of the probe’s instruction and of every instruction in this image, which builds with -march=rv64ima_zicsr and so has no 2-byte compressed instructions. A handler that had to step over an arbitrary instruction would read the instruction’s length from its low bits.
The handler is next, with the macro that prints the capture’s trap line:
/* The delegated trap is pinned by behavior: sepc must be the probe
* instruction (main.c's ember_probe), not a link-time address. The
* probe exists only in the chapter 5 and 6 images. */
extern char ember_probe[];
#define SEPC_IS_PROBE(pc) ((pc) == (unsigned long)ember_probe)
void trapper(struct trapframe *tf)
{
unsigned long cause = csr_read(scause);
if (cause == SCAUSE_ILLEGAL) {
if (!saw_illegal) {
saw_illegal = 1;
unsigned long pc = csr_read(sepc);
uart_puts("S: trap sepc=");
if (SEPC_IS_PROBE(pc))
uart_puts("probe");
else
uart_puthex(pc);
uart_puts(" scause=");
uart_puthex(cause);
uart_puts(" stval=");
uart_puthex(csr_read(stval));
uart_puts("\r\n");
}
skip_illegal(tf);
return;
}
if (cause == SCAUSE_SSI) {
csr_clear(sip, 1UL << 1);
ticks++;
uart_puts("S: tick ");
uart_puthex(ticks);
uart_puts("\r\n");
if (ticks >= 3) {
}
return;
}
if (cause == SCAUSE_SEI) {
unsigned src = plic_claim_s();
if (src == 10)
handle_uart();
if (src)
plic_complete_s(src);
return;
}
uart_puts("S: unexpected scause=");
uart_puthex(cause);
uart_puts("\r\n");
halt(1);
}
The first branch is the probe. csr_read(scause) is compared with 2. The line S: trap sepc=probe scause=0x2 stval=0xf14022f3 is printed once. stval is the instruction word of csrr t0, mhartid, 0xf14022f3, the same encoding as chapter 3’s line, now read from stval and not mtval, because the trap went to S. Then skip_illegal moves sepc past the instruction and the handler returns, so sret resumes after the probe.
The line pins sepc by behaviour, not by number. SEPC_IS_PROBE compares sepc with the address of ember_probe, and the handler prints the word probe when they match and the hex value when not, which fails the capture’s diff. The reason is the course’s testing rule: a capture pins behaviour, not layout, and link-time addresses appear in a transcript only where the chapter is about them (chapter 2). A raw sepc would be a link-time address, and the address moves with the compiler: GCC 16.2 sets up a frame pointer in s_entry’s prologue, which shifts the probe by eight bytes, so a correct kernel would fail a diff that pinned the number. The macro compares only in the chapter 5 and 6 images (HP_CH <= 6), the only ones that contain a probe; later images compile it to 0.
The second branch is SCAUSE_SSI, which is chapter 6’s: no software interrupt is raised in this chapter, and the empty if is the place where chapter 6’s terminator sits. The third is the UART. plic_claim_s returns the source; 10 is the UART; handle_uart drains it; and plic_complete_s(src) completes, guarded by if (src). The last lines are the exit for any cause the handler does not know: print it and halt. That line is what exercise (c)’s capture ends with.
The UART path
void uart_enable_rx(void)
{
volatile unsigned char *uart = (volatile unsigned char *)UART;
/* Do not poke FCR: QEMU already stuffed input.txt, and a FIFO
* enable/reset drops the first byte. IER only. */
uart[IER] = 0x01;
}
uart_enable_rx writes IER bit 0 and nothing else. The comment says why FCR is left alone.
static volatile unsigned int *plic_priority(unsigned src)
{
return (volatile unsigned int *)(PLIC + 4u * src);
}
static volatile unsigned int *plic_enable(unsigned ctx)
{
return (volatile unsigned int *)(PLIC + 0x2000u + 0x80u * ctx);
}
static volatile unsigned int *plic_threshold(unsigned ctx)
{
return (volatile unsigned int *)(PLIC + 0x200000u + 0x1000u * ctx);
}
static volatile unsigned int *plic_claim(unsigned ctx)
{
return plic_threshold(ctx) + 1;
}
void plic_init_uart(void)
{
*plic_priority(UART_SRC) = 1;
*plic_enable(S_CTX) |= (1u << UART_SRC);
*plic_threshold(S_CTX) = 0;
}
unsigned plic_claim_s(void)
{
return *plic_claim(S_CTX);
}
void plic_complete_s(unsigned src)
{
*plic_claim(S_CTX) = src;
}
The four accessors turn the specification’s formulas into pointers: PLIC + 4u * src is the priority register, PLIC + 0x2000u + 0x80u * ctx the enable block, PLIC + 0x200000u + 0x1000u * ctx the threshold. plic_claim is “threshold plus one”, and since the pointer is to a 32-bit word the + 1 is + 4 bytes, the claim register. plic_init_uart sets the priority, the enable bit (|= because the word has other sources’ bits, which later chapters add) and the threshold, for S_CTX, 1. plic_claim_s is the claim, a load, and plic_complete_s is the complete, a store to the same address. The pointers are volatile for the reason chapter 2 gave: each access is a device operation.
static void handle_uart(void)
{
int c;
while ((c = uart_getc()) >= 0) {
if (guard >= 128)
halt(1);
guard++;
uart_putc((char)c);
nread++;
if (c == '\n' || c == '\r') {
uart_puts("chars=");
uart_puthex(nread);
uart_puts("\r\nPASS\r\n");
halt(0);
}
}
}
handle_uart is the loop the interrupt and the boot drain share. It reads while DR says there is data, stops the run at 128 bytes (chapter 10 replaces that guard with a line buffer), echoes each byte, counts it, and on a newline prints the terminator the capture pins and halts. The loop has no state of its own beyond the globals.
void uart_irq_on(void)
{
plic_init_uart();
uart_enable_rx();
/* Drain what QEMU already stuffed with interrupts masked — and
* mask them here rather than assume they are: a driver brought up
* before the console may already have set sstatus.SIE and
* sie.SEIE, and the PLIC line just enabled above would then nest
* this handler inside its own loop, between an LSR read and the
* RBR read it belongs to. Bytes echo twice and land out of order.
* Anything that arrives after the drain comes through the
* interrupt. */
csr_clear(sstatus, MSTATUS_SIE);
handle_uart();
csr_set(sie, SIE_SEIE);
csr_set(sstatus, MSTATUS_SIE);
}
The six steps of the last Mechanism section are the six statements in order: plic_init_uart, uart_enable_rx, the SIE clear, the drain, SEIE, SIE. The comment records the reason for the clear.
The capture
S: trap sepc=probe scause=0x2 stval=0xf14022f3
ember
chars=0x6
PASS
This is the tail of the capture, the lines after the boot report; its first line shown is the delegated trap, explained under the handler above. ember is the six bytes of input.txt echoed, chars=0x6 is the count including the newline, and PASS is the terminator. How the six bytes split between the boot drain and interrupts depends on the host’s timing and the capture does not pin it. It pins the characters and the count.
Exercises
(a) Clear medeleg bit 2 and run. Where does the probe go, and what does the transcript show?
Answer
From labs/ch05/ex/medeleg-bit2.txt:
S: second map
M: trap cause 0x2 (illegal instruction) mtval=0xf14022f3 — S-mode proven
The probe goes to the M shim, chapter 3’s line with mtval and not stval. The delegation rule is a mask: a trap goes to S only if the bit is set, so the same instruction that S handled in the capture is M’s trap now. Nothing after it prints, because the shim halts on a cause it does not expect in this chapter, and no S: trap line or ember appears.
(b) Add a write to FCR (0x07) after the IER write in uart_enable_rx, which the code’s comment advises against. What happens to the input?
Answer
From labs/ch05/ex/fcr-write.txt:
S: trap sepc=probe scause=0x2 stval=0xf14022f3
mber
chars=0x5
PASS
The first byte, e, is gone and the count is 5. It was the byte already waiting when the write arrived, and the write flushed it with the FIFO, as the section on the 16550’s receive side explains. 0x07 is the FIFO enable bit with both reset bits, so the write is a mode change and a flush at once.
(c) Map only the PLIC’s base page: change the call in mem_init to map_mmio_range(0x0c000000UL, 0x1000UL) and print stval in the unexpected-cause line. Which access faults, and with what cause?
Answer
From labs/ch05/ex/plic-base-page.txt:
S: trap sepc=probe scause=0x2 stval=0xf14022f3
S: unexpected scause=0xd stval=0xc002080
Cause 13, a load page fault, with stval the enable word, 0x0c002080. The first access that leaves the base page is in plic_init_uart: the priority write at 0x0c000028 is on the mapped page, and the enable update *plic_enable(S_CTX) |= bit starts with a load of the word. So the fault is a load, 13, and not a store, 15, and it comes before any claim: the claim at 0x0c201004 would fault the same way, as a load, but the code never reaches it. The page fault was delegated (bit 13), so it reached trapper in S, whose last branch printed it and halted.
(d) skip_illegal writes the CSR sepc. Change it to advance only the frame’s slot, tf->sepc += 4, and run. What happens, and what does that say about what sret reads?
Answer
From labs/ch05/ex/frame-sepc.txt, where the patched handler also prints, on each call, whether the CSR still holds the probe’s address and halts after three:
S: trap sepc=probe scause=0x2 stval=0xf14022f3
S: trap 0x1: CSR sepc is still the probe
S: trap 0x2: CSR sepc is still the probe
S: trap 0x3: CSR sepc is still the probe
The probe traps again and again. Each pass writes the frame slot and returns, and sret loads pc from the CSR, which was never changed, so the hart resumes at the probe. The frame’s sepc slot is a copy the entry made, and the exit does not load it back.
(e) Change the frame to 288 bytes so that trapper runs on an aligned stack: only the three constants in trap.S change. Which offsets move, what does the board report, and what does the change cost?
Answer
No offset moves. The frame is still 35 slots at 0 to 272, and the new 8 bytes are padding at 280 to 287, above the last slot. The three changes are addi sp, sp, -288 at the entry, addi t0, sp, 288 where the interrupted sp is computed, and addi sp, sp, 288 at the exit. From labs/ch05/ex/frame-288.txt:
S: trap sepc=probe scause=0x2 stval=0xf14022f3
S: frame address mod 16 = 0x0, saved sp mod 16 = 0x0
The frame address is 16-byte aligned now, and ember still passes. Nothing reads sizeof(struct trapframe), so the struct needs no change. The cost is the freeze: trap.S is frozen at the commit that every later capture was taken against, and the change alters every image from this chapter on. Chapter 7’s proc.S carries its own literal 280s for its entry and exit, so its frame would need the same edit separately, and until then it would stay unaligned (kstack_top is page-aligned, so a frame at kstack_top - 280 is 8 mod 16).
(f) Set the S context’s PLIC threshold to 1 while source 10’s priority stays 1, with a byte waiting. What does the specification say reaches the hart and what a claim returns, and what does the board do?
Answer
The specification: “The PLIC will mask all PLIC interrupts of a priority less than or equal to threshold.” Source 10’s priority 1 is not above 1, so the source is masked, the notification is never raised, and sip.SEIP stays 0; priority 2 would pass, and 0 never does (“never interrupt”). On claims it says “the claim operation is not affected by the setting of the priority threshold register”, so a handler could poll by claim. The board differs. From labs/ch05/ex/threshold-claim.txt:
S: threshold 1: lsr=0x61 sip=0x0 claim=0x0
S: threshold 0: sip=0x200 claim=0xa
With the byte waiting (DR set) and the threshold at 1, sip is 0 and the claim returns 0. After the threshold is lowered to 0 the same source raises SEIP and the claim returns 10. On QEMU 11.1.1 a claim only finds sources whose priority exceeds the context’s threshold, so polling by claim under a raised threshold does not work here (sifive_plic.c).
Lab
make lab CH=05
make lab CH=05 IMPL=mine
make ex CH=05
The capture pins the trap line, the echoed ember, chars=0x6 and PASS. IMPL=mine stubs uart_irq_on with a halt(1), so the diff fails on the three lines the UART path prints, until the reader writes it. make ex CH=05 reruns every side run in a scratch copy of ember/ and diffs each transcript against the committed one in labs/ch05/ex/; it is not part of make check. The committed transcripts are from QEMU 11.1.1. plic-dtb.sh (the board’s device tree) and race.sh (the race, measured) are scripts, so make ex does not rerun them.
Further reading
- The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Supervisor-Level ISA (RISC-V International, v20260120, January 2026).
sstatusand the SPP field with the two interrupt-enable bits (11.1.1.1),stvecand its modes (11.1.1.2),sipandsieand the interrupt conditions and priority (11.1.1.3),sepc,scauseandstval(11.1.1.7 to 11.1.1.9). - The RISC-V Instruction Set Manual, Volume II: Privileged Architecture, Machine-Level ISA (same edition). The privilege stack for traps and returns (2.1.1.6.1), delegation and what a delegated trap writes (2.1.1.8),
mipandmieincluding SEIP (2.1.1.9),ecall(2.1.3.1), trap return (2.1.3.2),wfi(2.1.3.3). - “H” Extension for Hypervisor Support, Version 1.0 (same edition). Trap entry (14.1.6.2) and trap return (14.1.6.4), the additions to the lists above; chapter 18 builds on them.
- RISC-V Platform-Level Interrupt Controller Specification, 1.0.0 (RISC-V International, March 2023, the ratified release). The gateway rule, the claim and complete protocol, and the memory map.
- PC16550D Universal Asynchronous Receiver/Transmitter with FIFOs (Texas Instruments, SNLS378C, revised May 2015, from a distributor’s mirror of the datasheet). The line status, FIFO control, interrupt identification and interrupt enable registers (8.6.3 to 8.6.6).
- Devicetree binding for the SiFive PLIC 1.0.0 (Linux 6.12).
interrupts-extendedas the list of contexts. - QEMU v11.1.1, the board facts this chapter relies on:
hw/riscv/virt.c(the memory map),include/hw/riscv/virt.h(UART0_IRQand the PLIC offsets),hw/riscv/boot.c(the per-hart “MS” configuration),hw/intc/sifive_plic.c(claim and complete) andhw/char/serial.c(the 16550 model). These describe the board, not the architecture. - RISC-V ELF psABI, Calling Conventions (RISC-V International, v1.0). The stack alignment rule and its interrupt-service-routine clause.