On this page
QEMU and KVM Collaboration
Coverage: QEMU-KVM process model → KVM_CREATE_VM/KVM_RUN → memory layout → vCPU thread loop → device emulation → live migration Kernel version: 2.6.20 ~ 6.x
Process Model
flowchart TD
QEMU["One VM = One QEMU Process"]
QEMU --> MAIN["🧵 Main Thread<br/>event loop, monitor"]
QEMU --> IO["🧵 IO Thread (iothread)<br/>handles virtio device IO"]
QEMU --> VCPU["🧵 vCPU Threads × N<br/>each executes KVM_RUN"]
QEMU --> MIGRATE["🧵 Migration Thread<br/>live migration"]
classDef root fill:#e3f2fd,stroke:#1565c0
classDef thread fill:#fff3e0,stroke:#ef6c00
class QEMU root
class MAIN,IO,VCPU,MIGRATE thread
VM Creation Flow
// QEMU → KVM:
kvm_fd = ;
// 1. Create VM
vm_fd = ;
// 2. Allocate guest RAM (managed by QEMU):
guest_ram = ;
// 3. Register with KVM:
struct kvm_userspace_memory_region region = ;
;
// 4. Create vCPU:
for
vCPU Execution Loop
// QEMU: kvm_cpu_exec() (accel/kvm/kvm-all.c)
int
IO Thread and virtio Handling
// QEMU iothread: independent event loop
// → epoll on eventfd (virtio kick)
// → QEMU handles virtio requests:
// virtio-blk: read/write → map to host file (qcow2/raw)
// virtio-net: tap fd → read/write Linux tun/tap
//
// vhost (bypassing QEMU):
// ioeventfd + irqfd → kernel handles directly
// → QEMU only configures, does not participate in the data path
Live Migration
QEMU + KVM Collaboration:
1. Source: Mark all guest RAM as read-only
→ Subsequent writes generate write faults → record dirty pages
2. Iterative copy: Pre-copy RAM to destination
3. Dirty page convergence: Dirty rate ↓ each round → until threshold
4. Stop-and-copy: Pause source VM → copy last dirty pages + register state → start destination
5. Downtime ~100ms (depends on workload)
References
- Source Code: QEMU
accel/kvm/kvm-all.c(KVM acceleration core), Linuxvirt/kvm/kvm_main.c - Kernel Documentation:
Documentation/virt/kvm/api.rst(ioctl API manual)
Keywords: KVM_RUN, kvm_run, ioctl, KVM_CREATE_VM, vCPU thread, iothread, live migration