CPU series, post 4 of 5
A vCPU is a thread. The host schedules it like any other thread, and it can lose the core at any moment.
Hold that sentence against one measurement. In 2024, Netflix engineers published a write-up on noisy-neighbor detection built on run-queue latency, the time a runnable task waits for a CPU. One container’s P99 run-queue latency averaged 83 microseconds, with spikes to 400. Then a neighboring container that saturated every CPU launched. P99 jumped to 131 milliseconds. That is more than 1,500 times the average. No code changed.
That was containers sharing one kernel. Virtual machines hit the same wall one level up, and the mechanism is the scheduler from Post 2. This post shows the loop that makes a vCPU a thread, a model of what two stacked schedulers do to a spinlock, and a real cgroup experiment that separates weight from quota.
A hypervisor is a mode switch and a scheduler
What is a hypervisor, mechanically? Software that lets several operating systems share one machine while each believes it owns the hardware. The CPU helps. Intel VT-x adds a mode split, VMX root for the hypervisor and non-root for the guest, and AMD-V does the same with different names. The guest runs natively in non-root mode, at full speed, until something forces a VM exit: certain I/O, a fault in the nested page tables, a HLT instruction, an external interrupt. The CPU hands control back to the hypervisor, which handles the event and re-enters the guest. Intel SDM Volume 3C and AMD APM Volume 2 hold the details.
Textbooks split hypervisors into type 1, on bare metal, and type 2, hosted. KVM blurs the line. The Linux kernel is the hypervisor and also a general-purpose OS. The label matters less than the scheduling question: who decides which vCPU runs?
KVM is the kernel half. It is a module that exposes /dev/kvm. You create a VM and then a vCPU, each a file descriptor, and run the vCPU by calling the KVM_RUN ioctl. QEMU is the userspace half, and each vCPU in QEMU is a regular host thread looping around that ioctl. The call enters the guest, and it returns when an exit needs userspace, such as emulated device I/O (KVM API documentation). The skeleton of that loop fits on one screen.
// vcpu_loop.c: the shape of every KVM vCPU thread. A skeleton: it compiles, but it is not a complete VMM.
#include <linux/kvm.h>
#include <stddef.h>
#include <sys/ioctl.h>
struct vcpu {
int fd; // from ioctl(vm_fd, KVM_CREATE_VCPU, id)
struct kvm_run *run; // mmap of that fd: the kernel writes the exit reason here
};
void handle_port_io(struct vcpu *v); // emulated devices live in userspace
void handle_mmio(struct vcpu *v);
void *vcpu_thread(void *arg) {
struct vcpu *v = arg;
for (;;) {
ioctl(v->fd, KVM_RUN, 0); // enter the guest; return on an exit that userspace must handle
switch (v->run->exit_reason) {
case KVM_EXIT_IO: handle_port_io(v); break;
case KVM_EXIT_MMIO: handle_mmio(v); break;
case KVM_EXIT_HLT: break; // the guest has nothing to run
case KVM_EXIT_INTR: break; // a host signal ended the run; loop and enter again
default: return NULL; // shutdown, internal error, and so on
}
}
}
This is a skeleton, and I did not run it. The VM I test on has no /dev/kvm, so all I could do was compile-check it with gcc -fsyntax-only. There is no output block for it on purpose. For a complete program that creates a VM, loads a few bytes of machine code and runs it, read Josh Triplett’s Using the KVM API on LWN, which walks through a working sample and its KVM_RUN loop.
Read the loop for what it implies. The ioctl is the guest running. While it is blocked inside the kernel, the guest owns a CPU. When it returns, the thread is ordinary userspace code. The API requires vCPU ioctls to come from the thread that created the vCPU, which is why one vCPU is one host thread. There is no separate hypervisor scheduler. Linux is the hypervisor, and its scheduler decides which vCPU runs. Do not stretch that to ESXi or Hyper-V, which have schedulers of their own.

The scheduler of schedulers
Two schedulers now stack. Inside the guest, an ordinary OS scheduler, exactly the one from Posts 1 and 2, picks which guest thread runs on each vCPU. Outside, the host scheduler, EEVDF on Linux 6.6 and later, picks which vCPU thread runs on which physical CPU. The guest believes it owns a core. The host can take that core away between any two guest instructions. Even the guest’s timer interrupt, the mechanism that gave the guest kernel control in Post 1, is virtual. If the vCPU is descheduled when the timer should fire, the guest sees it late.
Post 1 ended on a measurement that fits here. My detector counted about 2,700 gaps per second on a CPU where the guest kernel logged 252 timer interrupts per second, and the guest’s own counters explained under a tenth of the gaps. The rest came from below the guest kernel, and I could not see what. This post is why a host scheduler is a plausible answer. I did not isolate the cause on this machine, so call it a likely explanation, not a result.
Can the guest tell? Yes, if the host helps. KVM can publish steal time to the guest: how long this vCPU was ready to run and did not. It shows up as st in top and vmstat and in /proc/stat. Red Hat’s definition is the clearest I know: CPU time the guest needed and the host did not provide. ESXi reports the same symptom as CPU Ready, measured by the hypervisor. Related, not identical. The guest sees steal. The hypervisor sees ready.
How many vCPUs is too many?
More is not faster. Red Hat’s RHEL 9 guidance says the safe ratio is typically 5 vCPUs to 1 physical CPU for loads under 100%, tells you to give a guest only the vCPUs it needs, and warns against overcommitting production without testing. The RHEL 7 guide is blunter. Overcommitting SMP guests beyond physical cores causes significant performance degradation. Tsuna’s 2010 estimate, one to handle with care, put context switches at 2.5 to 3 times more expensive under virtualization.
Why do wide guests degrade? Lock-holder preemption. Inside the guest, vCPU 2 takes a kernel spinlock. The host preempts vCPU 2, because the host does not know what the guest holds. vCPUs 0, 1 and 3 now spin on a lock whose owner is not running, burning real host CPU time on nothing. The one thread that can release the lock waits for its turn behind the threads wasting it.
Linux has two mitigations. Paravirtual spinlocks let a waiter yield to the host instead of spinning. Pause-loop exiting on Intel hardware, and pause filtering on AMD, lets the CPU detect a spin loop and exit so the host can run something else. The model below builds both ideas in about 50 lines. Each VM has four vCPUs. The host runs a first-in-first-out queue with a 3 millisecond slice on four physical CPUs, so adding VMs raises the vCPU to pCPU ratio. Every vCPU alternates between computing and taking its VM’s one spinlock. The second set of columns lets a spinner exit after a short spin and hands the core to the lock holder. This is a model of the mechanism, not a KVM measurement, and it has no cache effects, no wakeups and one lock.
# two_level.py: a guest spinlock meets host preemption. A model of the mechanism, not a KVM measurement.
import random
from collections import deque
QUANTUM, TOTAL = 300, 100_000 # one step is 10 us: a 3 ms host slice, 1 s of simulated time
def simulate(n_vms, work, hold, vcpus=4, pcpus=4, yield_after=None):
random.seed(1)
n = n_vms * vcpus
state, rem = ["C"] * n, [work] * n # C: compute, W: wait for the lock, H: hold the lock
age, ran, spin, spun, ops = [None] * n, [0] * n, [0] * n, [0] * n, [0] * n_vms
lock = [None] * n_vms
running, queue = [], deque(range(n))
for _ in range(TOTAL):
for v in list(running): # host: slice expired, back of the queue
if age[v] >= QUANTUM:
running.remove(v); queue.append(v)
while len(running) < pcpus and queue: # host: fill free pCPUs, first in first out
v = queue.popleft(); running.append(v)
age[v] = random.randrange(QUANTUM) if age[v] is None else 0 # stagger the first slices
for v in list(running): # guest: one step on every running vCPU
age[v] += 1; ran[v] += 1; vm = v // vcpus
if state[v] == "C":
rem[v] -= 1
if rem[v] == 0: state[v] = "W"
elif state[v] == "W":
if lock[vm] is None:
lock[vm], state[v], rem[v] = v, "H", hold
else: # spin on a lock whose holder may not be running
spin[v] += 1; spun[v] += 1
if yield_after and spun[v] >= yield_after: # pause-loop exit: give the core back
spun[v] = 0
running.remove(v); queue.append(v)
h = lock[vm]
if h in queue: # directed yield: run the lock holder next
queue.remove(h); queue.appendleft(h)
else:
rem[v] -= 1
if rem[v] == 0:
lock[vm], state[v], rem[v] = None, "C", work
ops[vm] += 1; spun[v] = 0
steal = 100 * (1 - sum(ran) / (n * TOTAL))
return steal, 100 * sum(spin) / sum(ran), sum(ops) / n_vms
for work, hold in ((100, 5), (60, 10)):
base = simulate(1, work, hold)[2]
print(f"\nlock held {hold * 10} us after every {work * 10} us of work. 4 vCPUs per VM, 4 pCPUs.")
print("'work' is lock acquisitions per VM, as a percent of the same VM at 1:1.")
print(f"{'vCPU:pCPU':>9} {'fair share':>10} | {'steal':>6} {'spin':>6} {'work':>6} | {'spin':>6} {'work':>6}")
print(f"{'':>9} {'':>10} | {'no mitigation':^20} | {'directed yield':^13}")
for vms in (1, 2, 4, 8):
st, sp, ops = simulate(vms, work, hold)
_, sp2, ops2 = simulate(vms, work, hold, yield_after=4)
print(f"{vms:>7}:1 {100 / vms:9.1f}% | {st:5.1f}% {sp:5.1f}% {100 * ops / base:5.1f}% | {sp2:5.1f}% {100 * ops2 / base:5.1f}%")
lock held 50 us after every 1000 us of work. 4 vCPUs per VM, 4 pCPUs.
'work' is lock acquisitions per VM, as a percent of the same VM at 1:1.
vCPU:pCPU fair share | steal spin work | spin work
| no mitigation | directed yield
1:1 100.0% | 0.0% 0.0% 100.0% | 0.0% 100.0%
2:1 50.0% | 50.0% 2.6% 48.7% | 0.0% 49.9%
4:1 25.0% | 75.0% 2.9% 24.2% | 0.0% 24.9%
8:1 12.5% | 87.5% 3.0% 12.1% | 0.1% 12.4%
lock held 100 us after every 600 us of work. 4 vCPUs per VM, 4 pCPUs.
'work' is lock acquisitions per VM, as a percent of the same VM at 1:1.
vCPU:pCPU fair share | steal spin work | spin work
| no mitigation | directed yield
1:1 100.0% | 0.0% 0.0% 100.0% | 0.0% 100.0%
2:1 50.0% | 50.0% 18.8% 40.6% | 0.4% 49.8%
4:1 25.0% | 75.0% 14.4% 21.4% | 0.2% 24.9%
8:1 12.5% | 87.5% 13.6% 10.8% | 0.3% 12.4%
One thing holds in both regimes. Steal is 50%, 75% and 87.5% at 2:1, 4:1 and 8:1, which is arithmetic, not a finding: if eight times as many vCPUs share a core, each gets one eighth of it. The question is what the VM does with the share it keeps. The “work” column is lock acquisitions relative to the same VM alone, and the fair-share column is the ceiling.
With a lock held 50 microseconds per 1,000 of work, the cost is small. Spinning wastes 2.6% to 3.0% of running time and work lands within 1.3 points of fair share, 48.7% against 50%. Lock-holder preemption needs contention to hurt. Raise the load to 100 microseconds per 600 and it shows. At 2:1 the VM spends 18.8% of its running time spinning, and it completes 40.6% of its solo work instead of 50%. At 4:1 it gets 21.4% against 25%. At 8:1, 10.8% against 12.5%. The share it keeps is not all useful.
With directed yield, spinning falls below half a percent and work recovers to 49.8%, 24.9% and 12.4%, within a point of fair share. So the mitigation works, in the model. It does not create CPU. It stops the host from paying for waiting. Two honest limits: the result depends on how much time the lock is held, which is why both regimes are printed, and a real hypervisor’s yield heuristics are far less exact than a toy that knows who holds the lock.
So wide guests dilute. A 16-vCPU VM on a busy host is not 16 cores. It is 16 threads, and each one waits for its turn.
Where does a vCPU run, by default? Anywhere. The host scheduler can move it between cores, and every move abandons some cache state. Pin it and it stays put. Pinning has a price, which comes next.
Slicing versus partitioning
Slicing shares cores in time. Partitioning hands cores to someone. Linux gives you one knob for each idea, plus a third in between.
| Control | cgroup v2 | libvirt | Promises | Does not promise |
|---|---|---|---|---|
| Weight | cpu.weight |
<shares> |
A proportional share under contention | Anything in absolute terms |
| Quota | cpu.max, format “$MAX $PERIOD”, default “max 100000” |
<quota>, <period> |
A hard cap | A reservation; it throttles even when cores are idle |
| Partition | cpuset.cpus, cpuset.mems |
<vcpupin> |
Use of specific cores only | Exclusivity, unless you keep everything else off those cores |
Do not take the table on trust. The script below puts two busy loops in two cgroups on one CPU with shares in a 1:3 ratio. Then it puts one loop alone on an otherwise idle CPU with a quota of 20 milliseconds per 100. This VM exposes cgroup v1, so the knobs are cpu.shares, cfs_quota_us and cfs_period_us. In cgroup v2 they become cpu.weight and cpu.max, and the behavior is the same.
# cgroup_demo.py: weight shares CPU only under contention; a quota caps it even when the CPU is idle.
# This VM exposes cgroup v1. In cgroup v2: cpu.shares becomes cpu.weight, cfs_quota_us and cfs_period_us become cpu.max.
import os, subprocess, time
CPU = "/sys/fs/cgroup/cpu"
def make(name, **knobs):
d = f"{CPU}/{name}"
os.makedirs(d, exist_ok=True)
for k, v in knobs.items():
open(f"{d}/{k}", "w").write(str(v))
return d
def spin(group, cpu): # a busy loop pinned to one CPU, moved into the cgroup
p = subprocess.Popen(["taskset", "-c", str(cpu), "python3", "-c", "while True: pass"])
open(f"{group}/tasks", "w").write(str(p.pid))
return p
def run_ns(p): # CPU time the scheduler has given this process
return int(open(f"/proc/{p.pid}/schedstat").read().split()[0])
def measure(procs, seconds):
before = [run_ns(p) for p in procs]
time.sleep(seconds)
return [(run_ns(p) - b) / 1e9 for p, b in zip(procs, before)]
def stop(procs, groups):
for p in procs:
p.kill(); p.wait()
for g in groups:
os.rmdir(g)
lo = make("demo_lo", **{"cpu.shares": 1024})
hi = make("demo_hi", **{"cpu.shares": 3072})
a, b = spin(lo, 0), spin(hi, 0)
ta, tb = measure([a, b], 3)
print(f"weight 1:3, both on CPU 0, 3 s: lo got {ta:.2f} s ({100 * ta / (ta + tb):.0f}%), hi got {tb:.2f} s ({100 * tb / (ta + tb):.0f}%)")
stop([a, b], [lo, hi])
cap = make("demo_cap", **{"cpu.cfs_period_us": 100000, "cpu.cfs_quota_us": 20000})
c = spin(cap, 1)
(tc,) = measure([c], 3)
stat = dict(line.split() for line in open(f"{cap}/cpu.stat"))
print(f"quota 20 ms per 100 ms, CPU 1 otherwise idle, 3 s: ran {tc:.2f} s ({100 * tc / 3:.0f}%), "
f"throttled in {stat['nr_throttled']} of {stat['nr_periods']} periods")
stop([c], [cap])
weight 1:3, both on CPU 0, 3 s: lo got 0.75 s (25%), hi got 2.24 s (75%)
quota 20 ms per 100 ms, CPU 1 otherwise idle, 3 s: ran 0.62 s (21%), throttled in 30 of 30 periods
Weight divided one CPU 25% to 75%, exactly the ratio of the shares, and it only did so because two tasks were contending. Quota is the surprise. The loop had a whole CPU to itself and got 21%. It was throttled in all 30 of the 30 periods in three seconds. The 20 milliseconds ran out early in each 100 millisecond period, and the group waited for the next one while the core sat idle. That is the difference in one run: weight allocates what is scarce, and quota restricts even what is not.

The default quota period is 100,000 microseconds, which is 100 milliseconds. The kernel documents the throttling counters in cpu.stat (CFS bandwidth control), and the script read them. Netflix’s write-up makes the same point from the other side. Hitting a CPU limit throttles a task in a way that looks exactly like run-queue latency. A cap and a noisy neighbor produce the same symptom and need opposite cures.
The misconception to kill: CPU limits do not reserve CPU. Only partitioning dedicates cores, and only if you keep the rest of the system off them.
A VM is also more than its vCPU threads. QEMU’s emulator thread, its IOThreads and any vhost threads do host-side work for the guest, and they compete with the vCPUs for the same cores. libvirt gives you <emulatorpin> and <iothreadpin> to keep them elsewhere. AHV is built on KVM, so these mechanisms apply there directly.
Read these, not my commands
Start with Brendan Gregg’s Linux Performance Analysis in 60,000 Milliseconds for vmstat 1 and mpstat -P ALL 1, including what the st column means. Then read the libvirt domain XML reference for <cputune>, and the kernel’s cgroup v2 guide for the weight, quota and cpuset files. They will teach the syntax better than I would, and they stay current.
What to carry forward
A vCPU is a thread. Two schedulers stack, and the lower one owns the clock. The guest can read its losses as steal time, but only the host can cure them. Which core a vCPU lands on matters as much as when it runs. Post 5 is about where.
Takeaways
- KVM makes each vCPU a host thread that enters the guest through
KVM_RUN. - Two schedulers stack: guest threads onto vCPUs, then vCPUs onto physical CPUs.
- Steal time (
st) is the guest’s evidence of host contention, and CPU Ready is the hypervisor’s view of the same thing. - Size vCPUs to the work; Red Hat’s typical ceiling is 5:1 for loads under 100%, and you still test.
- Weight shares, quota caps, and only pinning partitions; in the demo a quota throttled an idle CPU to 21%.
- Pin emulator and I/O threads away from vCPU threads.
Published November 22, 2026