xv6, line by line
kernel/entry.S

kernel/entry.S

RISC-V assembly · 21 lines · annotated 100% · kernel · upstream

About this file

These 21 lines are the first xv6 code any CPU runs. When QEMU starts, every hart (CPU core) starts running in parallel, in no particular order; after a few instructions in QEMU’s boot ROM, each one arrives here, in machine mode, with no stack, no virtual memory and no interrupts.

Compiled C code needs a stack before it can run, so this file does exactly one job: give each hart its own stack, then call the C function start in kernel/start.c. It is written in RISC-V assembly because C cannot set the stack pointer for itself.

Read before: kernel/kernel.ld, which places this code at address 0x80000000. Read next: kernel/start.c.

1 # qemu -kernel loads the kernel at 0x80000000
2 # and causes each hart (i.e. CPU) to jump there.
3 # kernel.ld causes the following code to
4 # be placed at 0x80000000.
5.section .text
6.global _entry
8 # set up a stack for C.
9 # stack0 is declared in start.c,
10 # with a 4096-byte stack per CPU.
11 # sp = stack0 + ((hartid + 1) * 4096)
12 la sp, stack0
13 li a0, 1024*4
14 csrr a1, mhartid
15 addi a1, a1, 1
16 mul a0, a0, a1
17 add sp, sp, a0
18 # jump to start() in start.c
19 call start