Lesson 12 · Files, storage, I/O, and protection

Virtualization

Virtualization gives software a convincing copy of hardware it does not own. A hypervisor fakes a whole machine so a guest kernel can boot on it; a container instead splits up the one kernel already running.

Virtualization concept diagramA visual explanation of the layout and operations shown in this lesson.Type 1 — bare metalguest OSguest OShypervisorhardwareType 2 — hostedguest OShypervisorhost OShardwareContainersappappone shared kernelhardwarea VM virtualises hardware and boots its own kernel; a container only partitions the kernel already running
1

What Virtualization Means

Virtualization means giving software a virtual version of a resource that behaves like the real thing while the real one is shared underneath. Every OS already does this: virtual memory gives each process a private address space, and time-sharing gives it what looks like a private CPU.

A virtual machine extends the idea to a whole computer. The guest sees a CPU, memory, disks and network cards, and can boot an unmodified operating system on them. The hypervisor, also called a virtual machine monitor, keeps up the illusion and shares the real hardware among guests.

The reasons are consolidation (many lightly loaded servers on one machine), isolation (a crashed or hacked guest does not take down its neighbours) and portability (a VM is a set of files that can be snapshotted, copied and even moved between hosts while running). Cloud computing is built on all three.

The word covers two different techniques. Hardware-level virtualization fakes a machine so a guest kernel can run. OS level virtualization fakes nothing: it partitions the running kernel so groups of processes get isolated views of it. Most confusion about the topic comes from mixing the two up.

  • Virtual memory and time-sharing are already virtualization
  • A VM fakes a whole machine; a container partitions a kernel
  • Motives: consolidation, isolation, portability
2

How a Hypervisor Runs a Guest

  1. Run guest code directly on the CPU, with the guest kernel deprivileged
  2. Ordinary instructions execute natively at full speed
  3. A privileged instruction in the guest kernel traps to the hypervisor
  4. The hypervisor applies its effect to that guest's virtual CPU or memory
  5. The hypervisor resumes the guest at the next instruction

The classic technique is trap and emulate. Almost all guest code is harmless and runs directly, which is why VMs are fast. When the guest kernel tries something that touches real hardware state, such as loading a page table or disabling interrupts, the CPU traps because the guest is not truly privileged, and the hypervisor does the job on the guest's behalf.

Popek and Goldberg stated the condition in 1974: an architecture can be virtualized this way if every sensitive instruction, one that reads or changes privileged state, is also privileged, so it traps when a guest runs it.

x86 failed the test. Seventeen instructions, POPF among them, behaved differently in a deprivileged kernel without trapping, so the hypervisor never saw them. Two workarounds appeared. Binary translation (VMware) rewrote problem instructions in guest kernel code on the fly. Paravirtualization (Xen) changed the guest kernel's source to call the hypervisor directly through hypercalls. Then Intel VT-x (2005) and AMD-V (2006) added a hardware guest mode in which the hypervisor chooses which events exit to it, and EPT/NPT later added hardware support for the guest's second layer of page tables.

  • Rule: every sensitive instruction must trap
  • x86 broke it until VT-x and AMD-V
  • Binary translation needs no guest changes; paravirtualization does
3

Type 1 vs Type 2 Hypervisor

The split between Type 1 and Type 2 hypervisors is about what sits underneath. A Type 1 hypervisor is the first thing that boots and owns the hardware, which keeps overhead and the trusted code base small. Data centres and clouds run this kind.

A Type 2 hypervisor is an application on an ordinary OS, convenient on a laptop because the machine stays usable as a normal computer. Its guests pay for the extra layer on I/O and inherit the host's weaknesses.

KVM blurs the line: it is a Linux kernel module that turns Linux itself into the hypervisor, with QEMU in user space supplying the virtual devices. It is usually counted as Type 1.

The two hypervisor types
Type 1 (bare metal)Type 2 (hosted)
Runs onThe hardware directlyA host operating system
Guest I/O passes throughThe hypervisorThe host OS and the hypervisor
OverheadLowHigher: an extra layer
Trusted code underneath guestsSmallA whole host OS
ExamplesESXi, Xen, Hyper-VVirtualBox, VMware Workstation
  • Type 1: on bare metal, used in data centres
  • Type 2: an app on a desktop OS
  • KVM turns the Linux kernel into the hypervisor
Key reference

Terms, operations, and practical uses

Hypervisors

  • Type 1On bare metal: ESXi, Xen, Hyper-V. Small trusted base.
  • Type 2On a host OS: VirtualBox, VMware Workstation.
  • KVMTurns the Linux kernel into the hypervisor.

Making x86 work

  • Popek and GoldbergSensitive instructions must be privileged, so they trap.
  • Binary translationRewrite problem guest kernel instructions on the fly.
  • ParavirtualizationModify the guest to make hypercalls instead.
  • VT-x / EPTHardware guest mode and two-level page tables.

Containers

  • NamespacesLimit what a process can see: mounts, PIDs, network, users.
  • cgroupsLimit what it can use: CPU, memory, I/O.
  • Shared kernelMillisecond starts; a kernel bug exposes every container.
  • MicroVMsFirecracker: VM isolation with a minimal device model.
Implementation

Trap and emulate, then containers

VM_BOOT_MS, CONTAINER_START_MS = 2400, 40

class Hypervisor:
    """Type 1: each guest boots its own kernel on virtual hardware."""
    def __init__(self):
        self.kernels = 0
    def launch(self, n):
        self.kernels += n              # every guest brings a kernel
        return n * VM_BOOT_MS

class Kernel:
    """OS-level: one kernel, partitioned by namespaces and cgroups."""
    def __init__(self):
        self.kernels = 1               # the one already running
    def launch(self, n):
        return n * CONTAINER_START_MS  # nothing boots -- just restricted views

vm, host = Hypervisor(), Kernel()
vm.launch(3)
host.launch(3)

print(f"VM boot {VM_BOOT_MS}ms x3 = {vm.kernels} kernels "
      f"| container {CONTAINER_START_MS}ms x3 = {host.kernels} kernel shared")
#include <iostream>
using namespace std;

const int VM_BOOT_MS = 2400, CONTAINER_START_MS = 40;

struct Hypervisor {          // Type 1: each guest boots its own kernel
    int kernels = 0;
    int launch(int n) { kernels += n; return n * VM_BOOT_MS; }
};

struct Kernel {              // OS-level: one kernel, partitioned
    int kernels = 1;         // the one already running
    int launch(int n) { return n * CONTAINER_START_MS; }   // nothing boots
};

int main() {
    Hypervisor vm;
    Kernel host;
    vm.launch(3);
    host.launch(3);

    cout << "VM boot " << VM_BOOT_MS << "ms x3 = " << vm.kernels
         << " kernels | container " << CONTAINER_START_MS << "ms x3 = "
         << host.kernels << " kernel shared\n";
}
class Main {
    static final int VM_BOOT_MS = 2400, CONTAINER_START_MS = 40;

    static class Hypervisor {        // Type 1: each guest boots its own kernel
        int kernels = 0;
        int launch(int n) { kernels += n; return n * VM_BOOT_MS; }
    }

    static class Kernel {            // OS-level: one kernel, partitioned
        int kernels = 1;             // the one already running
        int launch(int n) { return n * CONTAINER_START_MS; }   // nothing boots
    }

    public static void main(String[] args) {
        Hypervisor vm = new Hypervisor();
        Kernel host = new Kernel();
        vm.launch(3);
        host.launch(3);

        System.out.println("VM boot " + VM_BOOT_MS + "ms x3 = " + vm.kernels
            + " kernels | container " + CONTAINER_START_MS + "ms x3 = "
            + host.kernels + " kernel shared");
    }
}
Watch it run

Step through it

Running on two guests on a Type 1 hypervisor; two containers on one kernel

Type 1 hypervisor, two guestsguest A: appuser modeguest A: kernelruns deprivilegedguest B: appuser modeguest B: kernelruns deprivilegedhypervisor (Type 1)the only code with full privilegehardware: CPU, memory, deviceswhat the hypervisor keeps per guestguest A virtual CR30x2000guest A interruptsonguest B virtual CR30x7000guest kernels think they own the CPU
Step 1

Two guests share one machine

Each guest has an app and its own kernel, and each kernel believes it controls the hardware. Only the hypervisor really does. The guest kernels are run with reduced privilege so that anything touching real hardware state has to go through the hypervisor.

Output
1 / 12
4

Containers vs Virtual Machines

With OS level virtualization there is one kernel. A container is a group of ordinary processes that the kernel shows a private view of the system. On Linux this comes from two existing features. Namespaces limit what a process can see: its own mount tree, process IDs, network interfaces and hostname, so the first process inside sees itself as PID 1. cgroups limit what it can use: CPU share, memory, I/O.

That makes containers cheap. Nothing boots, instructions run natively with no traps, and images hold only the app and its libraries. The trade is the shared kernel: a kernel bug reachable from one container is a way out to the host and to every other container. Containers also cannot run a different kernel, which is why Docker on macOS and Windows runs a small Linux VM underneath.

So the choice between containers and virtual machines is mostly a choice of boundary. Untrusted tenants, different kernels or strict separation call for VMs; many copies of your own services call for containers. Production systems usually layer both, running containers inside VMs. Firecracker microVMs (behind AWS Lambda) and gVisor, which intercepts a container's system calls in user space, narrow the gap from each side.

What each one isolates and what it costs
Virtual machineContainer
VirtualizesHardwareThe operating system
KernelsOne per guestThe host's, shared
Start timeSeconds: a full bootMilliseconds: nothing boots
Image sizeGigabytesMegabytes
BoundaryVirtual hardware and the hypervisorKernel namespaces
A kernel exploit reachesOne guestThe host and every container
Different OS kernelYesNo
  • Namespaces hide; cgroups limit
  • Containers: fast and dense, but one shared kernel
  • Untrusted code goes in a VM, often with containers inside