ENع
←Hypervisors and VMs
Lesson 51 · I/O, virtualisation and isolation

Hypervisors and virtual machines

15 min11 steps5 questionsAdvanced
About this lesson

A virtual machine is a whole computer made of software: one real machine can run several operating systems at once, each sure it owns the hardware. The trick is a hypervisor that takes kernel mode for itself, moves every guest kernel down to user mode, and catches each privileged thing a guest tries. Follow one write() inside a VM as it bounces through the hypervisor, then see memory get one more map, the CPU switch between VMs, and why the original x86 could not play along. This builds on User mode and kernel mode and on Traps, exceptions and the interrupt table; the Hardware lesson on interrupts and I/O covers devices, and Containers and deployment compares VMs with containers.

You'll learn to

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

Fig 51 · Interactive
01 / 11

Machines inside a machine

A virtual machine (VM) is a software copy of a whole computer. A hypervisor, also called a virtual machine monitor, runs on the real hardware and shares it among VMs. Each VM runs its own operating system, the guest.

real hardware   one CPU, one memory, one screen
hypervisor      shares them out, like a kernel for kernels
VM 1, VM 2      each: a guest kernel + its programs

the goal: each guest believes it controls the machine
(OSTEP calls this transparency)
Loading figure…
or ← →
Read the lesson step by step
  1. Machines inside a machine

    A virtual machine (VM) is a software copy of a whole computer. A hypervisor, also called a virtual machine monitor, runs on the real hardware and shares it among VMs. Each VM runs its own operating system, the guest.

    real hardware   one CPU, one memory, one screen
    hypervisor      shares them out, like a kernel for kernels
    VM 1, VM 2      each: a guest kernel + its programs
    
    the goal: each guest believes it controls the machine
    (OSTEP calls this transparency)
  2. Only one boss in kernel mode

    Only the hypervisor runs in real kernel mode. Guest kernels are moved down to user mode, yet each assumes it is in kernel mode. The hypervisor keeps a virtual CPU for each guest, with a pretend mode bit.

    who            real CPU mode    what it believes
    hypervisor     kernel           (it knows the truth)
    guest kernel   user             kernel
    guest program  user             user
    
    vCPU = the guest's privileged CPU state, kept in memory:
      its mode, its trap table, its page table pointer, ...
  3. Plain work runs directly

    Line 1 is ordinary work, so it runs straight on the real CPU at full speed and stores 5. Neither the guest kernel nor the hypervisor is involved. This is limited direct execution, one level down.

    line 1   n = 2 + 3;
    runs on  the real CPU, real user mode
    traps    none
    memory   n = 5
    
    most guest instructions run like this, so plain
    computation in a VM runs at full speed
  4. The trap lands in the hypervisor

    Line 2 calls write(), which runs a trap instruction. The CPU switches to kernel mode and jumps through the real trap table. That table belongs to the hypervisor, not the guest kernel, so the hypervisor wakes up first.

    line 2   write(1, "hi\n", 3);
    trap     real mode user -> kernel
    lands    the hypervisor's trap handler
             (it installed the real trap table)
    vCPU 1   still user: the guest has not seen it yet
  5. Passing it to the guest kernel

    When the guest kernel booted, it tried to install its trap table. That is privileged, so it trapped, and the hypervisor wrote down the address. Now it sets vCPU 1's mode to kernel and jumps there, still in real user mode.

    earlier  guest kernel: set trap table   -> trapped
             hypervisor recorded: handler @ guest address
    now      vCPU 1 mode = kernel   (pretend)
             real mode   = user     (truth)
             jump to the guest kernel's write handler
  6. The device is emulated

    The guest kernel's driver writes the text hi to what it thinks is a screen. Device I/O is privileged, so this one output traps. The hypervisor checks it and shows the text on the real screen for the guest.

    guest driver   out "hi\n"        (one privileged I/O)
    trap           -> hypervisor   (one trap)
    hypervisor     emulates a common real device,
                   so the guest's normal driver works
    real screen    hi                (3 bytes)
    then           back to the guest kernel
  7. Return-from-trap traps too

    To go back, the guest kernel runs return-from-trap. That is privileged, so it bounces into the hypervisor, which sets vCPU 1's mode to user and does the real return. write() gives back 3 bytes written.

    guest kernel   return-from-trap (iret on x86)  -> traps
    hypervisor     vCPU 1 mode = user
                   real return-from-trap into the program
    result         write returns 3
    
    this one write() trapped into the hypervisor 3 times:
      the syscall, the device I/O and the return-from-trap
  8. Memory gets one more map

    n lives in the program's page 2. The guest's page table maps it to "physical" frame 3, but that is not real memory. The hypervisor keeps one more table per VM, mapping frame 3 to machine frame 6.

    level        table kept by        example (OSTEP Fig. B.4)
    virtual      (program's address)  page  2
    "physical"   guest kernel         page 2  -> frame 3
    machine      hypervisor           frame 3 -> machine 6
    
    the guest never sees machine addresses;
    the hypervisor can hand frames to any VM
  9. Switching between machines

    A timer interrupt hands the CPU to the hypervisor. It saves all of VM 1's state, registers and privileged state, then loads VM 2's and jumps back to where VM 2 stopped. This is a machine switch, a context switch one level down.

    timer interrupt   -> hypervisor (real kernel mode)
    save   VM 1: registers, PC, vCPU 1 (mode, trap table, ...)
    load   VM 2: registers, PC, vCPU 2
    jump   to VM 2's PC: here inside guest kernel 2
    
    like a process context switch, plus privileged state
  10. Two kinds of hypervisor

    A type 1 hypervisor runs directly on the hardware, like the one drawn here. A type 2 hypervisor runs as a program on a host operating system. Linux can be both: its KVM module makes the kernel itself a hypervisor.

    type 1   on the bare machine     e.g. Xen, VMware ESXi
    type 2   an app on a host OS     e.g. VirtualBox
    KVM      part of the Linux kernel; a program such as
             QEMU asks it for VMs with system calls:
    
    #define _POSIX_C_SOURCE 200809L
    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/ioctl.h>
    #include <unistd.h>
    #include <linux/kvm.h>
    
    int main(void) {
        int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC);
        if (kvm < 0) { perror("open /dev/kvm"); return 1; }
        int v = ioctl(kvm, KVM_GET_API_VERSION, 0);
        printf("KVM API version %d\n", v);   /* 12 */
        close(kvm);
        return 0;
    }
    
    prints   KVM API version 12   (on Linux with KVM)
  11. When trap and emulate works

    All of this needs every sensitive instruction to trap in user mode. The original x86 broke that rule: in user mode POPF silently skips the interrupt flag instead of trapping, so the hypervisor never sees it.

    guest kernel 2   popf   (tries to turn interrupts off)
    real CPU         user mode: IF unchanged, NO trap
    hypervisor       never told; guest is now wrong
    
    Pentium: 17 sensitive instructions that do not trap
    fixes: binary translation, para-virtualisation, VT-x
    
    trap and emulate as a Python simulation:
    
    PRIVILEGED = {"set_trap_table", "out", "iret"}
    vcpu = {"mode": "kernel", "trap_table": None}  # the guest's pretend CPU
    
    def hypervisor(op, arg):          # runs in real kernel mode
        if op == "syscall":           # pass it on to the guest kernel
            vcpu["mode"] = "kernel"
            return "jump to guest " + vcpu["trap_table"]
        if vcpu["mode"] == "user":
            return "fault: guest user code did " + op
        if op == "set_trap_table":    # remember, do not install
            vcpu["trap_table"] = arg
        if op == "out":               # emulate the device
            print("screen:", arg)
        if op == "iret":
            vcpu["mode"] = "user"
        return "emulated " + op
    
    def run(op, arg=None):            # the real CPU, in user mode
        if op in PRIVILEGED or op == "syscall":
            print(op, "traps:", hypervisor(op, arg))
        else:
            print(op, "runs directly")
    
    run("set_trap_table", "handler@0x80")  # guest kernel boots
    run("iret")                            # guest starts its program
    run("add")                             # line 1
    run("syscall")                         # line 2: write
    run("out", "hi")                       # guest driver
    run("iret")                            # back to the program
    
    prints:
    set_trap_table traps: emulated set_trap_table
    iret traps: emulated iret
    add runs directly
    syscall traps: jump to guest handler@0x80
    screen: hi
    out traps: emulated out
    iret traps: emulated iret

Quiz Unlocks after the last step.