The Complete Guide to Writing a RISC-V Kernel
Write a 64-bit RISC-V kernel in C and assembly for QEMU virt: boot through OpenSBI, traps, timer, paging with Sv39, a page allocator, tasks and user mode.

RISC-V is the friendliest architecture to write a kernel for, and the reason is not marketing. The privileged specification is short enough to read in a weekend, the instruction set has no historical layers, the control registers are few and orthogonal, and the QEMU virt machine gives you a clean, documented board with a UART, an interrupt controller, a timer and a set of virtual devices. A kernel that boots, handles interrupts, manages memory, switches tasks and runs a user program fits in about two thousand lines. This guide builds one, step by step, for 64-bit RISC-V in supervisor mode on QEMU, and points at the deeper posts for each subsystem.
The target is RV64GC under QEMU 9.2 using the virt machine, with OpenSBI as the firmware that gets the kernel started. The toolchain is a riscv64-unknown-elf GCC 14 with Binutils, and every register, instruction and bit position comes from the RISC-V Instruction Set Manual, Volume II: Privileged Architecture, and the OpenSBI and SBI specification documents. We write the code, we do not run it here, and the console output shown is what each stage prints on a correct build.
What you will build
By the end of this guide the kernel does these things, in this order of dependency: it starts from firmware and prints text; it takes traps and interrupts and recovers from them; it ticks a timer; it manages physical memory in 4 KiB pages; it turns on Sv39 virtual memory with its own page table; it runs several kernel tasks and switches between them; and it drops to user mode, where a small program asks the kernel for service through ecall.
That is a complete skeleton of an operating system. It has no filesystem, no networking and no drivers beyond the console, and each of those is a separate post in this series. The skeleton is the hard part, and once you have it every addition is local.
The machine and the privilege modes
RISC-V defines three privilege modes you care about. Machine mode (M) is the most privileged and is where firmware lives. Supervisor mode (S) is where an operating system kernel runs. User mode (U) is where applications run. A kernel normally never executes in M mode, and that is how this guide is organized: OpenSBI, a small open source firmware, runs in M mode and does the board-specific work, and your kernel starts in S mode and asks the firmware for services through the Supervisor Binary Interface, SBI, when it needs one.
This split removes a lot of setup. The firmware has already configured the physical memory protection, delegated traps and interrupts to S mode, started a timer abstraction and put the UART into a usable state. Your kernel inherits that.
The QEMU virt machine has a fixed physical memory map. These are the addresses you will use:
| Device | Base address | Used for |
|---|---|---|
| Test finisher | 0x0010_0000 | Power off the machine |
| CLINT | 0x0200_0000 | Timer and software interrupts (M mode, behind SBI) |
| PLIC | 0x0C00_0000 | External interrupt routing |
| UART 16550 | 0x1000_0000 | Serial console |
| virtio MMIO | 0x1000_1000 upward | Block, network and other devices |
| RAM | 0x8000_0000 | Firmware first, then your kernel at 0x8020_0000 |
The kernel loads at 0x80200000 because OpenSBI occupies the first 2 MiB of RAM and then jumps to the next 2 MiB boundary. With QEMU's default -bios setting you pass your kernel with -kernel and OpenSBI starts it for you, with the hart ID in register a0 and a pointer to the device tree in a1.
The toolchain and the first build
Install a bare-metal RISC-V compiler. The target triple is riscv64-unknown-elf, and every compile uses the same flags:
CROSS = riscv64-unknown-elf-
CC = $(CROSS)gcc
CFLAGS = -march=rv64imac_zicsr_zifencei -mabi=lp64 -mcmodel=medany \
-ffreestanding -fno-pic -O2 -Wall -Wextra -mno-relax
LDFLAGS = -T kernel.ld -nostdlib -static
OBJS = entry.o main.o sbi.o trap.o
kernel.elf: $(OBJS)
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS)
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
%.o: %.S
$(CC) $(CFLAGS) -c $< -o $@
run: kernel.elf
qemu-system-riscv64 -machine virt -cpu rv64 -smp 1 -m 128M \
-nographic -bios default -kernel kernel.elfEach flag has a reason. -march=rv64imac_zicsr_zifencei names the base integer instruction set, multiplication, atomics and compressed instructions, plus the two extensions that newer toolchains split out of the base: zicsr for the CSR instructions and zifencei for fence.i. -mabi=lp64 is the integer calling convention with no hardware floating point, which keeps floating point state out of every context switch. -mcmodel=medany lets code and data live at any address within a 2 GiB window, which is required because the kernel sits at 0x80200000, and the default model assumes addresses near zero. -mno-relax turns off linker relaxation, which would otherwise interfere with the global pointer setup we do not use.
Boot: from firmware to C
The linker script places the entry point at the load address and defines symbols the kernel uses to find its own end:
OUTPUT_ARCH(riscv)
ENTRY(_start)
SECTIONS {
. = 0x80200000;
.text : ALIGN(4096) {
*(.text.entry)
*(.text .text.*)
}
.rodata : ALIGN(4096) { *(.rodata .rodata.*) }
.data : ALIGN(4096) { *(.data .data.*) }
.bss : ALIGN(4096) {
__bss_start = .;
*(.bss .bss.*)
*(COMMON)
__bss_end = .;
}
. = ALIGN(4096);
__kernel_end = .;
}The first code is a few lines of assembly. It runs with no stack and with .bss containing whatever memory held before, so it must set a stack pointer, zero the .bss section and then call C:
.section .text.entry
.global _start
_start:
la sp, boot_stack_top # stack for the first hart
mv s0, a0 # keep the hart id
mv s1, a1 # keep the device tree pointer
la t0, __bss_start
la t1, __bss_end
1: bgeu t0, t1, 2f
sd zero, 0(t0)
addi t0, t0, 8
j 1b
2: mv a0, s0
mv a1, s1
call kmain
3: wfi
j 3b
.section .bss
.align 12
boot_stack:
.space 16384
boot_stack_top:The la pseudo-instruction expands to a PC-relative auipc plus addi, which is why medany matters. The final loop is the safe fall-through for kmain returning, since wfi waits for an interrupt without burning power.
Talking to the world: SBI calls
Before any driver exists, the firmware prints for you. An SBI call is an ecall instruction executed in S mode with an extension ID in a7, a function ID in a6 and arguments in a0 to a5. It returns an error code in a0 and a value in a1. The specification defines the Debug Console extension, DBCN, whose extension ID is the ASCII string "DBCN", 0x4442434E. Function 2 writes one byte.
#include <stdint.h>
struct sbiret { long error; long value; };
static inline struct sbiret sbi_call(long eid, long fid, long a0, long a1, long a2)
{
register long r0 __asm__("a0") = a0;
register long r1 __asm__("a1") = a1;
register long r2 __asm__("a2") = a2;
register long r6 __asm__("a6") = fid;
register long r7 __asm__("a7") = eid;
__asm__ volatile("ecall"
: "+r"(r0), "+r"(r1)
: "r"(r2), "r"(r6), "r"(r7)
: "memory");
return (struct sbiret){ r0, r1 };
}
#define SBI_EXT_DBCN 0x4442434E
#define SBI_EXT_TIME 0x54494D45
#define SBI_EXT_SRST 0x53525354
void console_putc(char c)
{
sbi_call(SBI_EXT_DBCN, 2, (unsigned char)c, 0, 0); // DBCN write_byte
}
void console_puts(const char *s)
{
while (*s)
console_putc(*s++);
}
void sbi_shutdown(void)
{
sbi_call(SBI_EXT_SRST, 0, 0, 0, 0); // system_reset: type 0 shutdown, reason 0
}Add a small kprintf that formats %d, %x, %s and %c into console_putc, and the first kernel is five lines long:
void kmain(unsigned long hartid, void *dtb)
{
kprintf("hello from RISC-V, hart %lu, dtb at %p\n", hartid, dtb);
sbi_shutdown();
}Run make run. OpenSBI prints its own banner first, then your line appears and the machine powers off. The pointer value depends on QEMU's layout, so treat it as typical:
OpenSBI v1.5
...
hello from RISC-V, hart 0, dtb at 0x00000000bfe00000That is the first milestone, and everything after it is built on a kernel that can print.
Control and status registers, the short version
RISC-V has no special instructions for the things x86 sprinkles through its architecture. State that controls the machine lives in CSRs, read and written with csrr, csrw, csrs and csrc. S mode has a small set, and these are the ones this guide uses:
| CSR | Purpose |
|---|---|
sstatus | Global state: SIE (bit 1) enables interrupts, SPIE (bit 5) and SPP (bit 8) record the state before a trap |
stvec | Address of the trap handler |
scause | Why the trap happened; the top bit is set for an interrupt |
sepc | The program counter at the trap |
stval | Extra information, such as the faulting address |
sie, sip | Which interrupt sources are enabled and pending |
satp | Page table root and the translation mode |
sscratch | A scratch register for the trap handler |
Wrap access in two helper macros so the rest of the code stays readable:
#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)); })
#define csr_set(csr, val) \
({ unsigned long __v = (unsigned long)(val); \
__asm__ volatile("csrs " #csr ", %0" : : "r"(__v)); })
#define csr_clear(csr, val) \
({ unsigned long __v = (unsigned long)(val); \
__asm__ volatile("csrc " #csr ", %0" : : "r"(__v)); })
#define SSTATUS_SIE (1UL << 1)
#define SSTATUS_SPIE (1UL << 5)
#define SSTATUS_SPP (1UL << 8)
#define SIE_STIE (1UL << 5)
#define SIE_SEIE (1UL << 9)Traps: exceptions and interrupts
A trap is the CPU transferring control to your handler. It happens for an exception, such as an illegal instruction or a page fault, or for an interrupt, such as a timer expiring. When it happens in S mode, the hardware does five things at once: it copies the program counter into sepc, writes the reason into scause, writes extra data into stval, copies the current interrupt enable into SPIE and clears SIE, and records the previous privilege in SPP. Then it jumps to the address in stvec.
The handler's job is to save every register, call C, and restore them. Define the saved state as a structure and mirror it in the assembly:
struct trapframe {
unsigned long regs[32]; // x0 is unused; x1 at regs[1], and so on
unsigned long sepc;
unsigned long sstatus;
unsigned long scause;
unsigned long stval;
}; // 36 words, 288 bytes .macro SAVE_REGS
.irp n, 1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
sd x\n, \n*8(sp)
.endr
.endm
.macro LOAD_REGS
.irp n, 1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
ld x\n, \n*8(sp)
.endr
.endm
.align 4
.global trap_entry
trap_entry:
addi sp, sp, -288
SAVE_REGS
addi t0, sp, 288
sd t0, 16(sp) # the original sp, as a trap frame field
csrr t0, sepc
sd t0, 256(sp)
csrr t0, sstatus
sd t0, 264(sp)
csrr t0, scause
sd t0, 272(sp)
csrr t0, stval
sd t0, 280(sp)
mv a0, sp
call trap_handler
ld t0, 256(sp)
csrw sepc, t0
ld t0, 264(sp)
csrw sstatus, t0
LOAD_REGS
addi sp, sp, 288
sretThe .align 4 is not decoration. stvec holds the handler address in its upper bits and a mode in the low two. Mode 0, direct, sends every trap to one address, and the address must be 4-byte aligned. This guide uses direct mode, with one entry point and a C dispatch on scause.
The LOAD_REGS restore overwrites t0 last, and the original sp comes back from the addi sp, sp, 288, which is why the saved sp slot is written for the benefit of C code but not read back.
On the C side, decode scause. The top bit distinguishes interrupts from exceptions, and the rest is a code:
#define SCAUSE_INTERRUPT (1UL << 63)
void trap_init(void)
{
extern void trap_entry(void);
csr_write(stvec, (unsigned long)trap_entry); // mode 0: direct
}
void trap_handler(struct trapframe *tf)
{
unsigned long cause = tf->scause;
if (cause & SCAUSE_INTERRUPT) {
switch (cause & ~SCAUSE_INTERRUPT) {
case 5: timer_interrupt(); break; // supervisor timer
case 9: external_interrupt(); break; // supervisor external
default: kprintf("unexpected interrupt %lu\n", cause & ~SCAUSE_INTERRUPT); break;
}
return;
}
switch (cause) {
case 2:
kprintf("illegal instruction at %lx\n", tf->sepc);
tf->sepc += 4; // skip it, for the demo
break;
case 3:
kprintf("breakpoint at %lx\n", tf->sepc);
tf->sepc += 2; // ebreak may be compressed
break;
default:
kprintf("fatal trap: scause=%lx sepc=%lx stval=%lx\n", cause, tf->sepc, tf->stval);
sbi_shutdown();
}
}Test the machinery by executing an instruction that traps. Executing ebreak raises cause 3:
trap_init();
kprintf("before\n");
__asm__ volatile("ebreak");
kprintf("after\n");before
breakpoint at 0x0000000080201c4e
afterThe address will differ with your build. The important part is that after prints, because sepc was moved past the instruction, and then sret returned into the code after the ebreak. The += 2 is subtle: with the c extension enabled, the compiler emits the 2-byte c.ebreak, and adding 4 would skip an instruction that was never executed.
A timer tick
Timer interrupts are what make preemption possible. On RISC-V the machine timer belongs to M mode, so the kernel asks the firmware through SBI: call sbi_set_timer(time) with an absolute time value, and the firmware raises a supervisor timer interrupt when the time counter reaches it. Read the current time with the rdtime pseudo-instruction, which reads the time CSR. On virt, the timebase is 10 MHz.
#define TIMEBASE_HZ 10000000UL
#define TICK_HZ 100UL
#define TICK_CYCLES (TIMEBASE_HZ / TICK_HZ)
volatile unsigned long ticks;
static inline unsigned long rdtime(void)
{
unsigned long t;
__asm__ volatile("rdtime %0" : "=r"(t));
return t;
}
static void sbi_set_timer(unsigned long when)
{
sbi_call(SBI_EXT_TIME, 0, (long)when, 0, 0);
}
void timer_init(void)
{
csr_set(sie, SIE_STIE); // allow supervisor timer interrupts
sbi_set_timer(rdtime() + TICK_CYCLES);
csr_set(sstatus, SSTATUS_SIE); // global enable
}
void timer_interrupt(void)
{
ticks++;
sbi_set_timer(rdtime() + TICK_CYCLES); // re-arm: one shot per call
if (ticks % 100 == 0)
kprintf("tick %lu\n", ticks);
}The timer is one-shot. Each interrupt must program the next, which also clears the pending condition. After the call to timer_init, the console prints once a second:
tick 100
tick 200
tick 300Physical memory
Everything from here needs pages of memory. The simplest allocator is a free list threaded through the free pages themselves. The pages are those between the end of the kernel image, the __kernel_end symbol, and the end of RAM, which with -m 128M is 0x80000000 + 128 MiB = 0x88000000.
#define PAGE_SIZE 4096UL
#define RAM_END (0x80000000UL + 128UL * 1024 * 1024)
struct free_page { struct free_page *next; };
static struct free_page *free_list;
static unsigned long free_count;
extern char __kernel_end[];
void pmm_init(void)
{
unsigned long p = ((unsigned long)__kernel_end + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
for (; p + PAGE_SIZE <= RAM_END; p += PAGE_SIZE)
pmm_free((void *)p);
kprintf("pmm: %lu pages free\n", free_count);
}
void pmm_free(void *page)
{
struct free_page *f = page;
f->next = free_list;
free_list = f;
free_count++;
}
void *pmm_alloc(void)
{
struct free_page *f = free_list;
if (!f)
return 0;
free_list = f->next;
free_count--;
memset(f, 0, PAGE_SIZE); // callers expect zeroed pages
return f;
}The expected output for a kernel image that ends near 0x80208000 is below; the exact count depends on the size of your image:
pmm: 32744 pages freeA free list stores its links inside the pages it manages, so it needs no memory of its own, and it hands out and takes back a page in constant time. Its weakness is that it cannot allocate contiguous ranges, which DMA buffers need. A bitmap allocator fixes that, and is the natural next step.
Virtual memory with Sv39
Paging on 64-bit RISC-V comes in several modes. Sv39 uses 39-bit virtual addresses, a three-level page table and 4 KiB pages, covering 512 GiB. A virtual address splits into three 9-bit indexes and a 12-bit offset:
38 30 29 21 20 12 11 0
+------------+------------+------------+------------+
| VPN[2] | VPN[1] | VPN[0] | offset |
+------------+------------+------------+------------+A page table is a 4 KiB page of 512 eight-byte entries. Each entry holds a physical page number in bits 53 to 10 and flag bits in 7 to 0: Valid, Read, Write, eXecute, User, Global, Accessed and Dirty. An entry with V set and all of R, W, X clear points to the next level; an entry with any of them set is a leaf. The satp register selects the mode in bits 63 to 60 (8 for Sv39) and holds the root table's physical page number in its low 44 bits.
The kernel's first page table identity-maps RAM and the devices, so that after paging is on, addresses mean what they meant before. Build it with a map_page function that walks the three levels and allocates tables on demand:
typedef unsigned long pte_t;
#define PTE_V (1UL << 0)
#define PTE_R (1UL << 1)
#define PTE_W (1UL << 2)
#define PTE_X (1UL << 3)
#define PTE_U (1UL << 4)
#define PTE_A (1UL << 6)
#define PTE_D (1UL << 7)
#define PA2PTE(pa) (((unsigned long)(pa) >> 12) << 10)
#define PTE2PA(pte) (((pte) >> 10) << 12)
#define VPN(va, l) (((va) >> (12 + 9 * (l))) & 0x1FF)
pte_t *kernel_pt;
int map_page(pte_t *root, unsigned long va, unsigned long pa, unsigned long flags)
{
pte_t *t = root;
for (int level = 2; level > 0; level--) {
pte_t *e = &t[VPN(va, level)];
if (!(*e & PTE_V)) {
pte_t *next = pmm_alloc();
if (!next)
return -1;
*e = PA2PTE(next) | PTE_V; // pointer to the next level
}
t = (pte_t *)PTE2PA(*e);
}
t[VPN(va, 0)] = PA2PTE(pa) | flags | PTE_V | PTE_A | PTE_D;
return 0;
}
void vm_init(void)
{
kernel_pt = pmm_alloc();
// Devices: UART, PLIC, virtio. Read and write only.
for (unsigned long a = 0x10000000UL; a < 0x10002000UL; a += PAGE_SIZE)
map_page(kernel_pt, a, a, PTE_R | PTE_W);
for (unsigned long a = 0x0C000000UL; a < 0x0C400000UL; a += PAGE_SIZE)
map_page(kernel_pt, a, a, PTE_R | PTE_W);
// Kernel text is read and execute, everything else read and write.
extern char __text_end[];
for (unsigned long a = 0x80200000UL; a < (unsigned long)__text_end; a += PAGE_SIZE)
map_page(kernel_pt, a, a, PTE_R | PTE_X);
for (unsigned long a = (unsigned long)__text_end; a < RAM_END; a += PAGE_SIZE)
map_page(kernel_pt, a, a, PTE_R | PTE_W);
csr_write(satp, (8UL << 60) | ((unsigned long)kernel_pt >> 12));
__asm__ volatile("sfence.vma zero, zero");
kprintf("paging on, satp=%lx\n", csr_read(satp));
}The accessed and dirty bits are set at map time because some implementations raise a page fault when an entry with A clear is used, and handling that in software is extra work for no benefit in a first kernel. The sfence.vma flushes cached translations, and it is mandatory after changing satp or any page table entry that may have been cached. The kernel text section needs a __text_end symbol in the linker script after .text, placed at a page boundary.
The output shows the mode bits in the top nibble:
paging on, satp=8000000000080215A leading 8 is Sv39, and the rest is the physical page number of the root table, which will differ on your build. If the kernel hangs the instant satp is written, an unmapped page is the cause: the instruction after the write, the stack, the UART or a data structure the code touches is missing from the page table.
Tasks and the context switch
A context switch on RISC-V is shorter than on x86, because the calling convention is explicit. A function call preserves s0 to s11 and sp, and clobbers everything else, so a switch routine needs to save and restore exactly those, plus the return address ra.
.global switch_to
# void switch_to(struct context *old, struct context *new)
switch_to:
sd ra, 0(a0)
sd sp, 8(a0)
sd s0, 16(a0)
sd s1, 24(a0)
sd s2, 32(a0)
sd s3, 40(a0)
sd s4, 48(a0)
sd s5, 56(a0)
sd s6, 64(a0)
sd s7, 72(a0)
sd s8, 80(a0)
sd s9, 88(a0)
sd s10, 96(a0)
sd s11, 104(a0)
ld ra, 0(a1)
ld sp, 8(a1)
ld s0, 16(a1)
ld s1, 24(a1)
ld s2, 32(a1)
ld s3, 40(a1)
ld s4, 48(a1)
ld s5, 56(a1)
ld s6, 64(a1)
ld s7, 72(a1)
ld s8, 80(a1)
ld s9, 88(a1)
ld s10, 96(a1)
ld s11, 104(a1)
retThe new task is started by setting its context's ra to its entry function and sp to the top of its own stack, so that the final ret jumps to it, exactly the trick used on x86. A round-robin scheduler on top of the timer tick completes the picture:
struct context { unsigned long ra, sp, s[12]; };
struct task {
struct context ctx;
void *stack;
int id;
int runnable;
};
#define MAX_TASKS 8
static struct task tasks[MAX_TASKS];
static int ntasks, cur;
void task_create(void (*entry)(void))
{
struct task *t = &tasks[ntasks];
t->id = ntasks++;
t->stack = pmm_alloc();
t->ctx.ra = (unsigned long)entry;
t->ctx.sp = (unsigned long)t->stack + PAGE_SIZE;
t->runnable = 1;
}
void schedule(void)
{
int prev = cur;
do {
cur = (cur + 1) % ntasks;
} while (!tasks[cur].runnable && cur != prev);
if (cur != prev)
switch_to(&tasks[prev].ctx, &tasks[cur].ctx);
}With three tasks that print their id and call schedule() in a loop, the output interleaves in order:
task 0
task 1
task 2
task 0
task 1
task 2Calling schedule() from timer_interrupt instead gives preemption, with one caution: the trap frame lives on the interrupted task's stack, so the switch happens inside the trap handler and returns through it when that task is next scheduled. That works as long as each task has its own stack, which it does.
User mode and system calls
The last piece is running code at the lowest privilege. Entering user mode is done with sret, which returns to whatever mode sstatus.SPP records. Set SPP to 0, which means user, set SPIE so interrupts turn on after the return, put the user entry address in sepc, and execute sret.
void enter_user(unsigned long entry, unsigned long user_sp)
{
unsigned long s = csr_read(sstatus);
s &= ~SSTATUS_SPP; // return to user mode
s |= SSTATUS_SPIE; // interrupts on after sret
csr_write(sstatus, s);
csr_write(sepc, entry);
csr_write(sscratch, current_kernel_sp()); // kernel stack for the next trap
__asm__ volatile("mv sp, %0; sret" : : "r"(user_sp));
}A trap from user mode arrives with sp still pointing at the user's stack, which the kernel must not use. The convention that solves this is sscratch: it holds the kernel stack pointer while user code runs, and zero while the kernel runs. The first instruction of the trap entry swaps it with sp. If the result is non-zero, we came from user mode and sp is now the kernel stack; if it is zero, we came from the kernel and must restore sp.
trap_entry:
csrrw sp, sscratch, sp # swap: sp = kernel stack or 0, sscratch = old sp
bnez sp, 1f # non-zero: we came from user mode
csrr sp, sscratch # zero: we were in the kernel, undo the swap
csrw sscratch, zero
1: addi sp, sp, -288
SAVE_REGS
# ... store the interrupted sp, sepc, sstatus, scause, stval and call trap_handler as before.
# On the way out for a user return, put the kernel sp back into sscratch before sret.The user program makes a system call with ecall. In U mode that raises exception cause 8, "environment call from U-mode", and the handler reads the call number from a7 and arguments from a0 to a5 in the saved frame, following the same convention the SBI uses in S mode. After handling it, advance sepc by 4 so the return lands after the ecall.
void handle_user_ecall(struct trapframe *tf)
{
unsigned long nr = tf->regs[17]; // a7
switch (nr) {
case 1: // write(buf, len)
for (unsigned long i = 0; i < tf->regs[11]; i++)
console_putc(((char *)tf->regs[10])[i]);
tf->regs[10] = tf->regs[11]; // return length in a0
break;
case 93: // exit
kprintf("user exited with %lu\n", tf->regs[10]);
task_exit();
break;
default:
tf->regs[10] = (unsigned long)-1;
}
tf->sepc += 4;
}The user program is a few instructions of assembly, linked separately at a user address and mapped into a user page table with PTE_U:
.section .text
.global user_start
user_start:
li a7, 1
la a0, msg
li a1, 14
ecall
li a7, 93
li a0, 0
ecall
.section .rodata
msg: .ascii "hello, user!\n\0"Running it prints the message from user mode, and the exit call returns control to the kernel:
hello, user!
user exited with 0The system call handler trusts buf in this sketch, reading it straight through the user pointer. A real one validates the range, walks the user page table to check the pages are mapped and readable by the user, and copies the bytes into kernel memory first. Skipping that check is how a user program reads kernel memory by passing a pointer into it, which is a good reason to treat the address of a user buffer as hostile from the first system call you write.
Hooking up interrupts from devices
Timer interrupts come through SBI, but device interrupts such as the UART receiving a byte arrive through the PLIC, the Platform-Level Interrupt Controller, at 0x0C000000. The UART on virt is interrupt source 10. Enabling it takes four register writes: a priority for the source (non-zero), an enable bit for your hart's supervisor context, a threshold of zero so nothing is masked, and sie.SEIE. When an external interrupt arrives, the handler reads the claim register to learn which source fired, services it and writes the same number back to complete it.
#define PLIC_BASE 0x0C000000UL
#define PLIC_PRIORITY(s) (PLIC_BASE + 4 * (s))
#define PLIC_SENABLE(h) (PLIC_BASE + 0x2000 + 0x80 * (2 * (h) + 1))
#define PLIC_STHRESH(h) (PLIC_BASE + 0x200000 + 0x1000 * (2 * (h) + 1))
#define PLIC_SCLAIM(h) (PLIC_BASE + 0x200004 + 0x1000 * (2 * (h) + 1))
#define UART_IRQ 10
void plic_init(unsigned long hart)
{
*(volatile unsigned int *)PLIC_PRIORITY(UART_IRQ) = 1;
*(volatile unsigned int *)PLIC_SENABLE(hart) = 1u << UART_IRQ;
*(volatile unsigned int *)PLIC_STHRESH(hart) = 0;
csr_set(sie, SIE_SEIE);
}
void external_interrupt(void)
{
unsigned int irq = *(volatile unsigned int *)PLIC_SCLAIM(0);
if (irq == UART_IRQ)
uart_rx_interrupt();
if (irq)
*(volatile unsigned int *)PLIC_SCLAIM(0) = irq; // complete
}Context 1 of each hart is its supervisor context, which is why the offsets use 2 * hart + 1. The dedicated post on the CLINT and PLIC gives the full register map and the multi-hart case.
Reading the device tree instead of hard-coding the map
Everything above hard-codes the virt memory map, which is fine for a first kernel and wrong the moment you target a second board. Firmware tells the kernel what the machine looks like by passing a flattened device tree, an FDT, and OpenSBI hands you its address in a1. The format is documented in the Devicetree Specification, and it is simple enough to walk by hand.
An FDT begins with a header of big-endian 32-bit fields: the magic 0xd00dfeed, the total size, and offsets to two blocks. The structure block is a sequence of tokens that describe the tree: FDT_BEGIN_NODE (1) followed by the node name, FDT_END_NODE (2), FDT_PROP (3) followed by a length, a name offset and the value bytes, and FDT_END (9). The strings block holds property names, referenced by offset. Everything is big-endian, because the format predates the little-endian world, and every value is padded to 4 bytes.
#include <stdint.h>
static inline uint32_t be32(const void *p)
{
const uint8_t *b = p;
return ((uint32_t)b[0] << 24) | ((uint32_t)b[1] << 16) | ((uint32_t)b[2] << 8) | b[3];
}
struct fdt_header {
uint32_t magic, totalsize, off_dt_struct, off_dt_strings, off_mem_rsvmap;
uint32_t version, last_comp_version, boot_cpuid_phys, size_dt_strings, size_dt_struct;
};
// Print every node name and its "compatible" string, so you can see the machine.
void fdt_dump(const void *dtb)
{
const uint8_t *base = dtb;
if (be32(base) != 0xd00dfeed) {
kprintf("no device tree\n");
return;
}
const uint8_t *p = base + be32(base + 8); // structure block
const char *strings = (const char *)base + be32(base + 12);
int depth = 0;
for (;;) {
uint32_t tok = be32(p);
p += 4;
if (tok == 1) { // FDT_BEGIN_NODE
kprintf("%*s%s\n", depth * 2, "", (const char *)p);
size_t n = strlen((const char *)p) + 1;
p += (n + 3) & ~3UL;
depth++;
} else if (tok == 2) { // FDT_END_NODE
depth--;
} else if (tok == 3) { // FDT_PROP
uint32_t len = be32(p), nameoff = be32(p + 4);
const char *name = strings + nameoff;
const char *val = (const char *)p + 8;
if (strcmp(name, "compatible") == 0)
kprintf("%*s compatible = %s\n", depth * 2, "", val);
p += 8 + ((len + 3) & ~3UL);
} else if (tok == 9) { // FDT_END
break;
} // FDT_NOP (4) falls through
}
}On the virt machine the output starts like this. The tree is much longer, with an entry for each device, and the node addresses are the ones in the memory map table earlier:
cpus
cpu@0
compatible = riscv
memory@80000000
soc
compatible = simple-bus
uart@10000000
compatible = ns16550a
plic@c000000
compatible = sifive,plic-1.0.0The empty first line is the root node, whose name is the empty string. A kernel that reads the memory node's reg property to learn RAM size, and the uart node to find the console, no longer needs the constants in pmm.c. Do that once the hard-coded version works, because the device tree is where a port to real hardware starts.
Interrupts and the rule for shared data
The timer handler and the allocator run in different contexts, and they can both touch shared state. On a single hart the only concurrency is interrupts, and the rule is the same as on every architecture: code that shares data with an interrupt handler must run with interrupts masked. On RISC-V the global switch is the SIE bit of sstatus, and the instructions csrrc and csrrs read and clear or set it atomically.
static inline unsigned long intr_off(void)
{
unsigned long old;
__asm__ volatile("csrrc %0, sstatus, %1" : "=r"(old) : "r"(SSTATUS_SIE) : "memory");
return old & SSTATUS_SIE; // was it on?
}
static inline void intr_restore(unsigned long was_on)
{
if (was_on)
csr_set(sstatus, SSTATUS_SIE);
}Use the pair around any critical section, such as the free list manipulation in pmm_alloc, and remember the value it returns: an unconditional re-enable would turn interrupts on in code that was entered with them off. When a trap is taken, the hardware clears SIE for you and saves the old value in SPIE, which is why a trap handler runs with interrupts off until it re-enables them, and why sret restores them.
A kernel heap
Whole pages are the wrong size for most kernel allocations. A process control block, a file structure or a small buffer needs tens of bytes. The simplest useful heap takes a page from the page allocator and carves it up. A bump allocator is enough to start: it hands out consecutive addresses and never frees.
static char *arena;
static unsigned long arena_left;
void *kmalloc(unsigned long n)
{
n = (n + 15) & ~15UL; // 16-byte alignment, which satisfies any C type
if (n > PAGE_SIZE)
return 0;
if (n > arena_left) {
arena = pmm_alloc();
if (!arena)
return 0;
arena_left = PAGE_SIZE;
}
void *p = arena;
arena += n;
arena_left -= n;
return p;
}It wastes the tail of each page and cannot free, which is acceptable for structures that live as long as the kernel. When you need kfree, the step up is size classes: one free list per power of two from 16 bytes to 2 KiB, each refilled by slicing a fresh page. That gives constant-time allocation and free and bounded waste, which is why it is the design behind most small kernels' heaps.
More than one hart
Everything so far runs on a single hart, the hardware thread QEMU starts with -smp 1. With -smp 4, OpenSBI picks one hart, passes its ID to your entry point, and parks the others. Starting them is a firmware call, from the SBI Hart State Management extension, extension ID 0x48534D, function 0, hart_start. It takes the hart ID, the physical address where that hart begins executing, and an opaque value delivered in a1.
#define SBI_EXT_HSM 0x48534D
int hart_start(unsigned long hartid, unsigned long entry, unsigned long opaque)
{
struct sbiret r = sbi_call(SBI_EXT_HSM, 0, (long)hartid, (long)entry, (long)opaque);
return (int)r.error;
}
void start_other_harts(unsigned long boot_hart, unsigned long nharts)
{
extern void secondary_entry(void);
for (unsigned long h = 0; h < nharts; h++) {
if (h == boot_hart)
continue;
int err = hart_start(h, (unsigned long)secondary_entry, h);
kprintf("hart %lu start: %d\n", h, err);
}
}The new hart begins at secondary_entry in S mode with paging off, a0 holding its hart ID and a1 the opaque value. It needs its own stack, so the entry code picks a per-hart stack from an array indexed by ID. The count of harts comes from the device tree's cpus node. The moment a second hart runs, every shared structure needs a lock: the page allocator, the console, the task list. RISC-V's atomic instructions make spinlocks short: amoswap.w.aq acquires and amoswap.w.rl with zero releases, and the same rule applies about disabling local interrupts while holding one.
Memory ordering on RISC-V
RISC-V uses a weak memory model, RVWMO, defined in the unprivileged specification. A hart may reorder its own loads and stores as seen by other harts, and the instruction fence is the tool that restores order. For a single-hart kernel this barely matters, but two cases always do.
Device registers need fence between the write that sets up a request and the write that starts it, such as filling a virtio descriptor and then writing the queue notify register. Without it, the device can observe the notification before the descriptor data. And instruction memory needs fence.i after code is written and before it is run, which a kernel does when it loads a user program into pages it just filled: the instruction fetch is not guaranteed to see recent stores to the same address until fence.i executes. Page table changes need sfence.vma, as shown earlier.
static inline void fence_rw(void) { __asm__ volatile("fence rw, rw" ::: "memory"); }
static inline void fence_i(void) { __asm__ volatile("fence.i" ::: "memory"); }Testing without a screen
A kernel you can only test by eye does not get tested. QEMU's virt machine includes a test finisher device at 0x100000 that ends the emulator with an exit status, so a script can run the kernel and check the result. Writing 0x5555 to it exits with status 0; writing (code << 16) | 0x3333 exits with a failure and code in the upper bits.
#define FINISHER ((volatile unsigned int *)0x100000UL)
void qemu_exit(int code)
{
if (code == 0)
*FINISHER = 0x5555;
else
*FINISHER = ((unsigned int)code << 16) | 0x3333;
for (;;)
__asm__ volatile("wfi");
}
void ktest_assert(int cond, const char *what)
{
if (!cond) {
kprintf("FAIL: %s\n", what);
qemu_exit(1);
}
}The finisher's mapping must exist in the page table once paging is on, so add its page to vm_init. With that, a boot test is a make run whose exit status says pass or fail, which is what continuous integration needs:
pmm: 32744 pages free
ok: allocator returns distinct pages
ok: map_page maps a test address
ok: context switch preserves s registers
all tests passedThe SBI shutdown call used earlier exits QEMU with a zero status regardless of what happened, so use the finisher for tests and keep SBI shutdown for the happy path of a demo.
A printf worth having
Every debugging session in this guide depends on kprintf, and a kernel cannot call the library printf, since there is no library. Write a small one early, because every other component will use it, and a bug in it hides every other bug. It needs four conversions for most work: %d for signed decimals, %x for hexadecimal, %s for strings and %c for characters, with the l length modifier for 64-bit values and %p as a convenience for pointers.
#include <stdarg.h>
static void print_num(unsigned long v, int base, int is_signed)
{
char buf[24];
int n = 0;
unsigned long u = v;
if (is_signed && (long)v < 0) {
console_putc('-');
u = (unsigned long)(-(long)v);
}
do {
buf[n++] = "0123456789abcdef"[u % base];
u /= base;
} while (u);
while (n--)
console_putc(buf[n]);
}
void kprintf(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
for (; *fmt; fmt++) {
if (*fmt != '%') {
console_putc(*fmt);
continue;
}
fmt++;
int is_long = 0;
if (*fmt == 'l') { is_long = 1; fmt++; }
switch (*fmt) {
case 'd': print_num(is_long ? va_arg(ap, long) : va_arg(ap, int), 10, 1); break;
case 'u': print_num(is_long ? va_arg(ap, unsigned long) : va_arg(ap, unsigned), 10, 0); break;
case 'x': print_num(is_long ? va_arg(ap, unsigned long) : va_arg(ap, unsigned), 16, 0); break;
case 'p': console_puts("0x"); print_num((unsigned long)va_arg(ap, void *), 16, 0); break;
case 's': { const char *s = va_arg(ap, const char *); console_puts(s ? s : "(null)"); break; }
case 'c': console_putc((char)va_arg(ap, int)); break;
case '%': console_putc('%'); break;
default: console_putc('%'); console_putc(*fmt); break;
}
}
va_end(ap);
}Notice that the signed int case widens to long through the ternary, so a negative int keeps its sign when print_num checks (long)v. The one limitation worth knowing is that this version has no field widths, so earlier examples that used %*s for indentation need a small extension, or a loop that prints spaces before the call.
Because kprintf calls console_putc, which calls ecall, it is slow. Each character is a trap into firmware. That is fine for a boot log and wrong for a kernel that logs in a hot path, which is the reason to write the direct UART driver covered in the next post and keep SBI only as the fallback for the earliest code.
Handling page faults
Once paging is on, three of the exceptions you will see are page faults: instruction page fault (cause 12), load page fault (13) and store page fault (15). stval holds the faulting virtual address and sepc the instruction that caused it. For a kernel that maps everything it uses up front, a page fault is always a bug, and the handler's job is to print what it knows and stop:
static const char *fault_name(unsigned long cause)
{
switch (cause) {
case 12: return "instruction page fault";
case 13: return "load page fault";
case 15: return "store page fault";
default: return "unknown";
}
}
void page_fault(struct trapframe *tf)
{
kprintf("%s at %lx, address %lx\n", fault_name(tf->scause), tf->sepc, tf->stval);
sbi_shutdown();
}For a store to a null pointer the log is two lines, and it names both the instruction and the address. The program counter will differ on your build:
store page fault at 0x0000000080201d4c, address 0x0000000000000008The fault address of 8 says the code stored through a null base pointer plus a structure offset of 8, which is the most common pattern. That one line is usually enough to find the bug, and it is why the handler is worth writing before you need it.
Later, the same handler becomes the place where demand paging and copy-on-write live: instead of stopping, it allocates a page, maps it at the faulting address and returns. The structure stays the same, and the policy grows.
How the pieces depend on each other
The order of this guide is not arbitrary, and knowing why helps when you extend it. Console output comes first because nothing else can be debugged without it. Traps come second because every later bug will arrive as one, and a kernel without a trap handler turns each into a silent hang. Interrupts and the timer come next because they depend on traps. The page allocator comes before paging because the page tables need pages to live in, and paging comes before tasks and user mode because user isolation is built from page table permissions. Tasks come before user mode because the first user program is just a task that happens to drop its privilege.
If you try to reorder, the dependencies bite. A task switch before traps means a single wrong instruction stops the machine with no explanation. Paging before an allocator means hand-placing page tables in static arrays, which works for one table and falls apart at the second. User mode before paging means no isolation, which defeats the point.
What to build next
The skeleton is complete, and four directions extend it, in roughly increasing difficulty. First, device drivers: the virtio block device on virt gives you a disk with a small, well-specified interface, and a filesystem on top gives the user program something to read. Second, a better scheduler: the round robin here ignores priorities, blocking and sleeping, and a run queue with sleep lists, as in the scheduler post of this series, is the next step. Third, processes: give each user program its own page table with the kernel mapped in every one, a trampoline page for trap entry, and fork and exec. Fourth, multiple harts, as outlined above, which touches every data structure in the kernel and is the best teacher of locking you will find.
Each of these is a project of its own, and a kernel is never done. The goal of this guide is that the base is solid: a kernel that boots, reports faults clearly, owns its memory and runs code at two privilege levels. Everything else is a chapter you add.
Naming things the way the specification does
A habit that pays off early is using the specification's own names for bits and registers, in code and in comments. SSTATUS_SPIE rather than PREV_INT_ENABLE, scause rather than trap_reason, and PTE_V rather than PRESENT. When something misbehaves at two in the morning, you will search the privileged manual for the exact string, and a codebase that matches it lets you check a bit position against the document in seconds. It also makes your code readable to anyone who has read another RISC-V kernel, including the Linux and xv6 ports, which use the same names.
Pair that with one more discipline: every magic number gets a named constant that cites its source in the comment, such as the PLIC context formula or the SBI extension IDs, so the next reader can verify them rather than trust them.
Reading the privileged specification as you build
The manuals are short and precise, and a kernel author gets more from reading them in the right order than from any tutorial. Start with the privilege levels and the mstatus and sstatus chapters, since every trap and return touches them. Read the trap chapter next, with the description of stvec and scause open beside your handler. Read the Sv39 section before writing a single page table entry, and keep the table of leaf and pointer encodings in view. Read the SBI specification's list of extensions once, so you know what the firmware offers before you write code for something it already does.
When a bit does not behave as you expect, the specification wins over memory and over this guide. Search it for the exact register name, check the field's width and its reset value, and check whether the field is read-only, write-any-read-legal or write-legal-read-legal, a distinction that explains why a write that looks correct sometimes reads back differently.
Keeping the kernel honest with assertions
A small macro pays for itself within the first week. assert(cond) that prints the file, the line and the failed expression, then shuts the machine down through the test finisher, turns a corrupted data structure from a mystery crash three calls later into a message at the first inconsistency. Put assertions where an invariant is cheap to state: a page address is aligned, a task is on at most one list, a lock is not already held by this hart, a trap came from the mode you expected. Keep them on in every build while the kernel is small. Their cost is a compare and a branch, and the kernel runs under an emulator that does not care.
Debugging a kernel that does not print
When nothing appears, narrow the failure with two tools. QEMU's -d int,cpu_reset -D qemu.log logs every trap taken, so you can see an exception loop, and -s -S starts a GDB server halted at reset, to which you attach with riscv64-unknown-elf-gdb kernel.elf and target remote :1234.
| Symptom | Likely cause |
|---|---|
| Nothing after the OpenSBI banner | Wrong load address, -bios dropped, or a bad entry in the linker script |
| Prints once, then hangs | Stack not set up, or a trap taken with stvec unset, looping at address 0 |
Hang right after writing satp | Something the code touches is missing from the page table |
| Interrupt storm | Timer not re-armed in the handler, or a PLIC source never completed |
scause=0xd or 0xf | Page fault on a load or store: unmapped, or a missing A or D bit |
User program traps with scause=0xc | The user page lacks the X permission or the U bit |
A trace log is the most valuable of these. A kernel stuck in a trap loop prints nothing, and the log shows the same two addresses repeating.
Where to read next
Each section here compresses a deeper post. The privilege modes post explains why the three-level design works, and the CSR post lists every register a kernel author touches. The bare-metal post builds this boot in full detail and the UART driver post replaces the SBI console with a direct 16550 driver. The OpenSBI post covers the full set of calls beyond the ones used here, and the trap post goes deeper into stvec modes and scause decoding. The Sv39 post builds the page table code in more depth, the CLINT and PLIC post covers interrupt routing, and the context switching post is the full assembly version. To see how a production kernel does all of this, the Linux boot post follows its RISC-V port from OpenSBI to start_kernel.
When this approach does not fit
The design above fits learning on QEMU, and four common goals pull away from it.
If you target a real board, the memory map, the console and the firmware differ. A SiFive or StarFive board has its own UART base address and interrupt wiring, and you read them from the device tree that firmware passes in a1 instead of hard-coding the virt map. The kernel logic is the same, and the board support is not.
If you want a kernel that runs in machine mode, with no firmware beneath it, you lose the SBI conveniences and must program the CLINT timer, the PMP registers and the trap delegation yourself. That is a valid and educational choice, and it is a different guide.
If you need 32-bit RISC-V, the register width, the Sv32 paging format with two levels and the pointer size all change. The control flow and the ideas carry over unchanged, but every constant in the paging code does not.
And if you plan on multiple harts, none of the code above is safe, since it assumes one core. Booting the other harts is done with the SBI Hart State Management extension, and then every shared structure needs locking.


