ENع
←Kernel start-up
Lesson 05 · The kernel and system calls

What the kernel sets up before the first process

12 min11 steps5 questionsBeginner
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.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 5 · Interactive
01 / 11

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
Loading figure…
or ← →
Read the lesson step by step
  1. 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
  2. Line 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()
  3. 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 only
  4. Line 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 files
  5. Line 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 Linux
  6. Line 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()
  7. 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 too
  8. Line 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"
  9. 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 1
  10. Process 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;
    }
  11. 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

Quiz Unlocks after the last step.