RISC-V Control and Status Registers Every Kernel Author Uses
A tour of the RISC-V supervisor CSRs a kernel touches: sstatus, sie, stvec, scause, sepc, stval, satp and sscratch, with instructions and exact bits.

On most architectures, the state that controls the machine is scattered: special registers with their own instructions, bits in flag words, model-specific registers behind an index. RISC-V gathers all of it in one place. A control and status register, or CSR, is a register in a separate 4,096-entry address space, read and written with a small family of instructions, and the whole privileged architecture is described as a list of them. A kernel author needs about ten. This post goes through the supervisor-mode ones, shows the instructions that touch them and the exact bits that matter, and ends with a program that dumps them at boot.
Every bit position comes from the RISC-V Instruction Set Manual, Volume II: Privileged Architecture. The code is C with GCC inline assembly for a 64-bit kernel built with -march=rv64imac_zicsr_zifencei.
How CSR instructions work
A CSR is not memory. You cannot take its address, and a load or store cannot reach it. Six instructions read and write CSRs, and they come in two sets: register operands and 5-bit immediate operands. Every one of them reads the old value and writes a new one in a single atomic step, which matters for a register like sstatus that an interrupt could change between a separate read and write.
| Instruction | Effect | Use |
|---|---|---|
csrrw rd, csr, rs | rd gets the old value, the CSR gets rs | Swap, or plain write when rd is x0 |
csrrs rd, csr, rs | rd gets the old value, bits set in rs become 1 in the CSR | Set bits |
csrrc rd, csr, rs | rd gets the old value, bits set in rs become 0 in the CSR | Clear bits |
csrrwi, csrrsi, csrrci | The same with a 5-bit immediate | Small constants |
The assembler offers pseudo-instructions for the common forms: csrr rd, csr reads (csrrs rd, csr, x0), csrw csr, rs writes (csrrw x0, csr, rs), csrs csr, rs sets bits and csrc csr, rs clears them. These are what you write in assembly and what the macros below emit.
#define csr_read(csr) \
({ unsigned long __v; \
__asm__ volatile("csrr %0, " #csr : "=r"(__v)); __v; })
#define csr_write(csr, val) \
({ unsigned long __v = (unsigned long)(val); \
__asm__ volatile("csrw " #csr ", %0" : : "r"(__v) : "memory"); })
#define csr_set(csr, val) \
({ unsigned long __v = (unsigned long)(val); \
__asm__ volatile("csrs " #csr ", %0" : : "r"(__v) : "memory"); })
#define csr_clear(csr, val) \
({ unsigned long __v = (unsigned long)(val); \
__asm__ volatile("csrc " #csr ", %0" : : "r"(__v) : "memory"); })
// Read the old value and clear bits in one atomic step.
#define csr_read_clear(csr, val) \
({ unsigned long __v = (unsigned long)(val), __o; \
__asm__ volatile("csrrc %0, " #csr ", %1" : "=r"(__o) : "r"(__v) : "memory"); __o; })The macros stringify the CSR name with #csr, so the assembler sees csrr a0, sstatus and resolves the number. The "memory" clobber on the writing forms stops the compiler from moving memory accesses across a CSR write, which is necessary for registers like satp that change what memory means.
Access is controlled by the privilege level. Bits 9:8 of the CSR number give the lowest mode that may access it, so s-prefixed registers need S mode or above, and touching one from user mode raises an illegal instruction exception. Bits 11:10 equal to 11 mean read-only: a write to such a register also traps.
sstatus: the global state
sstatus holds the switches that apply to everything the supervisor does. Four bits matter to a kernel.
SIE, bit 1, is the global interrupt enable for supervisor mode. Clear, no supervisor interrupt is taken, whatever sie says. When a trap is taken, hardware saves SIE into SPIE and clears it, so a handler starts with interrupts off.
SPIE, bit 5, is that saved value. sret copies SPIE back into SIE, which is how a return from a trap re-enables interrupts, and why you set it by hand before starting user mode.
SPP, bit 8, is the privilege the trap came from: 0 for user, 1 for supervisor. sret returns to that mode, so to start user code you clear it and execute sret.
SUM, bit 18, controls whether supervisor code may access pages marked user-accessible. It is clear by default, so a stray kernel pointer into user memory faults, and a kernel that wants to copy data from a user buffer sets it for the duration of the copy.
#define SSTATUS_SIE (1UL << 1)
#define SSTATUS_SPIE (1UL << 5)
#define SSTATUS_SPP (1UL << 8)
#define SSTATUS_SUM (1UL << 18)
static inline unsigned long intr_off(void)
{
return csr_read_clear(sstatus, SSTATUS_SIE) & SSTATUS_SIE;
}
static inline void intr_on(void)
{
csr_set(sstatus, SSTATUS_SIE);
}sie and sip: which interrupts are allowed and pending
Supervisor interrupts have three sources, each with an enable bit in sie and a pending bit in sip, at the same positions. Bit 1 is the supervisor software interrupt, SSIE and SSIP, used for inter-hart signalling. Bit 5 is the supervisor timer, STIE and STIP. Bit 9 is the supervisor external interrupt, SEIE and SEIP, which is how the PLIC delivers device interrupts.
A source interrupts the CPU only when three things are true: the source's pending bit is set, its enable bit in sie is set, and sstatus.SIE is set. A kernel that sets up a timer and sees no interrupts is usually missing one of the three.
#define SIE_SSIE (1UL << 1)
#define SIE_STIE (1UL << 5)
#define SIE_SEIE (1UL << 9)
static inline void enable_interrupt_sources(void)
{
csr_set(sie, SIE_SSIE | SIE_STIE | SIE_SEIE);
}stvec: where traps go
stvec holds the address of the trap handler in its upper bits and a mode in the low two bits. Mode 0, direct, sends every trap to the base address, and the handler decodes scause itself. Mode 1, vectored, sends exceptions to the base and interrupts to base plus four times the interrupt's cause number, so each interrupt gets its own small stub.
void trap_init_direct(void)
{
extern void trap_entry(void);
csr_write(stvec, (unsigned long)trap_entry); // low bits 00: direct mode
}
void trap_init_vectored(void)
{
extern void vector_table(void);
csr_write(stvec, (unsigned long)vector_table | 1); // low bits 01: vectored
}In vectored mode the base address must be aligned so that adding 4 * cause for a cause up to the highest supported never corrupts the mode bits, and the table is a sequence of 4-byte jump instructions. Direct mode is simpler and is what most small kernels use. Linux uses it too.
scause, sepc and stval: what happened
When a trap is taken, three registers describe it. scause holds the reason, with the top bit set for an interrupt and clear for an exception, and the remaining bits a code. sepc holds the address of the instruction that was executing, or for an interrupt, the one that would have run next. stval holds trap-specific data: the faulting address for a page fault or misaligned access, the instruction bits for an illegal instruction.
The causes a kernel meets first:
| Interrupt bit | Code | Meaning |
|---|---|---|
| 1 | 1 | Supervisor software interrupt |
| 1 | 5 | Supervisor timer interrupt |
| 1 | 9 | Supervisor external interrupt |
| 0 | 2 | Illegal instruction |
| 0 | 3 | Breakpoint (ebreak) |
| 0 | 8 | ecall from user mode |
| 0 | 12 | Instruction page fault |
| 0 | 13 | Load page fault |
| 0 | 15 | Store or AMO page fault |
sepc is writable, and that is how a handler resumes after an exception. For a system call, add 4 to sepc so sret lands after the ecall. For a page fault that the handler fixes, leave it unchanged so the faulting instruction runs again.
satp: the address translation switch
satp selects the translation mode and the root page table. On RV64 its top four bits are the mode, with 0 meaning no translation and 8 meaning Sv39. Bits 59:44 hold an address space identifier, ASID, and bits 43:0 hold the physical page number of the root table.
#define SATP_SV39 (8UL << 60)
void enable_paging(unsigned long root_phys)
{
csr_write(satp, SATP_SV39 | (root_phys >> 12));
__asm__ volatile("sfence.vma zero, zero" ::: "memory");
}Writing satp takes effect at once, and cached translations are not flushed by the write. The sfence.vma that follows is part of the sequence. A write that sets a mode the hardware does not support is silently ignored, which gives a probe: write Sv39, read it back, and if the mode field reads zero, the CPU has no paging.
sscratch: one register for the handler
A trap handler's first problem is that every general register holds live data from the interrupted code, and it needs somewhere to start saving. sscratch exists for that. Kernel code keeps it at zero or at a known value, and the handler's first instruction swaps it with a general register.
trap_entry:
csrrw sp, sscratch, sp # sp = what sscratch held, sscratch = interrupted sp
bnez sp, 1f # non-zero: it was the kernel stack for a user trap
csrr sp, sscratch # zero: the trap came from the kernel, undo the swap
1: # ... save registers on the kernel stackThis is the standard convention: while user code runs, sscratch holds the kernel stack pointer, and while the kernel runs, it holds zero. The same single instruction then serves both entry paths.
time, cycle and instret: counters
Three read-only counters are accessible with the rdtime, rdcycle and rdinstret pseudo-instructions. time is a wall-clock counter at a platform-defined frequency, 10 MHz on QEMU's virt, and is what timer interrupts are programmed against. cycle counts CPU cycles and instret counts retired instructions. Whether supervisor and user code may read them is gated by scounteren and the machine-mode mcounteren, so a read can trap if firmware has not enabled them.
static inline unsigned long rdtime(void)
{
unsigned long t;
__asm__ volatile("rdtime %0" : "=r"(t));
return t;
}Dumping the state at boot
A tiny diagnostic that prints the registers is worth having in every kernel. It shows what firmware left you and catches a wrong assumption fast.
void csr_dump(void)
{
kprintf("sstatus = %lx\n", csr_read(sstatus));
kprintf("sie = %lx\n", csr_read(sie));
kprintf("stvec = %lx\n", csr_read(stvec));
kprintf("satp = %lx\n", csr_read(satp));
kprintf("time = %lu\n", rdtime());
}On OpenSBI entering a fresh kernel, supervisor interrupts are off and no translation is active. The numbers vary with your build and with how long the machine has been running:
sstatus = 8000000200006000
sie = 0
stvec = 0
satp = 0
time = 4190872The sstatus value is worth reading. The top bit is SD, the summary dirty flag, set because the floating-point and vector state fields in bits 14:13 and 10:9 are non-zero on this configuration. The 0x2 in the upper word is UXL equal to 2, meaning user mode is 64-bit. You can see that SIE and SPIE are both clear, so the kernel starts with interrupts disabled, which is exactly what it should assume.
What a kernel can skip
The privileged architecture has far more CSRs than this: performance counters, the hypervisor registers, the entropy source, senvcfg for environment features, and the debug and trace extensions. A small kernel meets none of them. Learn the ten here first, and treat the rest as reading to do when a feature calls for it, such as stimecmp when you adopt the Sstc extension, which lets supervisor mode program its own timer without SBI.


