xv6, line by line
kernel/main.c

kernel/main.c

C · 45 lines · annotated 100% · kernel · upstream

About this file

main is where every hart arrives in supervisor mode, after start's mret. It brings up the kernel in a fixed order and then hands each CPU to the scheduler, which never returns.

The work is split. Hart 0 initializes everything that exists once for the whole machine: the console, the page allocator, the kernel’s page table, the process table, the disk, the first process. Every other hart waits until hart 0 says it is done, then configures only its own per-CPU hardware. A shared flag, started, carries the “done” signal safely from one hart to the others.

The list of calls on lines 14–31 doubles as a table of contents for the kernel: each call is the entry point of one subsystem, and following them one by one is a good way to tour xv6.

Read before: kernel/start.c. Read next: kernel/vm.c (the page tables set up here) or kernel/proc.c (userinit and scheduler).

1#include "types.h"
2#include "param.h"
4#include "riscv.h"
5#include "defs.h"
7volatile static int started = 0;
9// start() jumps here in supervisor mode on all CPUs.
10void
13 if (cpuid() == 0) {
16 printk("\n");
17 printk("xv6 kernel is booting\n");
18 printk("\n");
19 kinit(); // physical page allocator
20 kvminit(); // create kernel page table
21 kvminithart(); // turn on paging
22 procinit(); // process table
23 trapinit(); // trap vectors
24 trapinithart(); // install kernel trap vector
25 plicinit(); // set up interrupt controller
26 plicinithart(); // ask PLIC for device interrupts
27 binit(); // buffer cache
28 iinit(); // inode table
29 fileinit(); // file table
30 virtio_disk_init(); // emulated hard disk
31 userinit(); // first user process
33 __atomic_store_n(&started, 1, __ATOMIC_RELEASE);
34 } else {
35 while (__atomic_load_n(&started, __ATOMIC_ACQUIRE) == 0)
36 ;
38 printk("hart %d starting\n", cpuid());
39 kvminithart(); // turn on paging
40 trapinithart(); // install kernel trap vector
41 plicinithart(); // ask PLIC for device interrupts
42 }