ENع
←VT-x and nested paging
Lesson 52 · I/O, virtualisation and isolation

Hardware support for virtualisation: VT-x and nested page tables

15 min12 steps5 questionsAdvanced
About this lesson

A virtual machine runs a whole operating system as a guest, yet the hypervisor must stay in charge of the real CPU and memory. Early x86 made that hard, because some sensitive instructions did not trap. Intel VT-x fixed it with a new CPU mode for guests and controlled VM exits, and nested page tables (EPT) let the CPU translate guest memory by itself. Follow four real guest instructions to one VM exit and back, then one address through two page tables. Hypervisors and virtual machines sets up the idea of a hypervisor, and User mode and kernel mode covers the two CPU modes this lesson builds on.

You'll learn to

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

Fig 52 · Interactive
01 / 12

A kernel inside a kernel

A virtual machine runs a whole guest operating system. Its kernel expects kernel mode and full control of the CPU and memory. But the hypervisor, the software that runs virtual machines, must keep the real control.

guest kernel   thinks it owns the CPU, memory and devices
hypervisor     really owns them; shares them between guests

the wish:  guest code runs directly on the real CPU (fast)
           but every risky action reaches the hypervisor
Loading figure…
or ← →
Read the lesson step by step
  1. A kernel inside a kernel

    A virtual machine runs a whole guest operating system. Its kernel expects kernel mode and full control of the CPU and memory. But the hypervisor, the software that runs virtual machines, must keep the real control.

    guest kernel   thinks it owns the CPU, memory and devices
    hypervisor     really owns them; shares them between guests
    
    the wish:  guest code runs directly on the real CPU (fast)
               but every risky action reaches the hypervisor
  2. Old x86 broke the trick

    The classic trick: run the guest kernel in user mode, so privileged instructions trap to the hypervisor, which emulates them. Old x86 broke it: 17 sensitive instructions, such as POPF, misbehave or leak state in user mode without trapping.

    trap-and-emulate: guest kernel in user mode
      privileged instruction -> trap -> hypervisor emulates it
    
    POPF in user mode, trying to turn interrupts off:
      no exception, and the interrupt flag is not changed
      the hypervisor never hears about it
    
    Robin & Irvine (2000): 17 such Pentium instructions
    hypervisors had to rewrite guest code on the fly
  3. VT-x: root and non-root

    Intel VT-x adds a new pair of CPU modes. The hypervisor runs in root mode. Guests run in non-root mode, which has its own kernel and user levels, so the guest kernel truly runs in kernel mode.

    root mode       the hypervisor (host)
    non-root mode   the guest: its kernel and its programs
    
    in non-root mode the guest kernel may:
      run privileged instructions, change its page tables,
      take system calls from its own programs
    but chosen events force an exit to root mode
    
    AMD-V (SVM) is the same idea on AMD processors
  4. Fill the VMCS, then launch

    The hypervisor fills the VMCS, a control block in memory: the guest's instruction pointer and control registers, its own state, and which events must cause an exit, such as port I/O. VMLAUNCH then enters the guest, and the mode becomes non-root.

    VMCS (virtual machine control structure)
      guest state   ip, control registers (the VMM saves al, bl and other
                    general registers itself)
      host state    where the hypervisor resumes on an exit
      controls      exit on: port I/O, hlt, ...
    
    VMLAUNCH   root -> non-root, load the guest state
  5. Guest code at full speed

    In non-root mode the guest's instructions run directly on the real CPU, with no hypervisor in between. Registers al and bl both start at 2: the CPU adds them, then adds the code of the character '0', giving the character '4'.

    guest code (16-bit x86, from the LWN KVM example):
      1  mov $0x3f8, %dx
      2  add %bl, %al
      3  add $'0', %al
      4  out %al, (%dx)
      5  mov $'\n', %al
      6  out %al, (%dx)
      7  hlt
    
    line 1   dx = 0x3f8          runs directly
    line 2   al = 2 + 2 = 4         runs directly
    line 3   al = 4 + 0x30 = '4'    runs directly
  6. out: a VM exit

    Line 4 writes '4' to I/O port 0x3f8, a serial port. The VMCS says port I/O must exit, so the CPU saves the guest's state in the VMCS, switches to root mode and enters the hypervisor. Exit reason 30: I/O instruction.

    line 4   out %al, (%dx)      port 0x3f8 = COM1 serial port
    VM exit  save guest state in the VMCS
             load host state, mode non-root -> root
             exit reason 30  (EXIT_REASON_IO_INSTRUCTION)
             details: out, 1 byte, port 0x3f8
  7. The hypervisor plays the port

    On Linux, KVM is the hypervisor inside the kernel. Its KVM_RUN call returns to the VMM program with KVM_EXIT_IO: 1 byte out to port 0x3f8. The program acts as the serial port and prints 4 on the console.

    the VMM program's run loop (C, Linux KVM API):
    
    #include <stdio.h>
    #include <sys/ioctl.h>
    #include <linux/kvm.h>
    
    /* run: the vCPU's struct kvm_run, mapped with mmap() */
    int run_vcpu(int vcpu, struct kvm_run *run) {
        for (;;) {
            if (ioctl(vcpu, KVM_RUN, 0) < 0)   /* enter the guest */
                return -1;
            switch (run->exit_reason) {          /* why it exited */
            case KVM_EXIT_IO:
                if (run->io.direction == KVM_EXIT_IO_OUT &&
                    run->io.port == 0x3f8)
                    putchar(*((char *)run + run->io.data_offset));
                break;
            case KVM_EXIT_HLT:
                return 0;
            default:
                return -1;
            }
        }
    }
    
    console   4
  8. VM entry: carry on

    The program calls KVM_RUN again. The CPU reloads the guest's state from the VMCS, switches back to non-root mode and goes on just past the out instruction, where KVM moved it. To the guest, the write simply worked.

    KVM_RUN    VMRESUME: root -> non-root
               reload guest state, continue at line 5
    
    lines 5-6  print a newline: another exit, same path
    line 7     hlt: exit reason 12, KVM_EXIT_HLT, the loop ends
  9. Two page tables

    Memory needs the same care. The guest's own page table maps guest virtual to guest physical addresses, but guest physical is not real memory. A second table only the hypervisor controls, the EPT, maps guest physical to host physical.

    guest virtual   --guest page table-->  guest physical
    guest physical  --EPT--------------->  host physical
    
    guest page table   set by the guest kernel, no exit
    EPT                set by the hypervisor; the guest
                       cannot see or change it
    AMD calls it NPT; the general name is nested paging
  10. The CPU walks both

    The guest reads address 0x401234 and the TLB misses. The CPU finds page 0x401 in the guest's table: guest frame 0x2. Then it finds that frame in the EPT: host frame 0x7a3. The byte is at 0x7a3234. No exit.

    guest virtual    0x401234   page 0x401, offset 0x234
    guest page table page 0x401 -> frame 0x2
    guest physical   0x2234
    EPT              frame 0x2 -> host frame 0x7a3
    host physical    0x7a3234
    
    done by the CPU itself: the hypervisor does not run
    (a frame missing from the EPT would cause an exit:
     EPT violation, exit reason 48)
  11. Cache the whole answer

    The TLB keeps the whole result, page 0x401 to host frame 0x7a3, so the next read skips the walk. That matters: with 4 levels in each table, one full walk can take up to 24 memory reads instead of 4.

    TLB entry   guest page 0x401 -> host frame 0x7a3
    
    why a walk is costly (x86-64, 4 levels each):
      each guest table entry sits at a guest physical
      address, so it needs its own EPT walk first
      4 guest levels x (4 EPT + 1) + 4 EPT = 24 reads
      without virtualisation:                     4 reads
  12. Why hardware help?

    Before EPT, hypervisors kept shadow page tables and had to catch every change the guest made to its own. With VT-x and EPT, the guest runs its kernel and edits its page tables at full speed. The hypervisor steps in only on exits.

    the two lookups as a Python simulation:
    
    GUEST_PT = {0x401: 0x2}    # guest page -> guest frame (guest sets it)
    EPT      = {0x2: 0x7a3}    # guest frame -> host frame (hypervisor sets it)
    tlb = {}
    
    def read(gva):
        page, off = gva >> 12, gva & 0xfff
        if page not in tlb:              # TLB miss: walk both tables
            tlb[page] = EPT[GUEST_PT[page]]
        return tlb[page] << 12 | off     # host physical address
    
    print(hex(read(0x401234)))         # walk
    print(hex(read(0x401238)))         # TLB hit
    levels = 4
    print("worst-case walk:", levels * (levels + 1) + levels, "reads")
    
    prints:
    0x7a3234
    0x7a3238
    worst-case walk: 24 reads

Quiz Unlocks after the last step.