Skip to content
systemcoding.dev
Kernels

Write a Bare-Metal RISC-V Kernel That Runs on QEMU virt

Build the smallest RISC-V kernel that boots on QEMU virt: a linker script at 0x80200000, an entry stub, a C main printing through the UART, and a GDB check.

7 min read
Summarize in AI
Flat illustration of user space above the system call boundary, the kernel and the hardware, with the RISC-V, QEMU and Linux logos.

The smallest useful kernel does three things: it starts at the address the machine jumps to, it gets a stack so C can run, and it prints a line. On RISC-V and QEMU's virt machine, that is four small files and a Makefile, and building it teaches the pieces every later kernel reuses: the linker script, the entry stub, the toolchain flags and the debugging loop. This post builds exactly that, explains each file, and then checks the result in three independent ways, with readelf, with objdump and with GDB, so that when something is wrong you know which layer is at fault.

The guide to writing a RISC-V kernel in this series builds a full kernel. This post is the first hour of it, slowed down. It targets QEMU 9.2 with the default OpenSBI firmware and a GCC 14 cross toolchain for riscv64-unknown-elf.

How the machine starts

When you run qemu-system-riscv64 -machine virt with -bios default, QEMU loads OpenSBI into RAM at 0x80000000 and starts the first hart there. OpenSBI initializes the platform in machine mode, then jumps to the next stage, which it expects at 0x80200000, in supervisor mode. QEMU's -kernel option places your ELF's loadable segments at the addresses it names, and OpenSBI finds the entry point there.

On arrival, you can rely on exactly three things. The processor is in supervisor mode with translation off, so addresses are physical. Register a0 holds the hart ID and a1 holds the physical address of the device tree blob. And nothing else is set up: the stack pointer is whatever OpenSBI left, .bss holds whatever was in memory, and interrupts are off. The entry code has to fix the stack and .bss before any C runs.

The files

A bare-metal project needs four source files and a build recipe:

FileJob
kernel.ldTells the linker where to put the code and exposes boundary symbols
entry.SSets the stack, clears .bss, calls C
uart.cPrints characters
main.cThe kernel proper

The linker script

The linker script is the one place that decides where the kernel lives, so get the address right. Without it the linker picks a default that has nothing to do with 0x80200000, and OpenSBI jumps into empty memory.

kernel.ldld
OUTPUT_ARCH(riscv)
ENTRY(_start)

SECTIONS {
    . = 0x80200000;

    .text : ALIGN(4096) {
        *(.text.entry)           /* the entry stub must come first */
        *(.text .text.*)
    }

    .rodata : ALIGN(4096) {
        *(.rodata .rodata.*)
    }

    .data : ALIGN(4096) {
        *(.data .data.*)
    }

    .bss : ALIGN(4096) {
        __bss_start = .;
        *(.bss .bss.*)
        *(COMMON)
        __bss_end = .;
    }

    /DISCARD/ : {
        *(.comment)
        *(.note*)
        *(.eh_frame)
    }
}

Putting .text.entry first guarantees that the first byte at 0x80200000 is the first instruction of _start, which does not depend on the link order of object files. The __bss_start and __bss_end symbols are addresses the linker computes, which the entry code uses to zero the section. Discarding .eh_frame and notes removes unwinding tables that a freestanding kernel never reads.

The entry stub

Assembly runs first because C needs a stack and a clean .bss, and C cannot set those up for itself.

entry.Sasm
    .section .text.entry
    .global _start
_start:
    la   sp, stack_top            # a stack for C

    la   t0, __bss_start          # zero .bss, 8 bytes at a time
    la   t1, __bss_end
1:  bgeu t0, t1, 2f
    sd   zero, 0(t0)
    addi t0, t0, 8
    j    1b

2:  call kmain                    # a0 = hart id and a1 = dtb are still intact
3:  wfi                           # kmain should not return; if it does, sleep
    j    3b

    .section .bss
    .align 4
stack_bottom:
    .space 16384
stack_top:

Registers a0 and a1 stay untouched from entry to the call, because nothing in the stub writes them, so kmain(unsigned long hartid, void *dtb) receives the firmware's values with no extra work. The .bss loop zeroes 8 bytes per iteration and requires the section to be 8-byte sized and aligned, which the linker script's ALIGN(4096) guarantees at the start and whose end is rounded by the linker.

The UART and the kernel

The console is the direct UART driver from the previous post, reduced to its essentials:

uart.cc
#define UART0 ((volatile unsigned char *)0x10000000UL)

void uart_putc(char c)
{
    while (!(UART0[5] & 0x20))        // LSR bit 5: transmit holding register empty
        ;
    UART0[0] = (unsigned char)c;
}

void uart_puts(const char *s)
{
    for (; *s; s++) {
        if (*s == '\n')
            uart_putc('\r');
        uart_putc(*s);
    }
}
main.cc
void uart_puts(const char *s);

void kmain(unsigned long hartid, void *dtb)
{
    (void)hartid;
    (void)dtb;
    uart_puts("hello from bare-metal RISC-V\n");
    for (;;)
        __asm__ volatile("wfi");
}

The Makefile

Every flag in the build is there for a reason, and a wrong one produces symptoms that look like unrelated bugs.

Makefilemakefile
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 uart.o main.o

kernel.elf: $(OBJS) kernel.ld
	$(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.elf

debug: kernel.elf
	qemu-system-riscv64 -machine virt -cpu rv64 -smp 1 -m 128M \
	    -nographic -bios default -kernel kernel.elf -s -S

clean:
	rm -f *.o kernel.elf

-march names the instruction set and its extensions: i for integers, m for multiply and divide, a for atomics, c for compressed 16-bit instructions, with zicsr and zifencei for the CSR and instruction-fence instructions that older toolchains bundled into the base. -mabi=lp64 says integers and pointers are 64-bit with no floating point arguments in registers. -mcmodel=medany is the setting that makes position-independent addressing work at 0x80200000; the default medlow model can only address the lowest 2 GiB, which does not include it. -mno-relax stops the linker from rewriting instruction sequences in ways that interact badly with the entry stub's la. -ffreestanding -nostdlib -static remove the host's assumptions.

For QEMU, -nographic connects the UART to your terminal, -smp 1 uses one hart so there is no second core to start, and -bios default loads OpenSBI.

Run it

Shell
make run

OpenSBI prints its banner and platform summary, then your line appears. Exit QEMU with Ctrl-a x. The banner details vary with the OpenSBI version bundled in QEMU:

Text
OpenSBI v1.5
   ____                    _____ ____ _____
  / __ \                  / ____|  _ \_   _|
 | |  | |_ __   ___ _ __ | (___ | |_) || |
 | |  | | '_ \ / _ \ '_ \ \___ \|  _ < | |
 | |__| | |_) |  __/ | | |____) | |_) || |_
  \____/| .__/ \___|_| |_|_____/|____/_____|
        | |
        |_|

Platform Name             : riscv-virtio,qemu
...
Boot HART ID              : 0
Boot HART ISA             : rv64imafdch_zicsr_zifencei_...
...
hello from bare-metal RISC-V

Check it three ways

When the kernel does not print, find out which layer failed. Each tool answers a different question.

Did the linker put things where you wanted? readelf shows the entry point and the segments:

Shell
riscv64-unknown-elf-readelf -h kernel.elf | grep Entry
riscv64-unknown-elf-readelf -lW kernel.elf
Text
  Entry point address:               0x80200000
Program Headers:
  Type  Offset   VirtAddr           PhysAddr           FileSiz MemSiz  Flg Align
  LOAD  0x001000 0x0000000080200000 0x0000000080200000 0x0000b6 0x0000b6 R E 0x1000
  LOAD  0x002000 0x0000000080201000 0x0000000080201000 0x00001e 0x00001e R   0x1000
  LOAD  0x003000 0x0000000080202000 0x0000000080202000 0x000000 0x004000 RW  0x1000

The entry point is 0x80200000. If it is anything else, the linker script was not used or .text.entry was dropped. The last segment has a zero FileSiz and a MemSiz of 16 KiB: that is .bss with the stack, present in memory and absent from the file.

Is the first instruction what you think? Disassemble the start of the file:

Shell
riscv64-unknown-elf-objdump -d kernel.elf | head -12
Text
0000000080200000 <_start>:
    80200000:	00004117          	auipc	sp,0x4
    80200004:	00010113          	mv	sp,sp
    80200008:	00002297          	auipc	t0,0x2

The first two instructions are the expansion of la sp, stack_top: an auipc, which adds a 20-bit offset to the program counter, and an add. Seeing PC-relative instructions confirms medany took effect.

Does it run? Start QEMU halted and attach GDB:

Shell
make debug
riscv64-unknown-elf-gdb kernel.elf -ex "target remote :1234" -ex "break kmain" -ex "continue"

The -s flag opens a GDB server on port 1234 and -S halts the CPU at the first instruction, so you control when it starts. When the breakpoint hits, info registers a0 a1 shows the hart ID and device tree address that OpenSBI passed:

Text
Breakpoint 1, kmain (hartid=0, dtb=0xbfe00000) at main.c:6
a0             0x0      0
a1             0xbfe00000       3220176896

Reaching kmain with a0 equal to 0 proves the whole chain: OpenSBI found your kernel, the entry stub ran, the stack and .bss were set, and the call happened.

What goes wrong

A kernel that prints nothing after the OpenSBI banner has one of a few problems. The most common is a wrong load address: OpenSBI jumps to 0x80200000, and if your linker script put the code elsewhere, it executes zeros. The second is a missing -mcmodel=medany, which makes the linker fail with relocation errors such as relocation truncated to fit: R_RISCV_HI20. The third is forgetting the stack: the first function call that uses it writes into whatever sp happened to hold. The fourth is writing to a UART address with the wrong width, which shows up as garbled output.

If the kernel prints garbage characters, check that the build zeroed .bss before using it, and that uart_putc waits on bit 5 of the line status register, not another bit.

Boundaries

This kernel trusts OpenSBI, uses one hart and does not set up traps. A trap taken now, even a stray illegal instruction, has no handler, and the CPU jumps to address zero and stops. That is acceptable for the first hour, and the very next thing to add is a trap vector, so that a mistake produces a message instead of a silent halt. If you intend to boot on a real board, you will also replace the hard-coded UART address with one read from the device tree.

Also inAssembly
Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.