Virtualization & Containers

a VM-exit

When a guest is running under hardware-assisted virtualization, the CPU is humming along in guest mode executing the guest's own instructions directly. A VM-exit is the moment the hardware yanks that control back to the hypervisor because the guest just did something the hypervisor said it wanted to handle. The mirror-image operation, where the hypervisor hands control back into the guest to keep running, is a VM-entry. Together they are the heartbeat of a running virtual machine: enter the guest, let it run, exit on something interesting, fix it up, re-enter.

Mechanically, a VM-exit is like an extremely heavyweight trap. The CPU freezes the guest's exact state, saves its registers into the control structure (the VMCS on Intel), loads the hypervisor's saved state, and jumps to the hypervisor's handler - this is sometimes called a 'world switch' because the whole machine context flips from guest-world to host-world. The hypervisor then reads an 'exit reason' field to learn precisely WHY it exited: maybe the guest executed cpuid, or touched a control register, or accessed memory mapped to a virtual device, or an external interrupt arrived. It services that reason - emulating the device, injecting the interrupt, whatever - and finishes with a VM-entry that restores the guest exactly where it left off.

Why engineers obsess over this: a VM-exit is expensive, costing hundreds to a few thousand CPU cycles just for the context flip, before any actual work. So virtualization performance is, to a large extent, the art of reducing exits. That single fact explains a whole zoo of features: nested paging exists so that guest page-table updates do NOT exit; paravirtual drivers exist so that one batched exit replaces thousands of per-byte device exits; and posted interrupts exist so an interrupt can reach a guest without exiting. If you ever profile a slow virtual machine, counting and categorising its VM-exits is the first thing to do.

A guest runs the instruction cpuid to ask what CPU it is on. Because the hypervisor wants to present a controlled, consistent CPU identity to the guest, cpuid is configured to cause a VM-exit; the hypervisor fills in the answer it chooses, then does a VM-entry to resume the guest one instruction later.

cpuid triggers a VM-exit so the hypervisor can hand the guest a curated answer, then re-enters.

Each VM-exit costs real cycles for the context switch alone, so 'fast virtualization' largely means 'few exits.' A virtual machine that exits on every device byte or page-table write will crawl; batching and hardware features exist specifically to avoid that.

Also called
VM-entryVMEXITworld switch虛擬機退出 / 進入