What the kernel sets up before the first process
About this lesson
When the kernel first runs, nothing a program needs exists yet: no list of free memory, no trap table, no process table, no processes. Follow the eight lines of xv6's kernel main(), the teaching kernel of MIT 6.1810, as each one builds a part, until the kernel makes process 1 by hand and its scheduler runs it. The Software lesson on what an operating system does and the Hardware lesson on interrupts and I/O are good warm-ups, and How Linux boots covers the boot order that gets the kernel this far.
The kernel starts alone
A boot loader has copied the kernel into memory and jumped to it. The CPU is in kernel mode, running one thing: the kernel's main(). No free-memory list, trap table or process exists yet. Each line of main() builds one.
xv6's main() on the first CPU (abridged): 1 kinit(); // free page list 2 kvminit(); // kernel page table 3 procinit(); // process table 4 trapinithart(); // trap table 5 plicinit(); // interrupts 6 virtio_disk_init(); // disk driver 7 userinit(); // process 1 8 scheduler(); // run it mode kernel (the machine starts in kernel mode) exists only the kernel code itself
Read the lesson step by step
The kernel starts alone
A boot loader has copied the kernel into memory and jumped to it. The CPU is in kernel mode, running one thing: the kernel's main(). No free-memory list, trap table or process exists yet. Each line of main() builds one.
xv6's main() on the first CPU (abridged): 1 kinit(); // free page list 2 kvminit(); // kernel page table 3 procinit(); // process table 4 trapinithart(); // trap table 5 plicinit(); // interrupts 6 virtio_disk_init(); // disk driver 7 userinit(); // process 1 8 scheduler(); // run it mode kernel (the machine starts in kernel mode) exists only the kernel code itselfLine 1: list the free memory
kinit() cuts the free RAM into pages of 4096 bytes and puts every page the kernel is not using onto a free list. From now on, every page the kernel or a program needs is taken from this list.
line 1 kinit(); xv6 kinit() -> freerange(end, PHYSTOP) for each page from the end of the kernel to the top of RAM: kfree(page) (push it on the list) page 4096 bytes Linux the same job is part of mm_core_init()Line 2: the kernel page table
kvminit() takes a page from the free list and builds the kernel's page table: the map from the addresses code uses to real places in RAM. Then it writes the table's address into the CPU register satp, which turns paging on.
line 2 kvminit(); (and kvminithart()) kvminit kalloc() a page, map kernel code, data, RAM and devices into it kvminithart w_satp(MAKE_SATP(kernel_pagetable)) satp "holds the address of the page table" changing it is privileged: kernel mode onlyLine 3: the process table
procinit() sets up the process table: 64 slots in xv6, one per possible process, each marked UNUSED. A process will be a filled-in slot plus its own memory, so this table must exist before any process can.
line 3 procinit(); slots NPROC = 64 each state = UNUSED, a lock, a kernel stack address later pid, page table, saved registers, open filesLine 4: where traps land
trapinithart() writes the address of the kernel's trap handler into the CPU register stvec. System calls, faults and interrupts will all enter the kernel at that one place. A program cannot change it: that needs kernel mode.
line 4 trapinithart(); (after trapinit()) xv6 w_stvec((uint64)kernelvec) stvec where the CPU jumps on every trap x86-64 the same job: an interrupt table (IDT), set up by trap_init() in LinuxLine 5: interrupts and the timer
plicinit() sets up the interrupt controller, which passes device signals to the CPU. The timer, armed just before main(), fires about a tenth of a second in xv6. So the kernel can always take the CPU back.
line 5 plicinit(); (and plicinithart()) PLIC routes device interrupts (disk, keyboard) to a CPU timer start() -> timerinit(): first timer interrupt clockintr(): next one 1000000 cycles later, about a tenth of a second (xv6 comment) Linux init_IRQ() then time_init()Line 6: the disk and files
virtio_disk_init() starts the disk driver. The lines just before it set up the buffer cache, the inode table and the file table. Now the kernel can read files from the disk, such as the first program.
line 6 virtio_disk_init(); binit() buffer cache (disk blocks in RAM) iinit() inode table (files in use) fileinit() file table (open files) virtio_disk_init() the disk driver; takes pages tooLine 7: process 1, by hand
No process exists to call fork(), so userinit() makes the first one by hand. It fills an empty slot with process ID 1, takes free pages for its page table and saved registers, and marks it RUNNABLE.
line 7 userinit(); allocproc() first UNUSED slot pid = nextpid (nextpid starts at 1) kalloc() a trapframe page (saved registers) proc_pagetable(): its own page table state RUNNABLE Linux rest_init(): "spawn init first so that it obtains pid 1"Line 8: the scheduler takes over
scheduler() never returns. It loops forever, choosing a RUNNABLE process and switching the CPU to it. Right now there is only one: process 1. The kernel's start-up code is finished.
line 8 scheduler(); loop find a RUNNABLE slot swtch(&c->context, &p->context) the process runs until it gives the CPU back, or the timer takes it back chosen pid 1Process 1 loads /init
Still in kernel mode, process 1 first loads the program /init from the disk into its own pages. Then it returns from a trap: the CPU drops to user mode, and /init starts the shell. Linux does the same with /init or /sbin/init.
xv6 forkret(): fsinit(ROOTDEV); kexec("/init", ...) then return to user mode Linux kernel_init() runs /init from the initramfs if there is one, else init= or, in turn, /sbin/init, /etc/init, /bin/init, /bin/sh else panic: "No working init found." the same request as a user program (C99, POSIX): #include <stdio.h> #include <unistd.h> int main(void) { char *argv[] = { "/init", NULL }; execv("/init", argv); /* returns only if it failed */ perror("execv"); return 1; }Why this order?
Each part needs ones built before it. A process needs free pages and a table slot. Running it safely needs the trap table, interrupts and the disk. Only when all exist does the kernel hand the CPU to a program.
the order as a Python simulation: NEEDS = { "free pages": [], "page table": ["free pages"], "process table": [], "trap table": [], "interrupts": [], "disk": ["free pages"], "process 1": ["free pages", "process table"], "run process 1": ["process 1", "trap table", "interrupts", "disk"], } def boot(order): built = [] for part in order: for need in NEEDS[part]: if need not in built: raise RuntimeError(part + " needs " + need) built.append(part) return built print(len(boot(list(NEEDS))), "parts built") try: boot(["process 1"]) # too early except RuntimeError as e: print("refused:", e) prints: 8 parts built refused: process 1 needs free pages
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01What does xv6's kinit() build?
kinit() walks from the end of the kernel to the top of RAM and frees every page onto a list. Every later page, for page tables, processes or the disk driver, is taken from that list.
02Why must the trap table (stvec on RISC-V) be set before any program runs?
Every trap jumps to the address in the trap table. Setting it is privileged, so the kernel does it at boot in kernel mode, before handing the CPU to any program.
03What is the job of the timer the kernel arms during start-up?
A program might never make a system call. The timer interrupt guarantees the kernel runs again, so it can switch to another process.
04No process exists yet to call fork(). How does the first process come to be?
userinit() calls allocproc(), which takes the first UNUSED slot and the next process ID, starting at 1. Every other process is later made by fork() from it or its descendants.
05On Linux, which program does the kernel try first as process 1 when there is no initramfs and no init= option?
kernel_init() tries /sbin/init, then /etc/init, /bin/init and /bin/sh, and panics with "No working init found." if none runs. With an initramfs it first runs /init from it.
Glossary
- Page
- A fixed-size block of memory, 4096 bytes in xv6. The kernel hands out memory a page at a time.
- Free list
- The kernel's list of pages nobody is using. kinit() builds it; kalloc() takes a page from it and kfree() puts one back.
- Page table
- A map from the addresses code uses (virtual addresses) to real places in RAM. The CPU register satp on RISC-V holds the address of the current one.
- Process table
- The kernel's table of processes, one slot each: process ID, state, page table, saved registers. xv6 has 64 slots.
- Trap table
- The address or table of addresses the CPU jumps to on a system call, fault or interrupt. On RISC-V the kernel writes it into stvec; on x86-64 it is the interrupt descriptor table.
- Timer interrupt
- A regular interrupt from a hardware timer that hands the CPU back to the kernel, even if the running program never asks.
- Scheduler
- The kernel loop that picks a RUNNABLE process and switches the CPU to it. In xv6, scheduler() never returns.
- init (process 1)
- The first process. On xv6 it runs /init, which starts the shell; on Linux it is usually /sbin/init. Every other process descends from it.
Notes and sources
- The card is xv6's main(), the small teaching kernel used in MIT 6.1810, cut to one line per part. Each line stands for one or two real calls (kvminit and kvminithart, for example), kept in their real order; the console is set up first and is not shown.
- Linux does the same jobs in start_kernel(), in a different order and with far more steps: setup_arch, trap_init, mm_core_init, sched_init, init_IRQ and time_init, and later rest_init() starts process 1, which runs /sbin/init.
- The figure draws four pages and three process-table slots. A real machine has many thousands of pages, and xv6 has 64 slots. The disk driver and other parts take pages from the list too; the drawing shows only the kernel page table and process 1.
- On a machine with several CPUs, xv6 builds everything on the first CPU; each other CPU only turns on paging, installs the trap vector and asks for interrupts, then joins the scheduler.
- xv6-riscv source: kernel/main.c (MIT 6.1810 teaching kernel)
- xv6-riscv source: kernel/kalloc.c (physical page allocator)
- xv6-riscv source: kernel/proc.c (process table, userinit, scheduler)
- xv6-riscv source: kernel/trap.c (trap vector and timer)
- xv6-riscv source: kernel/start.c (timer set up before main)
- xv6-riscv source: kernel/param.h (NPROC = 64)
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 6: Limited Direct Execution
- Berkeley CS162, Lecture 2: Four Fundamental OS Concepts
- Linux source: init/main.c (start_kernel, rest_init, kernel_init)
- Linux man-pages: bootparam(7)
- Linux kernel documentation: Explaining the "No working init found." boot hang message
Quiz Unlocks after the last step.