Both layers between your training code and a cloud GPU get out of the way on the hot path: guest code runs directly on the CPU and a CUDA launch is a few stores into mapped memory plus a doorbell, so you pay only at the boundaries: a VM exit (about 0.92 µs here) each time the guest touches what the hypervisor must see, and a system call into the driver at start-up, allocation and errors.
Fig. 1: two stacks, one rule: the hot path never asks permission
libcuda, the kernel driver nvidia.ko, the GSP firmware, the GPU.libcuda writes the launch into memory the GPU can read and stores a token into the mapped doorbell register; the GPU fetches the work by DMA. No system call, and no exit even in a VM (section 9).ioctl, which on Turing and later GPUs forwards the work by RPC to the resource manager running as firmware on the GPU (section 9).You need: limited direct execution, system calls and the cost of a context switch from the root Topic: operating-systems (section 9 there is this page's intuition); page tables and the TLB from Virtual memory; namespaces, cgroups and the device controller from Containers and isolation. CUDA programming is Topic: cuda-and-gpu-programming's; the GPU as silicon is Topic: hardware's; MIG as a cluster scheduling unit is Kubernetes for ML's.
libcuda.so.1, installed with the host's driver; the kernel driver is nvidia.ko.| Mechanism | What it costs here | When it bites in ML | Command that shows it |
|---|---|---|---|
| VM exit | measured 0.92 µs per exit on this laptop's hypervisor | anything that traps often: interrupts, device registers, idle | on a KVM host: perf kvm stat |
| Cross-CPU wake-up in a VM | measured 25.3 µs, against 2.00 µs on one CPU | data-loader hand-offs, thread pools, NCCL proxy threads | grep IPI /proc/interrupts |
| Nested page walk | derived up to 24 memory reads per TLB miss, against 4 | large, random memory access in a VM | perf stat -e dTLB-load-misses |
| virtio disk and network | measured 1 interrupt per request at queue depth 1, 0.11 at 32 | data loading inside a VM | grep virtio /proc/interrupts |
| IOMMU and passthrough | not run here: no IOMMU in this VM | every cloud GPU VM; GPU peer-to-peer and RDMA | ls /sys/kernel/iommu_groups |
| Sharing one GPU | source isolation differs completely | inference and notebooks on shared GPUs | nvidia-smi mig -lgi |
| First CUDA call against the millionth | measured the search for a driver, call by call; source launches need no system call | slow start-up, "no CUDA-capable device" | strace -f -e trace=openat,ioctl |
| Driver against runtime version | measured errors 35, 34 and 100 reproduced | a new image on an old host | nvidia-smi, torch.version.cuda |
Linux runs: Docker Desktop's Linux VM on an Apple M1 Pro (Linux 5.10.104-linuxkit, arm64, 5 virtual CPUs, about 10 GB), October 2026, images kb-os-lab:1 (the root's lab image) and kb-os-virt:1 (the CUDA topic's kb-gpu-lab:1: CUDA 13.4.2 toolkit for arm64, plus strace). Containers were not privileged; strace needed --cap-add SYS_PTRACE, and one CUDA case used --device-cgroup-rule 'c 195:* rwm', both stated where used. macOS runs, labelled as contrasts: the hypervisor process that runs the VM, and a tiny VM of our own built on Apple's Hypervisor.framework. There is no GPU here: everything above the kernel driver was run for real; the kernel driver and the GPU are taught from NVIDIA's open source and documentation and tagged not run here. Labels: measured ran here; source read from source or documentation. Timings on a shared laptop VM vary from run to run, so each is a median of three runs and the raw files show the spread. Scripts and raw outputs: src/exp/ and src/raw/ in the repository. The root page, section 9, gave the intuition in one screen; this page goes down to the code: the Linux kernel at the version that ran here (v5.10) and a current one (v6.12), QEMU with Apple's Hypervisor.framework, NVIDIA's open kernel modules at 615.71.09, and the CUDA 13.4 runtime and user-mode driver run for real in a container with no GPU.
| OSTEP | Here | What this page adds |
|---|---|---|
| Appendix B, Virtual Machine Monitors | 1 to 4 | hardware virtualization (EL2, VMX), KVM's API, VM exits measured, nested paging, the information gap measured as a slow wake-up |
| 6 Limited Direct Execution | 1, 2 | the same idea one level down: the guest kernel runs directly, the hypervisor keeps control through traps |
| 19 TLBs, 20 Advanced Page Tables | 4 | two-dimensional page walks, VMIDs, huge pages in both stages |
| 36 I/O Devices | 6, 7, 9 | virtqueues, DMA and the IOMMU, doorbells and command buffers on a GPU |
| 26 to 28 Concurrency, Locks | 5 | why a sleeping lock's wake-up is dearer in a VM |
OSTEP is free at pages.cs.wisc.edu/~remzi/OSTEP; Appendix B is vmm-intro.pdf. Read it alongside sections 1 to 4 here.
The problem. A cloud provider sells slices of one big machine to strangers. Each wants root, their own kernel and drivers, and the certainty that the neighbour cannot read their memory or crash their kernel. A container cannot promise that: every container shares one kernel, so a kernel bug is everyone's bug. A virtual machine (VM) gives each customer a whole kernel of their own; the hypervisor (or virtual machine monitor, VMM) does for operating systems what an operating system does for processes.
How it works: limited direct execution, one level down. A kernel runs your program directly on the CPU and takes control back only on a system call, fault or timer (OSTEP chapter 6). A hypervisor does the same to a whole kernel: the guest kernel's instructions run directly, at full speed, and the hypervisor takes over only when the guest does something it must not do alone, such as touch a device or reprogram the interrupt controller. That hand-over is a trap; in a VM it is a VM exit. OSTEP's appendix calls it extending "the notion of limited direct execution" so the VMM can "interpose on key events (such as traps)" (OSTEP Appendix B).
| arm64 (this laptop) | Runs | x86-64 equivalent |
|---|---|---|
| EL0 | your process (Python, the training job) | ring 3 |
| EL1 | the (guest) kernel | ring 0, VMX non-root mode |
| EL2 | the hypervisor (KVM's core, Apple's Hypervisor.framework) | VMX root mode (Intel VT-x), or SVM host mode (AMD-V) |
| EL3 | firmware (secure monitor) | SMM, roughly |
Which instructions must trap. Popek and Goldberg (1974, Theorem 1, paraphrased): a VMM can be built if every sensitive instruction (one that reads or changes the machine's control state) is also privileged (traps outside the most privileged mode). Then the deprivileged guest kernel traps on every sensitive act and the hypervisor emulates it: trap and emulate. x86 broke the rule: Robin and Irvine "found that seventeen instructions violate" it, for example POPF, which in user mode silently ignores a change to the interrupt flag instead of trapping. Three answers followed:
Who is the hypervisor? Type 1 (bare metal): the hypervisor is what boots (Xen, VMware ESXi). Type 2 (hosted): a program on an ordinary OS; here, QEMU on macOS asking the macOS kernel, through Hypervisor.framework, to enter the guest. Linux's KVM blurs the two: a kernel module turns Linux into the hypervisor, and a user-space program (QEMU, Firecracker, cloud-hypervisor) provides the virtual devices. AWS's Nitro System uses "a custom-developed, minimized hypervisor based on KVM" with device work moved onto dedicated cards (AWS Nitro whitepaper).
Popek and Goldberg: CACM 1974. Robin and Irvine examined the Pentium's instruction set in 2000 (USENIX Security 2000); besides POPF, SGDT/SIDT reveal where the real descriptor tables are. A guest kernel that executes POPF thinking it disabled interrupts would be wrong, and the hypervisor would never know. Binary translation scans the guest kernel's code before it runs and rewrites the problem instructions into safe sequences. On paravirtualization OSTEP says such a system "can be made to be nearly as efficient a system without a VMM".
getpid() system calls, or a million 4 KiB disk reads?Containers: one kernel, separated by namespaces and cgroups (the Containers and isolation page owns how). VMs: one kernel per guest, separated by the CPU's virtualization hardware, so a guest kernel crash or exploit stays in its guest. The price is the boundary crossings of sections 2 to 6. Sandboxes for untrusted code (Firecracker, gVisor) sit between the two and are on the containers page.
What an exit is. When the guest does something the hypervisor asked to see, the CPU stops the guest, saves its registers, switches to the hypervisor's privilege level and jumps to its handler with a syndrome saying why (on arm64 the exception class, EC; on x86 the exit reason). The handler emulates the effect and resumes the guest. Everything a guest does is either free (runs directly) or costs one of these round trips.
Measured: our own tiny VM on this laptop. This VM cannot run KVM (no /dev/kvm: the M1 Pro has no nested virtualization), but macOS's Hypervisor.framework has the same shape (create a VM, map memory, create a vCPU, hv_vcpu_run until an exit). src/exp/hvf_exits.c builds a VM with one vCPU and two instructions of guest code, an instruction that exits and a branch back to it, and times one exit round trip 20,000 times.
Fig. 3: a system call never leaves the guest; a device register store does
hv_vcpu_run while the guest runs.getpid() stays in the guest. EL0 to EL1 and back, exactly as on bare metal: the guest kernel handles its own system calls and page faults, and the hypervisor never sees them.str x1, [x2] to an address with no memory behind it: the CPU saves the guest's state, enters EL2 with exception class 0x24, and hv_vcpu_run returns into QEMU, which emulates the device and enters the guest again. One round trip: 0.92 µs.hvc #0, class 0x16) took 0.88 µs and the idle instruction (wfi, class 0x01) 0.88 µs: the floor is the trip to EL2 and out to QEMU and back, not the reason.hv_vcpus_exit and the running vCPU is pulled out: 1.08 µs from the call to the exit. This is how a VMM interrupts a vCPU that is running guest code (section 5).read system call at 0.316 µs; an exit is roughly three of them. Cheap once; a fast VM is designed to keep it rare.| Guest instruction | Why it exits | Exception class | Median per exit measured |
|---|---|---|---|
hvc #0 | a hypercall: the guest asks the hypervisor for something | 0x16 | 0.88 µs |
str x1, [x2] to an address with no memory | a device register (MMIO): the hypervisor must emulate the device | 0x24 | 0.92 µs |
wfi | "wait for interrupt": the guest kernel's idle instruction | 0x01 | 0.88 µs |
(another host thread calls hv_vcpus_exit) | a forced exit, how a VMM interrupts a running vCPU | canceled | 1.08 µs from the call to the exit |
measured macOS host, not the VM: Apple M1 Pro, Hypervisor.framework, 3 runs of 20,000 exits (2,000 kicks), median of the three run medians; timer resolution 0.042 µs. Raw: src/raw/hvf_macos.txt.
Reading it. About 0.9 µs per exit, whatever the reason, is the floor: the hardware switch to EL2, Apple's kernel code, the return to our user-space loop, and back. The guest's own system calls, page faults and arithmetic never exit; idle, device registers, timer and interrupt-controller registers, hypercalls and host interrupts do.
perf kvm stat live
On a KVM host (not inside the guest): exits per second by reason, and the time each took.
KVM exposes all of this to an ordinary Linux process through one device file. The shape of every VMM (QEMU, Firecracker) is this loop; LWN's Using the KVM API builds a complete one in about 100 lines.
int kvm = open("/dev/kvm", O_RDWR); int vm = ioctl(kvm, KVM_CREATE_VM, 0); // a VM is a file descriptor void *mem = mmap(NULL, 0x1000, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0); // guest "physical" memory is ordinary memory of this process struct kvm_userspace_memory_region r = { .guest_phys_addr = 0x1000, .memory_size = 0x1000, .userspace_addr = (long)mem }; ioctl(vm, KVM_SET_USER_MEMORY_REGION, &r); int vcpu = ioctl(vm, KVM_CREATE_VCPU, 0); // a virtual CPU is another fd struct kvm_run *run = mmap(NULL, mmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, vcpu, 0); for (;;) { ioctl(vcpu, KVM_RUN, 0); // enter the guest; returns on an exit switch (run->exit_reason) { case KVM_EXIT_IO: /* the guest touched an I/O port: emulate the device */ break; case KVM_EXIT_MMIO: /* a device register in memory: emulate it */ break; case KVM_EXIT_HLT: return 0; // the guest idled } }
Kernel side, Linux v6.12: case KVM_RUN, KVM_CREATE_VCPU, KVM_SET_USER_MEMORY_REGION; the exit codes KVM_EXIT_IO 2, KVM_EXIT_HLT 5, KVM_EXIT_MMIO 6. Only exits the kernel cannot finish itself come back to user space; many (timer, some interrupt work) are handled inside KVM.
| Exit | KVM on arm64 (v6.12) | KVM on Intel (v6.12) | Typical cause |
|---|---|---|---|
| Idle | ESR_ELx_EC_WFx | EXIT_REASON_HLT | a guest CPU has nothing to run |
| Device register | ESR_ELx_EC_DABT_LOW | IO_INSTRUCTION, EPT_VIOLATION | emulated devices, virtio "kicks" (section 6) |
| System register | ESR_ELx_EC_SYS64 | MSR_WRITE, CPUID | timers, interrupt controller, feature probing |
| Hypercall | ESR_ELx_EC_HVC64 | VMCALL | paravirtual services (steal time, power off) |
| Interrupt for the host | (IRQ exit) | EXTERNAL_INTERRUPT | a device of the host's fired while the guest ran |
Why it matters. Every number on these OS pages came from inside a VM, and so does almost every cloud GPU you will train on. Both are recognisable from inside, and both pay the same kinds of cost: exits for idle and devices, slower cross-CPU wake-ups, two-stage page walks, and time the host takes without telling you.
systemd-detect-virt names the hypervisor (kvm, amazon, microsoft, xen) from firmware tables; lspci -nn shows virtio or vendor-specific devices next to the passed-through GPU.grep -c ^processor /proc/cpuinfo counts vCPUs, which on many instance types are hyperthreads, not cores; lscpu shows threads per core.top's st column is steal time where the hypervisor reports it; a large value means your vCPUs wait for the host (section 5).This VM, in one line. On macOS, Docker Desktop 4.11 starts the Linux VM as an ordinary process: QEMU 5.2 with -accel hvf (guest code runs directly through Hypervisor.framework), -smp 5 -m 10240 (5 vCPUs, each a thread of the QEMU process, and 10 GiB of "physical" memory that is ordinary memory of that process), QEMU's generic virt board with a GICv2 interrupt controller emulated by QEMU itself, and virtio disk and network. Inside, arm64 has no CPUID "hypervisor" bit, but the hardware gives it away: GIC-0 on every interrupt line, millions of IPIs, a virtio disk with one queue per vCPU, steal time always 0, no /dev/kvm and no IOMMU (table in the closed block below).
measured src/exp/vmid.sh in an unprivileged container; raw: src/raw/vmid.txt, which also lists the kernel's virtualization config (CONFIG_PARAVIRT=y, CONFIG_VIRTIO_BALLOON=y, CONFIG_KVM=y compiled in but unusable here).
| What the guest sees | What it tells you |
|---|---|
GIC-0 on every line of /proc/interrupts | Linux's GICv2 driver (irq-gic.c names its chip "GIC-%d"); its CPU interface is memory-mapped registers that QEMU emulates. Section 5 shows why that matters. |
IPI0, IPI1 counts in the millions | inter-processor interrupts, the subject of section 5 |
virtio1-req.0 to .4, one per CPU | the virtual disk has one request queue per vCPU (multi-queue), each with its own interrupt (section 6) |
clock source , cpuidle driver none | time comes from the CPU's own counter (virtualized by the hardware, no exit to read it); idle is a plain wfi, which exits |
steal time on every CPU | this hypervisor offers no paravirtual steal clock, so the guest cannot see time stolen by macOS (section 5) |
no /dev/kvm, no /sys/class/iommu | no nested virtualization (KVM inside this guest is impossible) and no virtual IOMMU (section 7 is from sources) |
The VM process's command line (disk path, console pipe, MAC address and network token removed):
measured ps -o args= of the VM process and qemu-system-aarch64 --version on the macOS host (src/exp/host_qemu.sh; raw: src/raw/host_qemu.txt).
| Argument | Means |
|---|---|
-accel hvf | run guest code directly on the CPU through Apple's Hypervisor.framework (the exits of section 2), instead of emulating every instruction in software |
-cpu host -smp 5 -m 10240 | the guest sees this CPU's features, 5 virtual CPUs and 10 GiB of memory |
-machine virt,highmem=off | QEMU's generic arm64 board: a PL011 serial port, a PL031 clock, a PCIe host bridge, and, when no version is asked for and KVM is not in use, a GICv2 interrupt controller emulated by QEMU itself (finalize_gic_version, hw/arm/virt.c L1802-1806, QEMU v6.2.0) |
-device virtio-blk-pci, virtio-net-device | a paravirtual disk on PCI and a paravirtual network card on a memory-mapped bus (section 6) |
-kernel ... -append ... mitigations=off | boot the linuxkit kernel directly, with CPU side-channel mitigations off |
1b36:0008 is QEMU's PCIe host bridge (Red Hat's vendor ID); 1af4:1001 is a virtio block device.
Device 1 is network, 2 is block; vendor 0x554d4551 is the ASCII bytes "QEMU" read as a little-endian number.
wfi, which exits to QEMU; QEMU then puts the vCPU thread to sleep in pselect until the guest's timer is due or another thread signals it (hvf_wfi and hvf_wait_for_ipi, QEMU v6.2.0). That is OSTEP's "information gap" handled well: the VMM notices the guest went idle and gives the CPU back. Section 5 shows what it costs to wake such a thread.The problem. The guest kernel believes it owns "physical" memory from address 0 and builds page tables onto it. That memory is really part of the hypervisor's process (QEMU's 10 GiB here), scattered across the host's RAM. So every guest access needs two translations: guest virtual to guest physical (the guest's tables), then guest physical to host physical (tables the hypervisor owns and the guest cannot see). Virtual memory owns the first translation, the TLB and huge pages; this is the second layer.
Shadow page tables, then nested paging. Before hardware help, the hypervisor kept a shadow page table from guest virtual straight to host physical and write-protected the guest's own tables, so every page-table update exited to be mirrored. With nested paging (Intel EPT, AMD NPT, ARM stage 2) the CPU walks both sets itself, the guest edits its tables with no exits, and the TLB caches the combined result tagged with a VM identifier (VMID on arm64, VPID on Intel) so switching VMs does not flush it. The price moves to the TLB miss: every pointer in the guest's walk is guest-physical and needs a host walk of its own.
Fig. 4: one TLB miss in a VM, each plate one memory reference
Predict before it plays: with 4 guest levels and 4 host levels, how many memory reads does one miss take?
derived with g guest levels and h host levels, each of the g guest table pointers needs a host walk (h reads) plus the read of the guest entry, and the final data address one more host walk: g(h+1) + h = (g+1)(h+1) - 1 references. Analysed in Bhargava et al., ASPLOS 2008, which also proposed the page-walk caches that keep most misses far shorter in practice.
| Configuration | Memory references on a full TLB miss |
|---|---|
| No VM, 4-level page table | 4 |
| VM, 4 KiB pages in both stages (4 x 4 levels) | 24 |
| VM, host backs the guest with 2 MiB pages (4 x 3) | 19 |
| VM, host backs with 1 GiB pages (4 x 2) | 14 |
| VM, 2 MiB pages in both stages (3 x 3) | 15 |
| VM, five-level tables in both stages (5 x 5) | 35 |
Memory overcommit, and why GPU VMs cannot do it. Because guest memory is memory of the hypervisor's process, a host can promise its VMs more than it has: a balloon driver in the guest gives pages back on request, KSM merges identical pages across VMs, and the host can swap. A VM with a passed-through device cannot: the device writes guest memory by DMA at any moment, so every page it might touch must stay put. VFIO pins the pages it maps for a device, and QEMU maps all of guest RAM for it, so a GPU VM's whole memory is pinned when it starts: one reason large GPU VMs boot slowly and cannot be overcommitted.
This kernel has CONFIG_VIRTIO_BALLOON=y; KSM, kernel docs. VFIO charges pinned pages against the locked-memory limit (vfio_pin_map_dma checks RLIMIT_MEMLOCK, Linux v6.12). QEMU maps every RAM region of the guest for the device as the region appears (vfio_listener_region_add calls vfio_dma_map, hw/vfio/common.c L864 and L1063, QEMU v6.2.0). Shadow page tables are described in OSTEP Appendix B: correct, but every page-table update and many page faults cost an exit.
The question the sibling pages left open. Scheduling measured a context switch on one CPU at 1.30 to 1.56 µs but a hand-off between two CPUs at 25.6 to 51.4 µs in this VM; Concurrency found the same for a futex wake-up on another CPU. Both suspected the hypervisor. This section measures it and follows the path through the hypervisor's source.
Inter-processor interrupts. An IPI is one CPU interrupting another. When thread A on CPU 1 writes to a pipe and thread B, asleep on it, last ran on CPU 2, the kernel marks B runnable on CPU 2 and sends CPU 2 a reschedule IPI. An idle arm64 CPU sleeps in wfi, so it always needs the interrupt. Linux also sends function-call IPIs ("run this on your CPU now"); membarrier() sends one to every CPU running a thread of the caller and waits, a direct way to time an IPI round trip from user space.
| Test (CPUs of the VM) | One way, µs measured | IPIs per operation |
|---|---|---|
| Pipe hand-off, both processes on CPU 1 | 2.00 | 0 (a context switch on one CPU) |
| Pipe hand-off, CPUs 1 and 2, idle between hand-offs | 25.3 | 1 reschedule IPI to each side per round trip |
| Same, with a nice 19 busy loop keeping both CPUs awake | 15.4 | 1 reschedule IPI to each side per round trip |
| Spin on one shared cache line, CPUs 1 and 2 (nobody sleeps) | 0.054 | 0 |
membarrier with no other thread running | 0.54 per call | 0 (just the system call) |
membarrier, one thread spinning on CPU 2 | 15.0 per call | 1 function-call IPI to CPU 2 |
membarrier, threads spinning on CPUs 2, 3, 4 | 91.1 per call | 1 function-call IPI to each |
measured src/exp/ipi.c in a container with --cpuset-cpus 1,2,3,4; medians of 3 runs (raw: src/raw/ipi.txt). After each test the program reads /proc/interrupts and divides the IPI counts it added by the number of operations. The sibling pages' numbers came from other runs on the same VM at other times; the spread between runs is itself a property of a laptop VM shared with other work.
Reading it. Moving the byte between CPUs through memory costs 0.054 µs: the cache-coherence hardware is fast. The interrupt is slow: one IPI round trip costs about 14.5 µs (membarrier with one peer, minus the bare system call), and a sleeping wake-up 12.7 times a same-CPU switch. Three IPIs at once cost 30.2 µs each, 2.1 times what three independent ones would: they queue behind each other somewhere.
Steps from the Linux v5.10 GICv2 driver and QEMU v6.2.0's HVF code (the upstream form of the patches in Docker's QEMU 5.2). Times: the totals are the one-way medians measured above; the per-step costs are measured separately on the macOS host (section 2's exits and kick, and a host thread woken from pselect the way QEMU does it). Bare hardware: macOS's own pipe hand-off on the same laptop; bare-metal Linux was not measured here.
Where the time goes. On this guest's emulated GICv2, sending an IPI is a store to a distributor register, and taking one is a load to acknowledge it and a store to end it. All three are device registers, so all three are VM exits into QEMU, which emulates the controller while holding its one global lock. If the target vCPU was idle, its host thread is asleep in pselect and must be woken with a signal. Step through it, against the same hand-off on bare hardware:
Fig. 5: one wake-up, three exits, and a sleeping host thread when the target is idle
resched_curr, smp_send_reschedule).GICD_SGIR) is an MMIO access: vCPU 1's host thread returns from hv_vcpu_run into QEMU. One exit cost 0.92 µs on this laptop.hv_vcpus_exit. vCPU 1 re-enters the guest.wfi (idle), exited, and QEMU put its thread to sleep in pselect. The signal wakes it: waking an idle host thread this way took 29.2 µs (median) in a separate test.hv_vcpu_set_pending_interrupt) and enters the guest.GICC_IAR): another MMIO access, another exit.GICC_EOIR): a third exit.hv_vcpu_run, so hv_vcpus_exit makes it exit: 1.08 µs measured. No host thread has to wake.GICC_IAR read.GICC_EOIR write.wfi. The idle instruction ends in hardware when the interrupt arrives.| Piece of the path | Cost measured on the macOS host |
|---|---|
| One VM exit (MMIO), three per wake-up (send, acknowledge, end) | 0.92 µs each, 2.7 µs for three |
Forcing a running vCPU out (hv_vcpus_exit) | 1.08 µs |
Waking an idle host thread from pselect with a signal | 29.2 µs median (the fastest tenth under 14.4 µs, the slowest tenth over 157.1 µs) |
| The same pipe hand-off natively on macOS | 1.80 µs one way |
So. With the target idle, the wake-up is dominated by the host waking a sleeping vCPU thread: about 29 µs on this laptop, the same size as the 25.3 µs measured inside. With the target busy, no host thread sleeps and 15.4 µs remain: exits and the kick explain 3.8 µs; the other 11.5 µs are QEMU's interrupt-controller emulation and the guest's scheduler work, not measured separately. The superlinear cost of three IPIs fits exits queuing on QEMU's single global lock (likely, not traced). A hand-off inside the VM was 14.0 times the same hand-off natively on the host.
Steal time. When the host runs something else while your vCPU wants to run, the guest only learns of it through a paravirtual clock. This hypervisor offers none, so the steal column here is 0 on every CPU even while macOS runs other programs. KVM reports it; on a cloud VM, top's st or the 8th number of the cpu lines in /proc/stat is the noisy neighbour made visible (Scheduling, CPU accounting).
prefetch_factor so a worker is never woken for one item.st.ThreadPoolExecutor), futex wake-ups. In a VM each hand-off is 10 to 30 µs instead of 1 to 2. Hand off less often: bigger work items per queue message (a batch, not a sample), prefetch_factor so a worker is never woken for one item.st.grep -E 'IPI0|IPI1|Rescheduling|Function call' /proc/interrupts
Run it twice, a second apart: the difference is IPIs per second per CPU (x86 names them RES and CAL).
The waker calls resched_curr, which sends the reschedule IPI (smp_send_reschedule). The only way to skip it is a CPU that is idle but polling a flag (set_nr_if_polling); an arm64 CPU idles in wfi (__cpu_do_idle). membarrier: membarrier.c L170 and L264, Linux v5.10. On a GICv2 the send is gic_ipi_send_mask writing GIC_DIST_SOFTINT; taking it is gic_handle_irq: GIC_CPU_INTACK, GIC_CPU_EOI. QEMU runs hv_vcpu_run between unlocking and relocking its global lock, and MMIO exits become address_space_write (hvf.c L1119-1175, QEMU v6.2.0); idle vCPUs sleep and are kicked in hvf_wait_for_ipi, hvf_kick_vcpu_thread. The host's idle cores sleep deeply, and a woken thread may land on a core that was asleep. Steal time accounting: cputime.c L237-243; arm64 asks the hypervisor through a firmware call, has_pv_steal_clock.
hv_vcpu_run, not asleep in pselect: QEMU forces it out with hv_vcpus_exit (about 1.1 µs). That is why the busy case (15.4 µs) is faster than the idle one (25.3 µs): the idle case adds a host thread wake-up.An illustration of the protocol with four requests; the measured ratios are in the table below.
The problem. An emulated real disk means the guest's normal driver pokes device registers, and every poke exits to the hypervisor: several exits per 4 KiB read, plus an emulated interrupt with its own exits (section 5).
How virtio works. virtio is a device interface made for VMs: guest and hypervisor share a virtqueue in guest memory, in three parts:
struct vring_desc)struct vring_avail)struct vring_used)A request is three descriptors (header "read sector N", data buffer, status byte). The guest adds them, bumps the available index, and only then kicks the device: one register write, one exit. The device reads the request straight out of guest memory, does the I/O, writes the used ring and injects one interrupt. With the event index feature each side says "notify me only when your index passes N", so a busy queue needs neither a kick per request nor an interrupt per completion.
virtio: Russell, virtio, 2008; OASIS VIRTIO 1.2 specification; the three parts in include/uapi/linux/virtio_ring.h, Linux v5.10. The event index is VIRTIO_RING_F_EVENT_IDX, bit 29 (vring_need_event, used by virtqueue_kick_prepare_split). Both of this VM's virtio devices offer it (section 3's feature bits). For QEMU, the device side reads guest memory as its own memory.
Fig. 6: four 4 KiB reads through one virtqueue
virtqueue_kick_prepare decides one notification covers them: the device is told where to look once.4 KiB random O_DIRECT reads, 20,000 each | Queue depth 1 | Queue depth 32 |
|---|---|---|
| Requests per second | 15748 | 60975 (3.9 times) |
| Time per request | 63.5 µs (1 / rate) | 508.6 µs mean completion latency (Little's law: 32 / rate = 524.8 µs) |
| virtio-blk interrupts per request | 1.0 | 0.11: 8.9 completions per interrupt |
measured fio 3.33 with libaio on a 256 MiB file on the VM's virtio-blk disk, interrupts counted from the virtio1-req.* lines of /proc/interrupts and requests from /sys/block/vda/stat (src/exp/virtio.sh; raw: src/raw/virtio.txt). The disk image is a file on the Mac's SSD that macOS caches, so absolute times are not a real NVMe drive's; the Storage page measured the disk side in depth.
Reading it. At queue depth 1, every request pays its own kick and its own interrupt, each with its exits; at depth 32, the event index lets one interrupt report about nine completions and the rate nearly quadruples. This is the I/O version of section 5's lesson: in a VM, notifications are the expensive part, and batching is how you buy them back.
vhost-net; this kernel builds it as a module, CONFIG_VHOST_NET=m): the kick wakes a kernel thread, no trip to QEMU.grep virtio /proc/interrupts; cat /sys/block/vda/queue/scheduler
not run here: this VM has no IOMMU and no device to pass through; taught from the kernel's VFIO documentation and source, and NVIDIA's NCCL guide.
The problem. A GPU cannot be emulated at any useful speed, so the guest is given the real device (passthrough). But a device writes to memory by DMA (direct memory access: the device itself reads and writes RAM, without the CPU), using physical addresses. A guest driver programs the GPU with guest-physical addresses, which are wrong on the host; worse, a malicious guest could program it to write anywhere in the host's memory.
How it works: an MMU for devices. The IOMMU (Intel VT-d, AMD-Vi, ARM SMMU) sits between devices and memory and translates every DMA address through page tables of its own, one set per device domain. The hypervisor fills them so the device's addresses are the guest's physical addresses, mapped to exactly the host pages backing that guest and nothing else. The same unit remaps the device's interrupts so they reach the right guest.
Fig. 7: the GPU speaks guest-physical; the IOMMU makes it land in this guest only
Linux exposes this as VFIO: "from a device and host perspective, this simply turns the VM into a userspace driver" (VFIO documentation, Linux v6.12).
"The VFIO driver is an IOMMU/device agnostic framework for exposing direct device access to userspace, in a secure, IOMMU protected environment". The steps of its own example:
int container = open("/dev/vfio/vfio", O_RDWR); // an IOMMU context int group = open("/dev/vfio/26", O_RDWR); // the device's IOMMU group ioctl(group, VFIO_GROUP_SET_CONTAINER, &container); ioctl(container, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU); ioctl(container, VFIO_IOMMU_MAP_DMA, &dma_map); // "device address X is this memory": pins it int device = ioctl(group, VFIO_GROUP_GET_DEVICE_FD, "0000:06:0d.0"); // then mmap the device's registers (BARs) and hand them to the guest
From vfio.rst lines 177-213. Mapping pins the pages (vfio_pin_pages_remote), which is section 4's "a GPU VM cannot overcommit memory". Newer kernels add iommufd, a general replacement for the container.
IOMMU groups and ACS. The IOMMU can only isolate what it can tell apart. Devices behind a bridge that lets them talk to each other directly, without passing the IOMMU, are inseparable: "a group is a set of devices which is isolatable from all other devices in the system. Groups are therefore the unit of ownership used by VFIO" (vfio.rst lines 55-71). PCIe switches use Access Control Services (ACS) to force device-to-device traffic up through the IOMMU, which makes small groups possible. That is exactly the tension with GPU clusters:
NCCL's guide: on bare metal, "IO virtualization (also known as VT-d or IOMMU) can interfere with GPU Direct by redirecting all PCI point-to-point traffic to the CPU root complex, causing a significant performance reduction or even a hang", so bare-metal clusters disable ACS on their PCIe switches. In a VM that is not an option: "Virtual machines require ACS to function, hence disabling ACS is not an option. To run with maximum performance inside virtual machines, ATS needs to be enabled in network adapters" (ATS, Address Translation Services, lets the device cache IOMMU translations itself). And NCCL reads the PCI topology from /sys: "Having /sys expose a virtual PCI topology can result in sub-optimal performance" (NCCL GPU troubleshooting).
What passthrough costs. Once set up, almost nothing on the data path: the GPU's registers are mapped into the guest by stage-2 page tables, so a doorbell write is an ordinary store, and the GPU's DMA goes through the IOMMU's translation cache. The costs are at the edges: pinning all guest memory at boot, IOTLB misses for scattered DMA, interrupts that must be remapped, and a guest that sees whatever PCI topology the hypervisor chose to show it.
NCCL_DEBUG=INFO) and the topology (nvidia-smi topo -m); a VM's real topology can be given to NCCL as an XML file (NCCL_TOPO_FILE; "by default, NCCL will load /var/run/nvidia-topologyd/virtualTopology.xml if present", NCCL environment variables).nvidia-smi topo -p2p on bare metal: IOMMU settings or ACS, per the NCCL guide.ls /sys/kernel/iommu_groups/; lspci -nnk | grep -A3 -i nvidia
On a host, a passed-through GPU shows Kernel driver in use: vfio-pci; inside the guest the same GPU shows nvidia.
not run here: no GPU; from NVIDIA's MIG, MPS, vGPU and GPU Operator documentation and the kernel's SR-IOV documentation.
The problem. Passthrough gives one guest a whole device. An 80 GB data-centre GPU is far more than a notebook, a small model's inference server or a CI job needs, and an idle GPU is expensive. The question is how to split one GPU between several processes, containers or VMs, and what each split gives up.
SR-IOV first, because NICs use it. Single Root I/O Virtualization lets one PCIe device present a physical function (PF, the full device, managed by the host) and many lightweight virtual functions (VFs), each with its own PCI identity, so each can be passed through to a different VM with section 7's machinery. On Linux you create them by writing a number to /sys/bus/pci/devices/<address>/sriov_numvfs (pci-iov-howto.rst, Linux v6.12). This is how a GPU VM gets its own slice of an InfiniBand or RoCE NIC for RDMA.
Why GPUs are harder: how the GPU itself schedules. A GPU runs work from one CUDA context (the per-process state: address space, loaded kernels, streams) concurrently, but "work launched to the compute engine from work queues belonging to different CUDA contexts cannot execute concurrently": between processes the GPU time-slices (MPS architecture). Every sharing scheme is a different answer to that:
Fig. 8: three ways to put jobs A and B on one GPU: take turns, merge, or cut
| Time slicing | MPS | MIG | vGPU | Passthrough | |
|---|---|---|---|---|---|
| What it is | several processes or pods use the same GPU; the GPU switches between their contexts | a server process merges clients' work so it runs concurrently | the hardware is cut into up to 7 instances, each with its own SMs, L2 slices and memory | a hypervisor-side manager gives each VM a virtual GPU, time-sliced or backed by a MIG instance | one whole GPU per VM |
| Concurrency between users | no, one context at a time | yes | yes, physically separate | time-sliced or MIG-backed | n/a |
| Memory isolation | no: any replica can use all the memory | address spaces isolated ("MPS client processes have fully isolated GPU address spaces") | yes, dedicated memory per instance | yes | whole GPU |
| Memory bandwidth and cache QoS | no | no | yes | per mode | whole GPU |
| Error isolation | no (time slicing has "no memory or fault-isolation between replicas") | no (limited containment on Volta and later) | yes | yes | yes |
| Max partitions | configurable replicas | 48 | 7 | per vGPU profile | 1 |
| Reconfigure | any time | at process launch | when the GPU is idle | per VM | per VM |
Streams, MPS and MIG columns from the MIG user guide's table "CUDA Concurrency Mechanisms" (MIG concepts): MPS "does not offer error isolation between clients", and with MIG "each instance's processors have separate and isolated paths through the entire memory system - the on-chip crossbar ports, L2 cache banks, memory controllers, and DRAM address busses" (MIG introduction); MPS's limited containment from the MPS documentation. Time slicing from the GPU Operator guide: "A request for more than one time-sliced GPU does not guarantee that the pod receives access to a proportional amount of GPU compute power." vGPU's time-sliced schedulers are "best effort" (the default), "equal share" and "fixed share" (vGPU scheduling policies).
MIG in practice. A MIG-capable GPU (A100 and later data-centre parts) is enabled once (on A100 and A30, "setting MIG mode ... requires a GPU reset"), then carved into GPU instances from fixed profiles, each named by its compute slices and memory: on an H100 80GB, 1g.10gb (1/7 of the SMs, 1/8 of the memory, up to 7 of them), 2g.20gb, 3g.40gb, 4g.40gb, 7g.80gb (MIG supported profiles). Profiles can only sit at certain positions, so the order you create them in matters. Each instance then appears to CUDA as its own device: CUDA_VISIBLE_DEVICES=MIG-<uuid>.
nvidia-smi on the node lists every process on the GPU.Predict first: can you fit a 3g.20gb after placing two 1g.5gb and a 2g.10gb? Pick a profile, then one of its allowed starts on the 8 memory slices; click an instance to remove it. Placements are NVIDIA's, for an A100 40GB, from nvidia-smi mig -lgipp in the MIG user guide; nothing here ran on a GPU.
$ nvidia-smi mig -lgipp (A100-SXM4-40GB, from the MIG user guide)
GPU 0 Profile ID 19 Placements: {0,1,2,3,4,5,6}:1 1g.5gb
GPU 0 Profile ID 20 Placements: {0,1,2,3,4,5,6}:1 1g.5gb+me (1 instance at most)
GPU 0 Profile ID 15 Placements: {0,2,4,6}:2 1g.10gb
GPU 0 Profile ID 14 Placements: {0,2,4}:2 2g.10gb
GPU 0 Profile ID 9 Placements: {0,4}:4 3g.20gb
GPU 0 Profile ID 5 Placement : {0}:4 4g.20gb
GPU 0 Profile ID 0 Placement : {0}:8 7g.40gb
"The syntax of the placement is {<index>}:<GPU Slice Count>". Instances may not overlap, and the compute slices (the number before "g") add up to at most 7. The guide warns: "As GPU Instances are created and destroyed at different locations, fragmentation can occur, and the physical position of one GPU Instance will play a role in which other GPU Instances can be instantiated next to it" (MIG concepts); and "due to a known issue with the APIs, the profile ID 9 or 3g.20gb must be specified first", because the driver's automatic placement of smaller instances can take the positions a 3g.20gb needs. Try the "1-1-2, then 3g" example to see it. The H100 80GB has the same seven profiles at twice the memory (1g.10gb, 1g.10gb+me, 1g.20gb, 2g.20gb, 3g.40gb, 4g.40gb, 7g.80gb) (supported profiles); its placement listing is not reproduced here.
After creating GPU instances you create compute instances inside them (nvidia-smi mig -cgi 9,3g.20gb -C does both), and each appears to CUDA as its own device: CUDA_VISIBLE_DEVICES=MIG-<uuid>. "The created MIG devices are not persistent across system reboots."
nvidia-smi mig -lgip; nvidia-smi mig -lgipp; nvidia-smi -L
The problem. y = x @ w on CUDA tensors returns in a few microseconds and the GPU does the work later. Between the two sit the libraries and driver in the hero figure, invisible until they fail. Writing kernels and the GPU as hardware are Topic: cuda-and-gpu-programming's (its Compiler explorer has the same CUDA 13.4 toolchain) and Topic: hardware's.
| Layer | What it is, where it comes from | Its job in y = x @ w |
|---|---|---|
| PyTorch | your wheel or image | the dispatcher picks the CUDA implementation of matmul, which calls cuBLAS; elementwise ops launch PyTorch's own kernels |
CUDA runtime libcudart.so.13 | part of the toolkit; PyTorch's CUDA wheels load it from the nvidia-cuda-runtime wheel (_preload_cuda_deps, torch/__init__.py L351-362, v2.14.1) | the convenient API: creates a context implicitly, registers the program's kernels, turns cudaLaunchKernel into driver calls |
CUDA driver libcuda.so.1 | the user-mode driver, installed with the host's driver package, not with the toolkit; a container gets the host's copy mounted in | the real work in user space: contexts, memory, module loading, JIT compiling PTX, building command buffers and submitting them |
Kernel driver nvidia.ko, nvidia-uvm.ko | the host's kernel modules; NVIDIA's open-gpu-kernel-modules are the open-source version | owns the hardware: memory allocation and mapping, channels, interrupts, faults, power, reset; reached by ioctl on /dev/nvidia* |
GSP firmware gsp_*.bin | installed with the driver in /lib/firmware/nvidia/615.71.09/, one file per GPU architecture | on Turing and later GPUs, runs most of the resource manager on the GPU's own processor (below) |
| GPU | a PCIe device (passed through in a VM) | fetches commands from memory by DMA and runs them |
Where the resource manager runs: the GSP. On Turing and later GPUs the driver by default offloads "GPU initialization and management tasks" to the GPU System Processor (GSP), "driven by firmware files distributed with the driver" (NVIDIA driver README 615.71.09, GSP Firmware). In the open driver that firmware is a build of the resource manager itself (GSP-RM), booted by the kernel module and reached by RPC messages through shared queues; the open modules work only this way. So three pieces must carry the same version: libcuda, nvidia.ko and the firmware.
Where the resource manager runs: the GSP. "Some GPUs include a GPU System Processor (GSP) which can be used to offload GPU initialization and management tasks. This processor is driven by firmware files distributed with the driver", and "the GSP firmware will be used by default for all Turing and later GPUs" (NVIDIA driver README 615.71.09, GSP Firmware). In the open driver the firmware is a build of the resource manager itself, booted by the kernel module (_kgspBootGspRm, kernel_gsp.c L5429) and reached by RPC messages through shared queues (_kgspRpcSendMessage, L525). The open modules work only this way: they "must be used with GSP firmware and user-space NVIDIA GPU driver components from a corresponding 615.71.09 driver release" (README). So three pieces must carry the same version: libcuda, nvidia.ko and the firmware.
First panel: GSP disabled (NVreg_EnableGpuFirmware=0, proprietary modules only, or GPUs before Turing): the resource manager runs on the host CPU inside nvidia.ko. Second: the default on Turing and later: nvidia.ko forwards the call as an RPC to GSP-RM on the GPU. Neither changes the launch path, which never enters the kernel. Check with nvidia-smi -q: "GSP Firmware Version" shows a version, or "N/A" if disabled. NVIDIA's known issues for the open modules (always GSP) against the proprietary modules with GSP disabled include "GPU initialization is slower", mitigated by nvidia-persistenced (section 11; open kernel modules README).
What happens with no GPU: four cases, run for real. A small CUDA program (src/exp/cuda/rt_probe.cu, built with the runtime as a shared library) and a driver-API probe (drv_probe.c, which dlopens libcuda.so.1 the way the runtime does) were run in the CUDA 13.4.2 image under strace and LD_DEBUG. Every recorded trace line is stepped in a closed block at the end of this section.
| Case | cudaGetDeviceCount returns measured | Why |
|---|---|---|
| 1. No driver at all (any container started without the NVIDIA runtime) | 35 cudaErrorInsufficientDriver: "CUDA driver version is insufficient for CUDA runtime version"; cudaDriverGetVersion gives 0 | the runtime looked for libcuda.so.1 in five directories and found none; "insufficient" here means "absent" |
2. The toolkit's stub libcuda.so found as libcuda.so.1 | 34 cudaErrorStubLibrary: "CUDA driver is a stub library" | the stub exists so programs can be linked on machines without a driver; it refuses to run |
| 3. The real user-mode driver 615.71.09, no kernel module | 100 cudaErrorNoDevice: "no CUDA-capable device is detected"; driver version 13040 | libcuda loaded, then failed to open /dev/nvidiactl (details below) |
| 4. As 3, with the container's device cgroup opened for major 195 | 100, and open now fails with ENXIO | the kernel has no driver registered for character major 195 |
How the kernel side is organised. Every device file of nvidia.ko shares one set of file operations; a few ioctls (the version handshake below) are handled in its Linux layer and the rest go to the resource manager (RM), where everything is an object with a handle (a client per process, a device, memory, a channel) that ioctls allocate, control, free and map. Unified memory has its own device, /dev/nvidia-uvm. libcuda's last act in case 3 was one such ioctl, 0xc020462a: NV_ESC_RM_CONTROL (decoded in the closed block below).
The version handshake. Among the first things a client sends on /dev/nvidiactl is NV_ESC_CHECK_VERSION_STR: the kernel compares the client's version string with its own and on a mismatch logs "NVRM: API mismatch ... Please make sure that this kernel module and all NVIDIA driver components have the same version". That is the dmesg line after a driver upgrade without a reboot: new user-mode libraries meet the old module still loaded.
Launching work without a system call. A GPU channel is a queue of work in memory: a pushbuffer holds the commands (launch this kernel, copy this, wait on that semaphore), a ring called the GPFIFO points at pushbuffer segments, and a doorbell register tells the GPU the ring moved. The open driver's unified-memory module submits work exactly so: fill a GPFIFO entry, barrier, write the put pointer, barrier, store a token into the doorbell (VOLTA_USERMODE_A, NOTIFY_CHANNEL_PENDING at offset 0x90). Once mapped every piece is ordinary memory, so a launch is plain stores: no system call, and no exit even in a VM.
Fig. 10: one CUDA call down, the first in a process against the millionth
The first CUDA call of a process against a launch in the training loop: what enters the kernel, and what is plain memory writes. Steps from the open driver's interface; the order inside the closed libcuda is simplified.
dlopen("libcuda.so.1"): enters the kernel. The runtime looks for the user-mode driver (here it searched five directories, case 1) and maps it: openat and mmap system calls.open("/dev/nvidiactl"): enters the kernel. cuInit opens the control device, character 195:255. In a container this is where the device cgroup says yes or no.ioctl NV_ESC_CHECK_VERSION_STR: enters the kernel. The version handshake with nvidia.ko: an exact or relaxed match of the version strings, or the "API mismatch" message in the kernel log.ioctl NV_ESC_RM_ALLOC, NV_ESC_RM_CONTROL: enters the kernel. Resource-manager objects: a client for this process, then a device and subdevice per GPU; control calls ask what the GPUs are. With GSP, nvidia.ko forwards them to GSP-RM on the GPU.open("/dev/nvidia0"), open("/dev/nvidia-uvm"): enters the kernel. The GPU itself, and the unified-memory device (UVM_INITIALIZE, UVM_REGISTER_GPU) that gives CPU and GPU one virtual address space.NV_ESC_RM_MAP_MEMORY and mmap so the process can write them directly.uvm_channel.c L984-1015 shows the same sequence).NOTIFY_CHANNEL_PENDING in the mapped usermode page. In a VM with passthrough this is not an exit: the page is mapped by stage-2 tables.cudaLaunchKernel, cuLaunchKernel: user space. PyTorch's dispatcher has chosen the kernel; the runtime forwards to the driver API. Everything the first call set up is already mapped.libcuda; see the box above).The version handshake. Among the first things a client sends on /dev/nvidiactl is NV_ESC_CHECK_VERSION_STR. The kernel compares the client's version string with its own, exactly, or only up to the first dot if the client asks for "relaxed" checking; on a mismatch it logs "NVRM: API mismatch: the client ... has the version ..., but this kernel module has the version ... Please make sure that this kernel module and all NVIDIA driver components have the same version" (RmPerformVersionCheck, osapi.c L1199-1302). That is the message in dmesg after a driver upgrade without a reboot: the new user-mode libraries meet the old module still loaded.
Launching work without a system call. A GPU channel is a queue of work: a pushbuffer in memory holds the commands ("methods": launch this kernel with these parameters, copy this, wait for that semaphore), a ring called the GPFIFO holds pointers to pushbuffer segments, and a doorbell register tells the GPU's host interface that the ring moved. The open driver's own unified-memory module submits work exactly like this, and its code shows each step: fill a GPFIFO entry pointing at the pushbuffer, a memory barrier, write the new put pointer, a write barrier, and ring the doorbell by storing a token into the doorbell register (internal_channel_submit_work, uvm_channel.c L984-1015; write_gpu_put, uvm_turing_host.c L222-236). The doorbell lives in a "usermode" register page, the class VOLTA_USERMODE_A with NOTIFY_CHANNEL_PENDING at offset 0x90 (clc361.h), an object any RM client can allocate and map. Every piece is ordinary memory once mapped, so a process holding the mappings can launch with plain stores: no system call, no exit even in a VM.
Verified from the open source: the device files, the ioctl protocol, the RM object model, the channel, GPFIFO and doorbell mechanism, and that kernel-side code (UVM) submits work with stores alone. Inferred: that the closed libcuda launches kernels the same way, by mapping its channels and the usermode page at context creation; it is the design the open interface supports, and the root page's description, but libcuda itself cannot be read. On a GPU machine, strace -f -c over a steady training loop confirms or refutes it in a minute. This replaces the root page's "not verified from a primary source" with this narrower statement.
--gpus.torch.cuda.is_available() returns False for cases 1 and 3 without raising, because it calls cudaGetDeviceCount (torch/cuda/__init__.py L209-228). The CPU-only wheel used here never even looks for a driver.fork(): the child inherits a driver state it cannot use; PyTorch avoids touching CUDA in is_available() only if PYTORCH_NVML_BASED_CUDA_CHECK=1 (same file). See the Processes page on start methods.strace -f -e trace=openat,ioctl,mmap -o trace.txt python train.py; LD_DEBUG=libs python -c "import torch; torch.cuda.init()" 2>&1 | grep libcuda
Case 3, line by line. The user-mode driver came from the image's forward-compatibility directory (/usr/local/cuda/compat, section 10). Its cuInit did, in order: read /proc/driver/nvidia/params (the kernel module's parameters: absent), look for /usr/bin/nvidia-modprobe (a setuid helper that loads the module and creates device files: absent), then, running as root, delete whatever was at /dev/nvidiactl and create it itself:
The node is character device 195:255, exactly the kernel driver's numbers (NV_MAJOR_DEVICE_NUMBER 195, NV_MINOR_DEVICE_NUMBER_CONTROL_DEVICE 255). Creating it worked (Docker grants CAP_MKNOD); opening it failed with EPERM, because the container's device cgroup only allows a short list of devices (the Containers and isolation page covers the device controller). libcuda retried eight times, scanned /sys/bus/pci/devices/*/config for an NVIDIA device, read /proc/modules for a loaded nvidia module, and finally sent one ioctl to the file descriptor -1 it never got: 0xc020462a. That number decodes, with Linux's _IOC layout, into the whole protocol:
| Bits | Field | Value | Meaning, from the open driver |
|---|---|---|---|
| 30-31 | direction | 3 | read and write: the kernel copies the argument in and back out |
| 16-29 | size | 32 bytes | the size of NVOS54_PARAMETERS: client handle, object handle, command, flags, a pointer to the command's own parameters, their size, a status |
| 8-15 | type | 'F' | NV_IOCTL_MAGIC, every NVIDIA ioctl |
| 0-7 | number | 0x2A | NV_ESC_RM_CONTROL: "run control command cmd on object hObject" |
The sources. nvidia.ko registers one set of file operations for all its device files: open, unlocked_ioctl, mmap, poll, release (nvidia_fops, nv.c L259-269). A handful of ioctls are handled in the Linux layer, such as the version handshake (below); everything else goes to the resource manager (RM), the OS-independent core of the driver (default: rm_ioctl, nv.c L2981-2982). In RM everything is an object with a handle: a client (your process), a device, a subdevice, a memory allocation, a channel. The escapes allocate objects (NV_ESC_RM_ALLOC 0x2B), free them, run control calls on them (NV_ESC_RM_CONTROL), and map them into the process (NV_ESC_RM_MAP_MEMORY, followed by an mmap of the device file, nvidia_mmap). Unified memory has its own device, /dev/nvidia-uvm, with ioctls such as UVM_REGISTER_GPU and UVM_MIGRATE.
Every line below was recorded in the CUDA 13.4.2 image (kb-os-virt:1) on this page's Linux VM, which has no GPU. Pick a case, then step through the trace: each step highlights the real line and says what it means, with the source that explains it. The table above is the summary; this is the evidence.
Inside the binary: what the driver loads. Your program's GPU code is not in the CPU part of the executable. It sits in a section called .nv_fatbin, a container (fatbin) holding machine code for specific GPUs (cubin, SASS) and the portable intermediate form (PTX). The test program was built for sm_80 and sm_90 plus PTX for compute_90:
measured cuobjdump -lelf -lptx and readelf -S on the built executable (raw: src/raw/cuda.txt; the tab shows the cubin sizes and the PTX). The executable carries two cubins per architecture: the two holding vadd come from this file; the object file alone has one per architecture, so the two small cubins with no kernels were added when nvcc linked the program (most likely by its device-link step).
At load time the driver picks, for the GPU it finds: a cubin for the same major compute capability and an equal or lower minor ("a cubin with code compiled for compute capability 8.6 ... can be loaded and executed on GPUs with compute capability 8.6 or 8.9"); otherwise it JIT-compiles the PTX, which works on any equal or newer GPU, and caches the result in the "compute cache" (~/.nv/ComputeCache, CUDA_CACHE_PATH) (CUDA Programming Guide 1.3.4; environment variables). Since CUDA 12.3 modules load lazily by default: a kernel is loaded at its first launch, not at start-up (CUDA_MODULE_LOADING, Lazy Loading).
What the driver would load on a GPU: the test program built with nvcc -cudart shared -gencode arch=compute_80,code=sm_80 -gencode arch=compute_90,code=sm_90 -gencode arch=compute_90,code=compute_90. The CUDA topic's Compiler explorer shows the SASS and PTX of many kernels for four GPU generations; here the point is only what the driver receives.
measured src/exp/cuda/run.sh and run_dev.sh; raw: src/raw/cuda.txt, src/raw/cuda_dev.txt. Containers ran unprivileged with --cap-add SYS_PTRACE for strace; case 4 added --device-cgroup-rule 'c 195:* rwm'.
The problem. A CUDA program depends on two independently installed things: the runtime it was built with (inside your image or wheel: torch.version.cuda) and the driver on the machine it runs on (host: nvidia-smi prints its version and the newest CUDA version it supports). Clusters upgrade drivers rarely and carefully; images change every week. "CUDA driver version is insufficient for CUDA runtime version" is the result of the two drifting apart.
Measured here. The runtime reported 13040 (CUDA 13.4) in every case. The driver version was 0 with no libcuda (case 1 of section 9), and 13040 with the 615.71.09 user-mode driver from the image's /usr/local/cuda/compat. The image also declares what it needs, for the NVIDIA container toolkit to check before starting it: NVIDIA_REQUIRE_CUDA=cuda>=13.4 plus a list of accepted driver branches for data-centre GPUs (brand=tesla,driver>=535,driver<536, and likewise 570, 580, 590, 595, 610). "If the version of the NVIDIA driver is insufficient to run this version of CUDA, the container does not start" (container toolkit, NVIDIA_REQUIRE_CUDA).
| The driver (libcuda) is | Compatibility | Requirements |
|---|---|---|
| newer than the runtime | backward compatibility | none |
| older than the runtime, same major version | minor version compatibility | no PTX (needs SASS for the GPU), the target architecture given to nvcc; some new features return cudaErrorCallRequiresNewerDriver |
| older than the runtime's major version | forward compatibility | the cuda-compat package; data-centre GPUs (and some RTX and Jetson) only |
From CUDA Compatibility: why and minor version compatibility: minimum drivers CUDA 13.x ">= 580", 12.x ">= 525", 11.x ">= 450"; "Applications that compile device code to PTX will not work on older drivers". Forward compatibility: "the cuda-compat-13-4 package is built using the NVIDIA driver libraries version 615", installed into /usr/local/cuda-13.4/compat/, and "This package only provides the libraries, and does not configure the system to find such libraries" (you set LD_LIBRARY_PATH); errors 803 CUDA_ERROR_SYSTEM_DRIVER_MISMATCH and 804 CUDA_ERROR_COMPAT_NOT_SUPPORTED_ON_DEVICE. Since CUDA 13.4 the Linux driver is no longer bundled with the toolkit.
The container toolkit at the driver level. A GPU container is section 9's stack cut in two: the image brings PyTorch and the runtime; the host must lend it the user-mode driver that matches its kernel module, the device files, and permission to open them. Each missing piece is one of section 9's measured failures. The NVIDIA Container Toolkit (or a CDI spec it generates) supplies all three and checks NVIDIA_REQUIRE_CUDA first; how it does so (bind mounts, the device cgroup's BPF program, CDI) is owned by Containers and isolation.
Why forward compatibility can work at all. Section 9's version handshake is between the user-mode driver and the kernel module. Forward compatibility swaps only the user-mode half: a newer libcuda (from the compat package) talks to an older nvidia.ko. NVIDIA: "forward compatibility is defined between the kernel driver and the CUDA driver", which is also why it can JIT PTX where minor version compatibility cannot (the compat package brings its own PTX compiler, libnvidia-ptxjitcompiler, visible in this image's compat directory).
| Fact | Value |
|---|---|
| Minimum driver for minor version compatibility | CUDA 13.x: 580; 12.x: 525; 11.x: 450 |
| Newest toolkit and its driver | CUDA 13.4, driver branch 615 (615.71.09 here); cuda-compat-13-4 is built from driver 615 |
| Forward-compatibility targets in the matrix | driver branches 535, 570, 580, 590, 595, 610 (data-centre GPUs) |
| Toolkit installer | since CUDA 13.4 the Linux driver is no longer bundled |
Errors measured here (section 9, cases 1 to 4) except the version mismatch, which is the open module's message read in source. Why the toolkit mounts the host's libcuda rather than trusting the image's: the version handshake wants the two halves of the driver to agree; the compat package is the one sanctioned exception.
dmesg.nvidia-smi | head -4; python -c "import torch; print(torch.version.cuda, torch.cuda.is_available())"; ls /usr/local/cuda/compat
not run here except where marked: no GPU; from the open kernel modules at 615.71.09 and NVIDIA's documentation.
GPU memory is not Linux's memory. The kernel's page allocator, page cache, swap and OOM killer (the Virtual memory page) know nothing about the GPU's own memory. The driver's resource manager hands it out in response to RM allocation ioctls; above it, PyTorch's caching allocator keeps freed blocks for reuse (the Memory allocators page). So "CUDA out of memory" is never solved by the host's swap, and GPU memory a crashed process held comes back only when the driver tears its client down.
| Kind of memory | What the OS does | Where on these pages |
|---|---|---|
Device memory (cudaMalloc) | nothing: RM allocates it; the CPU can reach parts of it through a PCIe window (BAR1) mapped by mmap on the device file (nvidia_mmap) | here; Memory allocators |
Pinned host memory (pin_memory=True) | ordinary RAM, locked so the GPU's DMA can target it; counts against RLIMIT_MEMLOCK | Virtual memory, section 9 |
Managed memory (cudaMallocManaged) | pages migrate between CPU and GPU on page faults, serviced by nvidia-uvm.ko | here |
| System memory used by the GPU directly (HMM, Grace Hopper) | the GPU uses the process's own page tables, through Linux's HMM or hardware coherence | here |
Unified memory and HMM: the GPU takes page faults. With managed memory one pointer works on both sides; a GPU access to a page the CPU holds faults, the GPU records the fault in a buffer, and nvidia-uvm.ko services faults in batches by unmapping, migrating and remapping the page, which is expensive and proportional to the page size. With Linux's HMM even plain malloc memory becomes reachable from the GPU (open kernel modules only). How to use managed memory well, and prefetching, are owned by GPU memory hierarchy and Streams, CUDA graphs and multi-GPU.
With managed memory, one pointer works on both sides. On systems where CPU and GPU each have their own page tables, a fault means the page must be unmapped from its owner, mapped for the requester, and "the physical page backing this virtual page must be moved/migrated to the processor requesting access: this can be an expensive operation, and the amount of work is proportional to the page size" (CUDA Programming Guide, unified memory). The GPU records its faults in a buffer and the UVM driver services them in batches (uvm_parent_gpu_service_replayable_faults). With Linux's HMM (heterogeneous memory management), even plain malloc memory becomes reachable from the GPU; it "requires Linux kernel version 6.1.24+, 6.2.11+ or 6.3+, devices with compute capability 7.5 or higher and a CUDA driver version 535+ installed with Open Kernel Modules" (same guide; the open module's support starts at uvm_hmm.c).
GPUDirect RDMA. For multi-node training the NIC should move data straight to and from GPU memory: the nvidia-peermem module lets the InfiniBand stack pin GPU pages for the NIC, or, with the open driver and a recent kernel, NCCL uses DMA-BUF instead. In a VM both devices sit behind the IOMMU and section 7's ACS and ATS rules apply.
Driver state lives as long as someone holds it open. The kernel module tears the device down on the last file close, so without a long-lived client every short CUDA job re-initialises the GPU, "on the order of seconds"; nvidia-persistenced is a daemon that simply keeps the device files open (the old nvidia-smi -pm 1 is deprecated). GPU errors are logged by the kernel driver as Xid messages (dmesg | grep "NVRM: Xid"), which a container or VM may not be allowed to read: ask whoever runs the host. CUDA_VISIBLE_DEVICES filters and reorders the devices the runtime enumerates; below it, a container sees only the device files it was given.
GPUDirect RDMA: the NIC writes into GPU memory. For multi-node training the network card should move data straight to and from GPU memory. The nvidia-peermem module lets the InfiniBand stack pin GPU pages for the NIC (nvidia_p2p_get_pages); "GDRDMA can also be enabled by using the DMA-BUF feature of recent Linux kernels combined with the open source Nvidia GPU driver. In this case, NCCL will automatically detect and enable DMA-BUF so the nvidia-peermem module will not be necessary" (NCCL GPU troubleshooting). In a VM, both devices sit behind the IOMMU and section 7's ACS and ATS rules apply.
Driver state lives as long as someone holds it open. The kernel module "tears down the device on the last file close" (nv_stop_device, nv.c L2216). Without a long-lived client, every short CUDA job re-initialises the GPU, which "leads to long load times for each CUDA job, on the order of seconds" (driver persistence). The old fix, persistence mode (nvidia-smi -pm 1), now logs "Persistence mode is deprecated and will be removed in a future release. Please use nvidia-persistenced instead" (nv.c L2259-2265): a daemon that simply keeps the device files open.
When the GPU fails, the kernel log says so. GPU errors (a kernel's illegal memory access, a fallen-off-the-bus GPU, ECC errors) are logged by the kernel driver as Xid messages: "Under Linux, the Xid error messages are logged in the kernel log buffer ... Grep for 'NVRM: Xid'" (Xid errors). A training job that dies with a vague CUDA error should be read together with dmesg on the host; inside a container or a VM you may not be allowed to read it (this page's containers could not), so ask whoever runs the host.
Which GPUs a process sees. CUDA_VISIBLE_DEVICES filters and reorders devices for the CUDA runtime: "setting CUDA_VISIBLE_DEVICES=2,1 makes device 0 not visible and enumerates device 2 before device 1", accepts UUIDs and MIG instance names, and cudaGetDeviceCount() "includes only the visible devices" (CUDA environment variables). Below it, a container only sees the device files it was given, and its device cgroup decides which it may open (section 9, cases 3 and 4).
nvidia-persistenced.cudaMemPrefetchAsync) or use device memory.CUDA_VISIBLE_DEVICES and the code also indexes devices by local rank, or CUDA_DEVICE_ORDER differs from nvidia-smi's PCI order.nvidia-smi -q -d MEMORY,ECC; dmesg | grep -i "NVRM: Xid"; systemctl status nvidia-persistenced; ls -l /dev/nvidia*
| Belief | What is true |
|---|---|
| "A VM is slow because it emulates the CPU." | Guest code runs directly on the CPU; only exits cost (about 0.92 µs each here). Interrupts, idle and device access are where the time goes (sections 2, 5). |
| "GPU passthrough adds overhead to every kernel." | The GPU's registers and DMA go through stage-2 tables and the IOMMU, not through the hypervisor; launches do not exit. The costs are pinned memory, topology and peer-to-peer (section 7). |
| "Containers isolate GPUs like VMs do." | A container sees device files the host passed in; the GPU is shared with whatever else uses it unless MIG or exclusive scheduling separates them (section 8). |
| "Time-sliced GPUs give each pod a fair share." | "A request for more than one time-sliced GPU does not guarantee that the pod receives access to a proportional amount of GPU compute power", and there is no memory or fault isolation (section 8). |
"nvidia-smi shows CUDA 13.0, so I cannot run a CUDA 13.4 build." | That is the newest CUDA the driver was released with; minor version compatibility runs any 13.x build with SASS for the GPU (section 10). |
| "The CUDA toolkit in my image includes the driver." | The image has the runtime and a stub libcuda; the real driver comes from the host (section 9, cases 1 and 2). |
"torch.cuda.is_available() is False, so there is no GPU." | It is False with no driver library, with no device files, and with a forbidden device cgroup: four different fixes (section 9). |
| "Steal time is zero, so nothing else runs on my host." | Only if the hypervisor reports it; this one does not (section 5). |
wfi, hlt), accessing interrupt-controller or timer registers that are not virtualized in hardware, hypercalls, and host interrupts. Guest system calls and page faults do not exit with hardware virtualization and nested paging. About 0.9 µs per exit was measured on an M1 Pro's hypervisor.cudaMalloc on the first call in a process.libcuda.so.1 (the user-mode driver, from the host), which initialises: opens /dev/nvidiactl, checks versions with the kernel module, allocates RM objects (client, device, subdevice) by ioctl, opens /dev/nvidiaN, creates a context with its channels and maps them; then the allocation itself is an RM allocation ioctl plus a mapping into the GPU's address space. Later kernel launches write into mapped command buffers and ring a doorbell without a system call.libcuda.so.1 present (the NVIDIA container runtime or CDI injects it; without it the error is "driver version is insufficient"), do /dev/nvidiactl and /dev/nvidiaN exist in the container, may the container open them (device cgroup: EPERM), is CUDA_VISIBLE_DEVICES empty or wrong, and does the host see the GPU (nvidia-smi, dmesg Xid). strace -f -e openat,ioctl shows which step fails.cuda-compat-13-4 in the image and put /usr/local/cuda/compat on LD_LIBRARY_PATH: NVIDIA's matrix marks that combination compatible. On consumer GPUs, use a 12.x build or upgrade the driver.Links checked on 5 October 2026; GSP and open-module README links added 24 October 2026. Times are estimates for the part worth reading. Suggested order: this page's Reading tab with OSTEP's Appendix B beside it; section 9's trace explorer; then the KVM and VFIO documentation for the virtualization half, or NVIDIA's open kernel modules and the CUDA compatibility guide for the GPU half, depending on what you are debugging.
Section 9 is this page's intuition; the root measured the costs this page builds on (system call 0.316 µs, context switch 1.33 µs, TLB miss 7.6 ns).
On the root page, the cases that meet this page: "CUDA out of memory (from source; not run here: no GPU)" and "A worker hangs forever: fork while another thread holds a lock" (the same reason CUDA must not be initialised before fork).
On the root page: the CPU training job traced; the "language to kernel" view this page extends below the CUDA runtime.
The system call mechanism, ioctl as a system call, file descriptors for devices, and multiprocessing start methods (CUDA and fork).
Context switches and cross-CPU wake-ups measured (section 5 here explains the VM's share), CPU accounting and steal time.
Page tables, the TLB and huge pages (the first dimension of section 4's walk), pinned memory and memlock for GPU copies.
PyTorch's CUDA caching allocator: what sits on top of section 11's GPU memory.
Futexes and wake-ups (section 5's cost in practice), NCCL's progress threads.
The virtio disk of section 6 measured from the storage side, and GPUDirect Storage.
Containers against VMs, the device cgroup that returned EPERM in section 9, GPU containers (NVIDIA container toolkit, CDI), and sandboxes built on microVMs (gVisor, Firecracker).
Writing kernels; its Compiler explorer shows real SASS and PTX for four GPU generations, built with the same CUDA 13.4 image used here.
The chips, memory and interconnects (PCIe, NVLink) under this page's driver and IOMMU.
Kubernetes GPU scheduling, the device plugin, time slicing and MIG in clusters.
The dispatcher and CUDA backend at the top of section 9's stack.
NCCL and the collectives whose peer-to-peer paths section 7 is about.
GPU health checks (DCGM levels, the action for each Xid) and recovery at scale.
Running untrusted code: where microVMs (section 1's KVM) are the sandbox.
Limited direct execution for a whole OS, shadow page tables, the information gap. The textbook view of sections 1 to 4.
A complete virtual machine monitor in about a hundred lines of C; run it on any Linux machine with /dev/kvm.
Every ioctl and exit reason; read KVM_RUN and struct kvm_run first.
Why device assignment needs the IOMMU, groups, and the example of section 7.
The formal requirement for trap-and-emulate virtualization.
The seventeen x86 instructions that broke it.
Two-dimensional page walks and the caches that make them affordable.
Virtqueues, notifications and the event index (section 6); Russell's 2008 paper is the short version.
A production hypervisor: KVM-based, with device work moved to dedicated cards.
A minimal KVM-based VMM for serverless and sandboxes.
The exit loop, WFI handling and vCPU kicks of section 5, in about 1,300 lines.
How KVM trades CPU for wake-up latency.
Start at kernel-open/nvidia/nv.c (file operations, ioctl), then nvidia-uvm/uvm_channel.c (work submission).
Backward, minor version and forward compatibility, with the matrix behind section 10's checker.
Cubins, fatbins, binary and PTX compatibility, JIT and the compute cache.
Page faults, migration, HMM and hardware coherence.
Concepts, profiles, placements, and the streams, MPS and MIG comparison.
How contexts are time-sliced and how MPS merges them.
Sharing GPUs in Kubernetes and what it does not isolate.
IOMMU, ACS, ATS, virtual topologies and GPUDirect RDMA.
Why the first CUDA call can take seconds; how the driver reports GPU faults.
Which GPUs run the resource manager as firmware, how to check and disable it, and what the open modules need.
NVIDIA_VISIBLE_DEVICES, NVIDIA_DRIVER_CAPABILITIES and NVIDIA_REQUIRE_CUDA.